1 Chapter 2 Elementary Programming 2 Introducing Programming











































![Syntax Errors public class Show. Syntax. Errors { public static void main(String[] args) { Syntax Errors public class Show. Syntax. Errors { public static void main(String[] args) {](https://slidetodoc.com/presentation_image/36d23278b47246a823d49f4b48b09c1b/image-44.jpg)
![Runtime Errors public class Show. Runtime. Errors { public static void main(String[] args) { Runtime Errors public class Show. Runtime. Errors { public static void main(String[] args) {](https://slidetodoc.com/presentation_image/36d23278b47246a823d49f4b48b09c1b/image-45.jpg)



- Slides: 48

1 Chapter 2 Elementary Programming

2 Introducing Programming with an Example Listing 2. 1 Computing the Area of a Circle This program computes the area of the circle. Compute. Area Run IMPORTANT NOTE: To enable the buttons, you must download the entire slide file slide. zip and unzip the files into a directory (e. g. , c: slide).

3 animation Trace a Program Execution public class Compute. Area { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius = 20; // Compute area = radius * 3. 14159; // Display results System. out. println("The area for the circle of radius " + radius + " is " + area); } } allocate memory for radius no value

4 animation Trace a Program Execution public class Compute. Area { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius = 20; // Compute area = radius * 3. 14159; // Display results System. out. println("The area for the circle of radius " + radius + " is " + area); } } memory radius no value area no value allocate memory for area

5 animation Trace a Program Execution public class Compute. Area { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius = 20; // Compute area = radius * 3. 14159; // Display results System. out. println("The area for the circle of radius " + radius + " is " + area); } } assign 20 to radius area 20 no value

6 animation Trace a Program Execution public class Compute. Area { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius = 20; // Compute area = radius * 3. 14159; // Display results System. out. println("The area for the circle of radius " + radius + " is " + area); } } memory radius area 20 1256. 636 compute area and assign it to variable area

7 animation Trace a Program Execution public class Compute. Area { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius = 20; // Compute area = radius * 3. 14159; // Display results System. out. println("The area for the circle of radius " + radius + " is " + area); } } memory radius area 20 1256. 636 print a message to the console

Identifier 8 • sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($). • cannot start with a digit. ▫ An identifier cannot be a reserved word. (See Appendix A, “Java Keywords, ” for a list of reserved words). • An identifier cannot be true, false, or null. • An identifier can be of any length.

9 Variables // Compute the first area radius = 1. 0; area = radius * 3. 14159; System. out. println("The area is “ + area + " for radius "+radius); // Compute the second area radius = 2. 0; area = radius * 3. 14159; System. out. println("The area is “ + area + " for radius "+radius);

10 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;

11 Assignment Statements x = 1; // Assign 1 to x; radius = 1. 0; // Assign 1. 0 to radius; a = 'A'; // Assign 'A' to a;

12 Declaring and Initializing in One Step • int x = 1; • double d = 1. 4;

13 Constants final datatype CONSTANTNAME = VALUE; final double PI = 3. 14159; final int SIZE = 3; Must be declared at initialization.

14 Numerical Data Types

Numeric Operators 15

Integer Division +, -, *, /, and % 5 / 2 yields an integer 2. 5. 0 / 2 yields a double value 2. 5 will be truncated (not rounded) if assigned to an integer 5 % 2 yields 1 (the remainder of the division) 16

Problem: Displaying Time Write a program that obtains hours and minutes from seconds. Display. Time Run 17

18 Number Literals A literal is a constant value that appears directly in the program. For example, 34, 1, 000, and 5. 0 are literals in the following statements: int i = 34; long x = 1000000; double d = 5. 0;

19 Arithmetic Expressions is translated to (3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y) Remember: Order of operations!

20 Shortcut Assignment Operators Operator Example Equivalent += i += 8 i = i + 8 -= f -= 8. 0 f = f - 8. 0 *= i *= 8 i = i * 8 /= i /= 8 i = i / 8 %= i %= 8 i = i % 8

21 Increment / Decrement ++var var++ preincrement postincrement --var var-- predecrement postdecrement What is the difference between ++var and var++?

22 Numeric Type Conversion Consider the following statements: byte i = 100; long k = i * 3 + 4; double d = i * 3. 1 + k / 2;

23 Conversion Rules When performing a binary operation involving two operands of different types, Java automatically converts the operand based on the following rules: 1. If one of the operands is double, the other is converted into double. 2. Otherwise, if one of the operands is float, the other is converted into float. 3. Otherwise, if one of the operands is long, the other is converted into long. 4. Otherwise, both operands are converted into int.

24 Type Conversion • Widening: convert numeric type of smaller range to type of larger range ▫ Done implicitly • Narrowing: convert numeric type of larger range to type of smaller range ▫ May result in overflow ▫ Explicit casts

Type Casting Implicit casting double d = 3; (type widening) Explicit casting int i = (int)3. 0; (type narrowing) int i = (int)3. 9; (truncate decimal) What is wrong? int x = 5 / 2. 0; 25

26 Character Data Type Four hexadecimal digits. char letter = 'A'; (ASCII) char num. Char = '4'; (ASCII) char letter = 'u 0041'; (Unicode) char num. Char = 'u 0034'; (Unicode) NOTE: Increment (decrement) operators on char variables get the next (preceding) Unicode character. What character is printed by these statements? char ch = 'a'; System. out. println(++ch);

27 Escape Sequences for Special Characters Description Escape Sequence Unicode Backspace b u 0008 Tab t u 0009 Linefeed n u 000 A Carriage return r u 000 D Backslash \ u 005 C Single Quote ' u 0027 Double Quote " u 0022

Appendix B: ASCII Character Set 28 ASCII Character Set is a subset of the Unicode from u 0000 to u 007 f

Casting between char and Numeric Types 29 int i = 'a'; // Same as int i = (int)'a'; char c = 97; // Same as char c = (char)97; Unicode representation of characters

The String Type String message = "Welcome to Java"; Compare char and String: Øchar: single character String: several characters Øchar literal ‘a’ ØString literal “A” Øchar is a primitive data type String is predefined class (reference type) More on classes later! 30

String Concatenation (+ operator) 31 // Three strings are concatenated String message = "Welcome " + "to " + "Java"; // String Chapter is concatenated with number 2 String s = "Chapter" + 2; // s becomes Chapter 2 // String Supplement is concatenated with character B String s 1 = "Supplement" + 'B'; // s becomes Supplement. B

32 Problem: Monetary Units This program lets the user enter the amount in decimal representing dollars and cents and output a report listing the monetary equivalent in single dollars, quarters, dimes, nickels, and pennies. Your program should report maximum number of dollars, then the maximum number of quarters, and so on, in this order. Compute. Change Run

33 Trace Compute. Change Suppose amount is 11. 56 int remaining. Amount = (int)(amount * 100); // Find the number of one dollars int number. Of. One. Dollars = remaining. Amount / 100; remaining. Amount = remaining. Amount % 100; // Find the number of quarters in the remaining amount int number. Of. Quarters = remaining. Amount / 25; remaining. Amount = remaining. Amount % 25; // Find the number of dimes in the remaining amount int number. Of. Dimes = remaining. Amount / 10; remaining. Amount = remaining. Amount % 10; // Find the number of nickels in the remaining amount int number. Of. Nickels = remaining. Amount / 5; remaining. Amount = remaining. Amount % 5; // Find the number of pennies in the remaining amount int number. Of. Pennies = remaining. Amount; remaining. Amo unt 1156 remaining. Amount initialized

34 animation Trace Compute. Change Suppose amount is 11. 56 int remaining. Amount = (int)(amount * 100); // Find the number of one dollars int number. Of. One. Dollars = remaining. Amount / 100; remaining. Amount = remaining. Amount % 100; // Find the number of quarters in the remaining amount int number. Of. Quarters = remaining. Amount / 25; remaining. Amount = remaining. Amount % 25; // Find the number of dimes in the remaining amount int number. Of. Dimes = remaining. Amount / 10; remaining. Amount = remaining. Amount % 10; // Find the number of nickels in the remaining amount int number. Of. Nickels = remaining. Amount / 5; remaining. Amount = remaining. Amount % 5; // Find the number of pennies in the remaining amount int number. Of. Pennies = remaining. Amount; remaining. Amo unt number. Of. One. Dol lars 1156 11 number. Of. One. Dolla rs assigned

35 animation Trace Compute. Change Suppose amount is 11. 56 int remaining. Amount = (int)(amount * 100); // Find the number of one dollars int number. Of. One. Dollars = remaining. Amount / 100; remaining. Amount = remaining. Amount % 100; // Find the number of quarters in the remaining amount int number. Of. Quarters = remaining. Amount / 25; remaining. Amount = remaining. Amount % 25; // Find the number of dimes in the remaining amount int number. Of. Dimes = remaining. Amount / 10; remaining. Amount = remaining. Amount % 10; // Find the number of nickels in the remaining amount int number. Of. Nickels = remaining. Amount / 5; remaining. Amount = remaining. Amount % 5; // Find the number of pennies in the remaining amount int number. Of. Pennies = remaining. Amount; remaining. Amo unt number. Of. One. Dol lars remaining. Amount updated 56 11

36 animation Trace Compute. Change Suppose amount is 11. 56 int remaining. Amount = (int)(amount * 100); // Find the number of one dollars int number. Of. One. Dollars = remaining. Amount / 100; remaining. Amount = remaining. Amount % 100; // Find the number of quarters in the remaining amount int number. Of. Quarters = remaining. Amount / 25; remaining. Amount = remaining. Amount % 25; // Find the number of dimes in the remaining amount int number. Of. Dimes = remaining. Amount / 10; remaining. Amount = remaining. Amount % 10; // Find the number of nickels in the remaining amount int number. Of. Nickels = remaining. Amount / 5; remaining. Amount = remaining. Amount % 5; // Find the number of pennies in the remaining amount int number. Of. Pennies = remaining. Amount; remaining. Amo unt number. Of. One. Dol lars 56 number. Of. One. Qua rters 2 11 number. Of. One. Quart ers assigned

37 animation Trace Compute. Change Suppose amount is 11. 56 int remaining. Amount = (int)(amount * 100); // Find the number of one dollars int number. Of. One. Dollars = remaining. Amount / 100; remaining. Amount = remaining. Amount % 100; // Find the number of quarters in the remaining amount int number. Of. Quarters = remaining. Amount / 25; remaining. Amount = remaining. Amount % 25; // Find the number of dimes in the remaining amount int number. Of. Dimes = remaining. Amount / 10; remaining. Amount = remaining. Amount % 10; // Find the number of nickels in the remaining amount int number. Of. Nickels = remaining. Amount / 5; remaining. Amount = remaining. Amount % 5; // Find the number of pennies in the remaining amount int number. Of. Pennies = remaining. Amount; remaining. Amo unt number. Of. One. Dol lars number. Of. Quart ers remaining. Amount updated 6 11 2

38 Problem: Displaying Current Time Write a program that displays current time in GMT in the format hour: minute: second such as 1: 45: 19. The current. Time. Millis method in the System class returns the current time in milliseconds since the midnight, January 1, 1970 GMT. (1970 was the year when the Unix operating system was formally introduced. ) You can use this method to obtain the current time, and then compute the current second, minute, and hour as follows. Show. Current. Time Run

Programming Style and Documentation • Appropriate Comments • Naming Conventions • Proper Indentation and Spacing Lines • Block Styles Java is case sensitive! 39

40 Appropriate Comments Summary before program: ØWhat the program does ØYour name ØClass Section ØInstructor ØDate

41 Naming Conventions • Choose meaningful and descriptive names. • Variables and method names: ▫ Lowercase for first word ▫ Camelcase if several words • Class names: ▫ Capitalize first letter of each word • Constants: ▫ Capitalize all letters, use underscores to connect words.

42 Block Styles Chose next-line or end-of-line style for braces.

43 Programming Errors • Syntax Errors ▫ Detected by the compiler • Runtime Errors ▫ Causes the program to abort • Logic Errors ▫ Produces incorrect result
![Syntax Errors public class Show Syntax Errors public static void mainString args Syntax Errors public class Show. Syntax. Errors { public static void main(String[] args) {](https://slidetodoc.com/presentation_image/36d23278b47246a823d49f4b48b09c1b/image-44.jpg)
Syntax Errors public class Show. Syntax. Errors { public static void main(String[] args) { i = 30; System. out. println(i + 4); } } 44
![Runtime Errors public class Show Runtime Errors public static void mainString args Runtime Errors public class Show. Runtime. Errors { public static void main(String[] args) {](https://slidetodoc.com/presentation_image/36d23278b47246a823d49f4b48b09c1b/image-45.jpg)
Runtime Errors public class Show. Runtime. Errors { public static void main(String[] args) { int i = 1 / 0; } } 45

Logic Errors public class Show. Logic. Errors { // Determine if a number is between 1 and 100 inclusively public static void main(String[] args) { // Prompt the user to enter a number String input = JOption. Pane. show. Input. Dialog(null, "Please enter an integer: ", "Show. Logic. Errors", JOption. Pane. QUESTION_MESSAGE); int number = Integer. parse. Int(input); // Display the result System. out. println("The number is between 1 and 100, " + "inclusively? " + ((1 < number) && (number < 100))); System. exit(0); } } 46

Debugging Logic errors are called bugs. Debugging: process of finding and correcting. Narrow down segment of code where the bug is located: Ø hand-trace the program Ø insert print statements to see what’s happening Ø debugger utility (part of IDE) 47

Debugger A debugger can • Execute a single statement at a time. • Trace into or stepping over a method. • Set breakpoints. • Display variables. • Display call stack. • Modify variables. 48