Download presentation
Presentation is loading. Please wait.
Published byBennett Brown Modified over 9 years ago
1
Java Overview CS2336: Computer Science II1
2
First Program public class HelloWorld { public static void main(String args[]) { System.out.println("Hello World"); } CS2336: Computer Science II2
3
Compiling and Running HelloWorld.java javac HelloWorld.java java HelloWorld HelloWorld.class compile run bytecode source code CS2336: Computer Science II3
4
Java bytecode and interpreter bytecode is an intermediate representation of the program (class). The Java interpreter starts up a new “ Virtual Machine ”. The VM starts executing the users class by running it ’ s main() method. CS2336: Computer Science II4
5
Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } no value radius allocate memory for radius animation CS2336: Computer Science II5
6
Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } no value radius memory no value area allocate memory for area animation CS2336: Computer Science II6
7
Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } 20 radius no value area assign 20 to radius animation CS2336: Computer Science II7
8
Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } 20 radius memory 1256.636 area compute area and assign it to variable area animation CS2336: Computer Science II8
9
Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } 20 radius memory 1256.636 area print a message to the console animation CS2336: Computer Science II9
10
Reading Input from the Console Create a Scanner object – Scanner input = new Scanner(System.in); 2. Use the methods next(), nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble(), or nextBoolean() to obtain to a string, byte, short, int, long, float, double, or boolean value. For example, – System.out.print("Enter a double value: "); – Scanner input = new Scanner(System.in); – double d = input.nextDouble(); CS2336: Computer Science II10
11
import java.util.Scanner; // Scanner is in the java.util package public class ComputeAreaWithConsoleInput { public static void main(String[] args) { // Create a Scanner object Scanner input = new Scanner(System.in); // Prompt the user to enter a radius System.out.print("Enter a number for radius: "); double radius = input.nextDouble(); // Compute area double area = radius * radius * 3.14159; // Display result System.out.println("The area for the circle of radius " + radius + " is " + area); } CS2336: Computer Science II11
12
Declaring Variables int x; // Declare x to be an // integer variable; double radius; // Declare radius to // be a double variable; char a; // Declare a to be a // character variable; CS2336: Computer Science II12
13
Assignment Statements x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a; CS2336: Computer Science II13
14
Declaring and Initializing in One Step int x = 1; double d = 1.4; CS2336: Computer Science II14
15
Constants final datatype CONSTANTNAME = VALUE; final double PI = 3.14159; final int SIZE = 3; CS2336: Computer Science II15
16
Numeric Operators CS2336: Computer Science II16
17
Integer Division +, -, *, /, and % 5 / 2 yields an integer 2. 5.0 / 2 yields a double value 2.5 5 % 2 yields 1 (the remainder of the division) CS2336: Computer Science II17
18
Quiz1-1 Suppose today is Saturday and you and your friends are going to meet in 10 days. What day is in 10 days? CS2336: Computer Science II18
19
Answer CS2336: Computer Science II19
20
Quiz1-2 Write a program that obtains hours and minutes from seconds. CS2336: Computer Science II20
21
Shortcut Assignment Operators OperatorExampleEquivalent +=i += 8i = i + 8 -=f -= 8.0f = f - 8.0 *=i *= 8i = i * 8 /=i /= 8i = i / 8 %=i %= 8i = i % 8 CS2336: Computer Science II21
22
Increment and Decrement Operators OperatorNameDescription ++varpreincrementThe expression (++var) increments var by 1 and evaluates to the new value in var after the increment. var++postincrementThe expression (var++) evaluates to the original value in var and increments var by 1. --varpredecrementThe expression (--var) decrements var by 1 and evaluates to the new value in var after the decrement. var--postdecrement The expression (var--) evaluates to the original value in var and decrements var by 1. CS2336: Computer Science II22
23
Increment and Decrement Operators, cont. CS2336: Computer Science II23
24
Increment and Decrement Operators, cont. Using increment and decrement operators makes expressions short, but it also makes them complex and difficult to read. Avoid using these operators in expressions that modify multiple variables, or the same variable for multiple times such as this: int k = ++i + i. CS2336: Computer Science II 24
25
The String Type The char type only represents one character. To represent a string of characters, use the data type called String. For example, String message = "Welcome to Java"; String is actually a predefined class in the Java library. The String type is not a primitive type. It is known as a reference type. Any Java class can be used as a reference type for a variable. Reference data types will be thoroughly discussed in Chapter 7, “Objects and Classes.” CS2336: Computer Science II25
26
String Concatenation // Three strings are concatenated String message = "Welcome " + "to " + "Java"; // String Chapter is concatenated with number 2 String s = "Chapter" + 2; // s becomes Chapter2 // String Supplement is concatenated with character B String s1 = "Supplement" + 'B'; // s1 becomes SupplementB CS2336: Computer Science II26
27
Programming Style and Documentation Appropriate Comments Naming Conventions Proper Indentation and Spacing Lines Block Styles CS2336: Computer Science II27
28
Appropriate Comments Include a summary at the beginning of the program to explain what the program does, its key features, its supporting data structures, and any unique techniques it uses. Include your name, class section, instructor, date, and a brief description at the beginning of the program. CS2336: Computer Science II28
29
Naming Conventions Choose meaningful and descriptive names. Variables and method names: – Use lowercase. If the name consists of several words, concatenate all in one, use lowercase for the first word, and capitalize the first letter of each subsequent word in the name. For example, the variables radius and area, and the method computeArea. CS2336: Computer Science II29
30
Naming Conventions, cont. Class names: – Capitalize the first letter of each word in the name. For example, the class name ComputeArea. Constants: – Capitalize all letters in constants, and use underscores to connect words. For example, the constant PI and MAX_VALUE CS2336: Computer Science II30
31
Proper Indentation and Spacing Indentation – Indent two spaces. Spacing – Use blank line to separate segments of the code. CS2336: Computer Science II31
32
Block Styles Use end-of-line style for braces. CS2336: Computer Science II32
33
Programming Errors Syntax Errors – Detected by the compiler Runtime Errors – Causes the program to abort Logic Errors – Produces incorrect result CS2336: Computer Science II33
34
Syntax Errors public class ShowSyntaxErrors { public static void main(String[] args) { i = 30; System.out.println(i + 4); } CS2336: Computer Science II34
35
Runtime Errors public class ShowRuntimeErrors { public static void main(String[] args) { int i = 1 / 0; } CS2336: Computer Science II35
36
Debugging Logic errors are called bugs. The process of finding and correcting errors is called debugging. A common approach to debugging is to use a combination of methods to narrow down to the part of the program where the bug is located. You can hand-trace the program (i.e., catch errors by reading the program), or you can insert print statements in order to show the values of the variables or the execution flow of the program. This approach might work for a short, simple program. But for a large, complex program, the most effective approach for debugging is to use a debugger utility. CS2336: Computer Science II36
37
Debugger Debugger is a program that facilitates debugging. You can use a debugger to Execute a single statement at a time. Trace into or stepping over a method. Set breakpoints. Display variables. Display call stack. Modify variables. CS2336: Computer Science II37
38
Converting Strings to Integers The input returned from the input dialog box is a string. If you enter a numeric value such as 123, it returns “123”. To obtain the input as a number, you have to convert a string into a number. To convert a string into an int value, you can use the static parseInt method in the Integer class as follows: int intValue = Integer.parseInt(intString); where intString is a numeric string such as “123”. CS2336: Computer Science II38
39
Converting Strings to Doubles To convert a string into a double value, you can use the static parseDouble method in the Double class as follows: double doubleValue =Double.parseDouble(doubleString); where doubleString is a numeric string such as “123.45”. CS2336: Computer Science II39
40
Motivations If you assigned a negative value for radius in ComputeArea.java, the program would print an invalid result. If the radius is negative, you don't want the program to compute the area. How can you deal with this situation? CS2336: Computer Science II40
41
import java.util.Scanner; // Scanner is in the java.util package public class ComputeAreaWithConsoleInput { public static void main(String[] args) { // Create a Scanner object Scanner input = new Scanner(System.in); // Prompt the user to enter a radius System.out.print("Enter a number for radius: "); double radius = input.nextDouble(); // Compute area double area = radius * radius * 3.14159; // Display result System.out.println("The area for the circle of radius " + radius + " is " + area); } CS2336: Computer Science II41
42
Comparison Operators The boolean Type and Operators Operator Name < less than <= less than or equal to > greater than >= greater than or equal to == equal to != not equal to boolean b = (1 > 2); CS2336: Computer Science II42
43
Control Structures More of what you expect: conditional: if, if else, switch loop: while, for, do break and continue (but a little different than with C/C++). CS2336: Computer Science II43
44
One-way if Statements if (boolean-expression) { statement(s); } if (radius >= 0) { area = radius * radius * PI; System.out.println("The area" + " for the circle of radius " + radius + " is " + area); } CS2336: Computer Science II44
45
Note CS2336: Computer Science II45
46
Problem: Guessing Birthday The program can guess your birth date. Run to see how it works. CS2336: Computer Science II46
47
The Two-way if Statement if (boolean-expression) { statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case; } CS2336: Computer Science II47
48
if...else Example if (radius >= 0) { area = radius * radius * 3.14159; System.out.println("The area for the “ + “ circle of radius " + radius + " is " + area); } else { System.out.println("Negative input"); } CS2336: Computer Science II48
49
Multiple Alternative if Statements CS2336: Computer Science II49
50
Trace if-else statement if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; Suppose score is 70.0The condition is false animation CS2336: Computer Science II50
51
Trace if-else statement if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; Suppose score is 70.0The condition is false animation CS2336: Computer Science II51
52
Trace if-else statement if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; Suppose score is 70.0The condition is true animation CS2336: Computer Science II52
53
Trace if-else statement if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; Suppose score is 70.0grade is C animation CS2336: Computer Science II53
54
Trace if-else statement if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; Suppose score is 70.0Exit the if statement animation CS2336: Computer Science II54
55
Note The else clause matches the most recent if clause in the same block. CS2336: Computer Science II55
56
Note, cont. Nothing is printed from the preceding statement. To force the else clause to match the first if clause, you must add a pair of braces: int i = 1; int j = 2; int k = 3; if (i > j) { if (i > k) System.out.println("A"); } else System.out.println("B"); This statement prints B. CS2336: Computer Science II56
57
Common Errors Adding a semicolon at the end of an if clause is a common mistake. if (radius >= 0); { area = radius*radius*PI; System.out.println( "The area for the circle of radius " + radius + " is " + area); } This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error. This error often occurs when you use the next-line block style. Wrong CS2336: Computer Science II57
58
TIP CS2336: Computer Science II58
59
CAUTION CS2336: Computer Science II59
60
Acknowledgement The original authors of these slides are the authors of the textbook. The instructor made necessary modifications, with permissions from the authors. CS2336: Computer Science II
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.