Chapter 2: Elementary Programming CS1: Java Programming Colorado State University Original slides by Daniel Liang Modified slides by Chris Wilcox Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from this chapter, you will learn how to solve practical problems programmatically. Through these problems, you will learn Java primitive data types and related subjects, such as variables, constants, data types, operators, expressions, and input and output. 1 2 Objectives To write Java programs to perform simple computations ( 2.2). To obtain input from the console using the Scanner class ( 2.3). To use identifiers to name variables, constants, methods, and classes ( 2.4). To use variables to store data ( 2.5 2.6). To program with assignment statements and assignment expressions ( 2.6). To use constants to store permanent data ( 2.7). To name classes, methods, variables, and constants by following their naming conventions ( 2.8). To explore Java numeric primitive data types: byte, short, int, long, float, and double ( 2.9.1). To read a byte, short, int, long, float, or double value from the keyboard ( 2.9.2). To perform operations using operators +, -, *, /, and % ( 2.9.3). To perform exponent operations using Math.pow(a, b) ( 2.9.4). To write integer literals, floating-point literals, and literals in scientific notation ( 2.10). To write and evaluate numeric expressions ( 2.11). To obtain the current system time using.currenttimemillis() ( 2.12). To use augmented assignment operators ( 2.13). To distinguish between postincrement and preincrement and between postdecrement and predecrement ( 2.14). To cast the value of one type to another type ( 2.15). To describe the software development process and apply it to develop the loan payment program ( 2.16). To write a program that converts a large amount of money into smaller units ( 2.17). To avoid common errors and pitfalls in elementary programming ( 2.18). Introducing Programming with an Example Listing 2.1 Computing the Area of a Circle This program computes the area of the circle. ComputeArea Note: Clicking the green button displays the source code with interactive animation. You can also run the code in a browser. Internet connection is needed for this button. Note: Clicking the blue button runs the code from Windows. If you cannot run the buttons, see IMPORTANT NOTE: If you cannot run the buttons, see www.cs.armstrong.edu/liang/javaslidenote.doc. 3 4 animation Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(string[] args) { double radius; double area; radius allocate memory for radius no value animation Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(string[] args) { double radius; double area; radius area memory no value no value // Assign a radius radius = 20; // Compute area // Display results.out.println("the area for the circle of radius " + radius + " is " + area); // Assign a radius radius = 20; // Compute area // Display results.out.println("the area for the circle of radius " + radius + " is " + area); allocate memory for area 5 6 1
animation Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(string[] args) { double radius; double area; radius area assign 20 to radius 20 no value animation Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(string[] args) { double radius; double area; radius area memory 20 1256.636 // Assign a radius radius = 20; // Compute area // Display results.out.println("the area for the circle of radius " + radius + " is " + area); // Assign a radius radius = 20; // Compute area // Display results.out.println("the area for the circle of radius " + radius + " is " + area); compute area and assign it to variable area 7 8 animation Trace a Program Execution Reading Input from the Console public class ComputeArea { /** Main method */ public static void main(string[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area // Display results.out.println("the area for the circle of radius " + radius + " is " + area); radius area memory 20 1256.636 print a message to the console 1. Create a Scanner object Scanner input = new Scanner(.in); 2. Use the method nextdouble() to obtain to a double value. For example,.out.print("enter a double value: "); Scanner input = new Scanner(.in); double d = input.nextdouble(); ComputeAreaWithConsoleInput ComputeAverage 9 10 Identifiers An identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($). An identifier must start with a letter, an underscore (_), or a dollar sign ($). It 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. Variables // Compute the first area radius = 1.0;.out.println("The area is + area + " for radius "+radius); // Compute the second area radius = 2.0;.out.println("The area is + area + " for radius "+radius); 11 12 2
int x; Declaring Variables // 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; Assignment Statements x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a; 13 14 Declaring and Initializing in One Step Named Constants final datatype CONSTANTNAME = VALUE; int x = 1; double d = 1.4; final double PI = 3.14159; final int SIZE = 3; 15 16 Naming Conventions Naming Conventions, cont. 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. 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 17 18 3
Numerical Data Types Name Range Storage Size byte 2 7 to 2 7 1 (-128 to 127) 8-bit signed short 2 15 to 2 15 1 (-32768 to 32767) 16-bit signed int 2 31 to 2 31 1 (-2147483648 to 2147483647) 32-bit signed long 2 63 to 2 63 1 64-bit signed (i.e., -9223372036854775808 to 9223372036854775807) float Negative range: 32-bit IEEE 754-3.4028235E+38 to -1.4E-45 Positive range: 1.4E-45 to 3.4028235E+38 double Negative range: 64-bit IEEE 754-1.7976931348623157E+308 to -4.9E-324 Positive range: 4.9E-324 to 1.7976931348623157E+308 Reading Numbers from the Keyboard Scanner input = new Scanner(.in); int value = input.nextint(); Method nextbyte() nextshort() nextint() nextlong() nextfloat() Description reads an integer of the byte type. reads an integer of the short type. reads an integer of the int type. reads an integer of the long type. reads a number of the float type. nextdouble() reads a number of the double type. 19 20 Numeric Operators Integer Division Name Meaning Example Result +, -, *, /, and % + Addition 34 + 1 35 - Subtraction 34.0 0.1 33.9 5 / 2 yields an integer 2. * Multiplication 300 * 30 9000 5.0 / 2 yields a double value 2.5 / Division 1.0 / 2.0 0.5 % Remainder 20 % 3 2 5 % 2 yields 1 (the remainder of the division) 21 22 Remainder Operator Remainder is very useful in programming. For example, an even number % 2 is always 0 and an odd number % 2 is always 1. So you can use this property to determine whether a number is even or odd. Suppose today is Saturday and you and your friends are going to meet in 10 days. What day is in 10 days? You can find that day is Tuesday using the following expression: Problem: Displaying Time Write a program that obtains minutes and remaining seconds from seconds. Saturday is the 6 th day in a week A week has 7 days (6 + 10) % 7 is 2 After 10 days The 2 nd day in a week is Tuesday DisplayTime 23 24 4
NOTE Calculations involving floating-point numbers are approximated because these numbers are not stored with complete accuracy. For example,.out.println(1.0-0.1-0.1-0.1-0.1-0.1); displays 0.5000000000000001, not 0.5, and.out.println(1.0-0.9); displays 0.09999999999999998, not 0.1. Integers are stored precisely. Therefore, calculations with integers yield a precise integer result. Exponent Operations.out.println(Math.pow(2, 3)); // Displays 8.0.out.println(Math.pow(4, 0.5)); // Displays 2.0.out.println(Math.pow(2.5, 2)); // Displays 6.25.out.println(Math.pow(2.5, -2)); // Displays 0.16 25 26 Number Literals A literal is a constant value that appears directly in the program. For example, 34, 1,000,000, and 5.0 are literals in the following statements: int i = 34; long x = 1000000; double d = 5.0; 27 Integer Literals An integer literal can be assigned to an integer variable as long as it can fit into the variable. A compilation error would occur if the literal were too large for the variable to hold. For example, the statement byte b = 1000 would cause a compilation error, because 1000 cannot be stored in a variable of the byte type. An integer literal is assumed to be of the int type, whose value is between -2 31 (-2147483648) to 2 31 1 (2147483647). To denote an integer literal of the long type, append it with the letter L or l. L is preferred because l (lowercase L) can easily be confused with 1 (the digit one). 28 Floating-Point Literals Floating-point literals are written with a decimal point. By default, a floating-point literal is treated as a double type value. For example, 5.0 is considered a double value, not a float value. You can make a number a float by appending the letter f or F, and make a number a double by appending the letter d or D. For example, you can use 100.2f or 100.2F for a float number, and 100.2d or 100.2D for a double number. double vs. float The double type values are more accurate than the float type values. For example,.out.println("1.0 / 3.0 is " + 1.0 / 3.0); displays 1.0 / 3.0 is 0.3333333333333333 16 digits.out.println("1.0f / 3.0F is " + 1.0F / 3.0F); displays 1.0F / 3.0F is 0.33333334 7 d igits 29 30 5
Scientific Notation Floating-point literals can also be specified in scientific notation, for example, 1.23456e+2, same as 1.23456e2, is equivalent to 123.456, and 1.23456e-2 is equivalent to 0.0123456. E (or e) represents an exponent and it can be either in lowercase or uppercase. Arithmetic Expressions 3 + 4x 10( y - 5)( a + b + c) 4 9 + x - + 9( + ) 5 x x y is translated to (3+4*x)/5 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y) 31 32 How to Evaluate an Expression Though Java has its own way to evaluate an expression behind the scene, the result of a Java expression and its corresponding arithmetic expression are the same. Therefore, you can safely apply the arithmetic rule for evaluating a Java expression. 3 + 4 * 4 + 5 * (4 + 3) - 1 3 + 4 * 4 + 5 * 7 1 3 + 16 + 5 * 7 1 3 + 16 + 35 1 19 + 35 1 54-1 53 (1) inside parentheses first (2) multiplication (3) multiplication (4) addition (5) addition (6) subtraction Problem: Converting Temperatures Write a program that converts a Fahrenheit degree to Celsius using the formula: 5 celsius = ( 9 )( fahrenheit - 32) Note: you have to write celsius = (5.0 / 9) * (fahrenheit 32) FahrenheitToCelsius 33 34 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 currenttimemillis method in the 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. Augmented Assignment Operators Unix Epoch 01-01-1970 00:00:00 GMT Elapsed time Current Time.currentTimeMills() Time ShowCurrentTime 35 36 6
Increment and Decrement Operators Increment and Decrement Operators, cont. int i = 10; Same effect as int newnum = 10 * i++; int newnum = 10 * i; i = i + 1; int i = 10; Same effect as int newnum = 10 * (++i); i = i + 1; int newnum = 10 * i; 37 38 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. Assignment Expressions and Assignment Statements Prior to Java 2, all the expressions can be used as statements. Since Java 2, only the following types of expressions can be statements: variable op= expression; // Where op is +, -, *, /, or % ++variable; variable++; --variable; variable--; 39 40 Numeric Type Conversion Consider the following statements: byte i = 100; long k = i * 3 + 4; double d = i * 3.1 + k / 2; 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. 41 42 7
Type Casting Implicit casting double d = 3; (type widening) Explicit casting int i = (int)3.0; (type narrowing) int i = (int)3.9; (Fraction part is truncated) Problem: Keeping Two Digits After Decimal Points Write a program that displays the sales tax with two digits after the decimal point. What is wrong? int x = 5 / 2.0; range increases byte, short, int, long, float, double SalesTax 43 44 Casting in an Augmented Expression Software Development Process In Java, an augmented expression of the form x1 op= x2 is implemented as x1 = (T)(x1 op x2), where T is the type for x1. Therefore, the following code is correct. int sum = 0; sum += 4.5; // sum becomes 4 after this statement sum += 4.5 is equivalent to sum = (int)(sum + 4.5). 45 46 A formal process that seeks to understand the problem and document in detail what the software system needs to do. This phase involves close interaction between users and designers. Seeks to analyze the business process in terms of data flow, and to identify the system s input and output. Most of the examples in this book are simple, and their requirements are clearly stated. In the real world, however, problems are not well defined. You need to study a problem carefully to identify its requirements. Part of the analysis entails modeling the system s behavior. The model is intended to capture the essential elements of the system and to define services to the system. 47 48 8
IPO The process of designing the system s components. Input, Process, Output This phase involves the use of many levels of abstraction to decompose the problem into manageable components, identify classes and interfaces, and establish relationships among the classes and interfaces. The essence of system analysis and design is input, process, and output. This is called IPO. 49 50 The process of translating the system design into programs. Separate programs are written for each component and put to work together. Ensures that the code meets the requirements specification and weeds out bugs. This phase requires the use of a programming language like Java. The implementation involves coding, testing, and debugging. An independent team of software engineers not involved in the design and implementation of the project usually conducts such testing. 51 52 makes the project available for use. is concerned with changing and improving the product. For a Java program, this means installing it on a desktop or on the Web. A software product must continue to perform and improve in a changing environment. This requires periodic upgrades of the product to fix newly discovered bugs and incorporate changes. 53 54 9
Problem: Computing Loan Payments This program lets the user enter the interest rate, number of years, and loan amount, and computes monthly payment and total payment. monthlypayment = loanamount monthlyinterestrate 1 (1 + monthlyinterestrate) 1 - numberofyears 12 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. ComputeLoan ComputeChange 55 56 Common Errors and Pitfalls Common Error 1: Undeclared/Uninitialized Variables and Unused Variables Common Error 2: Integer Overflow Common Error 3: Round-off Errors Common Error 4: Unintended Integer Division Common Error 5: Redundant Input Objects Common Error 1: Undeclared/Uninitialized Variables and Unused Variables double interestrate = 0.05; double interest = interestrate * 45; Common Pitfall 1: Redundant Input Objects 57 58 Common Error 2: Integer Overflow int value = 2147483647 + 1; // value will actually be -2147483648 Common Error 3: Round-off Errors.out.println(1.0-0.1-0.1-0.1-0.1-0.1);.out.println(1.0-0.9); 59 60 10
Common Error 4: Unintended Integer Division int number1 = 1; int number2 = 2; double average = (number1 + number2) / 2;.out.println(average); (a) int number1 = 1; int number2 = 2; double average = (number1 + number2) / 2.0;.out.println(average); (b) Common Pitfall 1: Redundant Input Objects Scanner input = new Scanner(.in);.out.print("Enter an integer: "); int v1 = input.nextint(); Scanner input1 = new Scanner(.in);.out.print("Enter a double value: "); double v2 = input1.nextdouble(); 61 62 11