Java Programming 1
Java Programming 1
You should have already installed Java Development Kit (JDK) and JCreator. Let us begin by writing our first Java program that prints a message "Hello, world!" to the display console, as follows: Hello, world! Step 1: Write the Source Code: Enter the following source codes using a programming text editor (such as JCreator) or an Interactive Development Environment (IDE) (such as Eclipse or Netbeans. Do not enter the line numbers (on the left panel), which were added to help in the explanation. Save the source file as "Hello.java". A Java source file should be saved with a file extension of ".java". The filename shall be the same as the classname - in this case "Hello". 1 /* 2 * First Java program, which says "Hello, world!" 3 */ 4 public class Hello { // Save as "Hello.java" 5 public static void main(String[] args) { 6 System.out.println("Hello, world!"); // print message 7 } 8} Step 2: Compile the Source Code: Compile the source code "Hello.java" into portable bytecode "Hello.class" using JDK compiler "javac". There is no need to explicitly compile the source code under IDEs (such as JCreator or NetBeans), as they perform incremental compilation implicitly. Step 3: Run the Program: On IDEs (such as JCreator or NetBeans), choose Run or press F5. Brief Explanation of the Program /* ...... */ // ... until the end of the line
These are called comments. Comments are NOT executable and are ignored by the compiler. But they provide useful explanation and documentation to your readers (and to yourself). There are two kinds of comments: 1. Multi-line Comment: begins with /* and ends with */, and may span more than one lines (as in Lines 1-3). 2. End-of-line Comment: begins with // and lasts until the end of the current line (as in Lines 4 and 6). public class Hello { ...... } The basic unit of a Java program is a class. A class called "Hello" is defined via the keyword "class" in Lines 4-8. The {...} is the body of the class. In Java, the name of the source file must be the same as the name of the public class with a mandatory file extension of ".java". Hence, this file MUST be saved as "Hello.java". public static void main(String[] args) { ...... } Lines 5-7 defines the so-called main() method, which is the starting point, or entry point for program execution. The {...} is the body of the method which contains programming statements. //NDT Page 1
System.out.println(aString) (Print-Line) prints the given aString, and brings the cursor to the beginning of the next line. System.out.print(aString) prints aString but places the cursor after the printed string.
Try the following program and explain the output produced: 1 /* Test System.out.println() and System.out.print() */ 2 public class PrintTest { // Save as "PrintTest.java" 3 public static void main(String[] args) { 4 System.out.println("Hello, world!"); // Advance the cursor to the beginning of next line 5 System.out.println(); // Print a empty line 6 System.out.print("Hello, world!"); // Cursor stayed after the printed string 7 System.out.println("Hello,"); 8 System.out.print(" "); // Print a space 9 System.out.print("world!"); 10 System.out.println("Hello, world!"); //NDT Page 2
5. Let's Write a Program to Add a Few Numbers Let us write a program to add five integers as follows: 1 /* 2 * Sum five numbers and print the result 3 */ 4 public class FiveNumberSum { // Save as "FiveNumberSum.java" 5 public static void main(String[] args) { 6 int number1 = 11; // Declare 5 int variables to hold 5 integers 7 int number2 = 22; 8 int number3 = 33; 9 int number4 = 44; 10 int number5 = 55; 11 int sum; // Declare an int variable called sum to hold the sum 12 sum = number1 + number2 + number3 + number4 + number5; 13 System.out.print("The sum is "); // Print a descriptive string 14 System.out.println(sum); // Print the value stored in sum 15 } 16 } The sum is 165 int number1 = 11; int number2 = 22; int number3 = 33; int number4 = 44; int number5 = 55;
declare five int (integer) variables called number1, number2, number3, number4, and number5; and assign values of 11, 22, 33, 44 and 55 to the variables, respectively, via the so-called assignment operator '='. You could also declare many variables in one statement, separating with commas, e.g., int number1 = 11, number2 = 22, number3 = 33, number4 = 44, number5 = 55; //NDT Page 3
A program is a sequence of instructions (called programming statements), executing one after another usually in a sequential manner, as illustrated in the following flow chart. Example The following program prints the area and perimeter of a circle, given its radius. Take note that the programming statements are executed sequentially - one after another in the order that they are written. 1 /* 2 * Print the area and circumference of a circle, given its radius. 3 */ 4 public class CircleComputation { // Saved as "CircleComputation.java" 5 public static void main(String[] args) { 6 // Declare variables 7 double radius, area, circumference; 8 final double PI = 3.14159265; 9 10 // Assign a value to radius 11 radius = 1.2; //NDT Page 4
The radius is 1.2 The area is 4.523893416 The circumference is 7.5398223600000005 double radius, area, circumference; declare three double variables radius, area and circumference. A double variable can hold real numbers (or floating-point numbers, with an optional fractional part). final double PI = 3.14159265; declare a double variables called PI and assign a value. PI is declared final, i.e., its value cannot be changed. radius = 1.2; assigns a value to the variable radius. area = radius * radius * PI; circumference = 2.0 * radius * PI; compute the area and circumference, based on the radius. System.out.print("The radius is "); System.out.println(radius); System.out.print("The area is "); System.out.println(area); System.out.print("The circumference is "); System.out.println(circumference); print the results with proper descriptions. Take note that the programming statements inside the main() are executed one after another, in a sequential manner. Exercises 1. Follow the above example, write a program (called RectangleComputation) to print the area and perimeter of a rectangle, given its length and width in doubles. 2. Follow the above example, write a program (called CylinderComputation) to print the surface area and volume of a cylinder, given its radius and height in doubles. 7. What is a Variable? Computer programs manipulate (or process) data. A variable is used to store a piece of data for processing. It is called variable because you can change the value stored.
//NDT
Page 5
A variable has a name (or identifier), e.g., radius, area, age, height. The name is needed to uniquely identify each variable, so as to assign a value to the variable (e.g., radius=1.2), and retrieve the value stored (e.g., radius*radius*3.1416). A variable has a type. Examples of type are: o int: for integers (whole numbers) such as 123 and -456; o double: for floating-point or real numbers, such as 3.1416, -55.66, 7.8e9, -1.2e3.4 having an optional decimal point and fractional part, in fixed or scientific notations; o String: for texts such as "Hello", "Good Morning!". Text strings are enclosed within a pair of double quotes. A variable can store a value of that particular type. It is important to take note that a variable in most programming languages is associated with a type, and can only store value of the particular type. For example, a int variable can store an integer value such as 123, but NOT real number such as 12.34, nor texts such as "Hello". The concept of type was introduced into the early programming languages to simplify intrepretation of data.
The following diagram illustrates three types of variables: int, double and String. An int variable stores an integer (whole number). A double variable stores a real number. A String variable stores texts.
To use a variable, you need to first declare its name and type, in one of the following syntaxes: varType varName; // Declare a variable of a type varType varName1, varName2,...; // Declare multiple variables of the same type varType varName = initialValue; // Declare a variable of a type, and assign an initial value varType varName1 = initialValue1, varName2 = initialValue2,... ; // Declare variables with initial values Take note that:
Each declaration statement is terminated with a semi-colon (;). In multiple-variable declaration, the names are separated by commas (,). The symbol =, known as the assignment operator, can be used to assign an initial value (of the declared type) to the variable.
For example, int sum; // Declare a variable named "sum" of the type "int" for storing an integer. // Terminate the statement with a semi-colon. //NDT Page 6
Each variable can only be declared once. (You cannot have two houses with the same address.) You can declare a variable anywhere inside the program, as long as it is declared before it is being used. Once the type of a variable is declared, it can only store a value of this particular type. For example, an int variable can hold only integer such as 123, and NOT floating-point number such as -2.17 or text string such as "Hello". The type of a variable cannot be changed inside the program, once declared.
I have shown your two data types in the above example: int for integer and double for floating-point number (or real number). Take note that in programming, int and double are two distinct types and special caution must be taken when mixing them in an operation, which shall be explained later. x=x+1? Assignment (=) in programming is different from equality in Mathematics. e.g., "x=x+1" is invalid in Mathematics. However, in programming, it means compute the value of x plus 1, and assign the result back to variable x. "x+y=1" is valid in Mathematics, but is invalid in programming. In programming, the RHS of "=" has to be evaluted to a value; while the LHS shall be a variable. That is, evaluate the RHS first, then assign to LHS. Some languages uses := as the assignment operator to avoid confusion with equality. 8. Basic Arithmetic Operations The basic arithmetic operations are: Operator + * //NDT Meaning Addition Subtraction Multiplication Example x+y xy x*y Page 7
Addition, subtraction, multiplication, division and remainder are binary operators that take two operands (e.g., x + y); while negation (e.g., -x), increment and decrement (e.g., x++, --x) are unary operators that take only one operand. Example The following program illustrates these arithmetic operations: 1 /** 2 * Test Arithmetic Operations 3 */ 4 public class ArithmeticTest { // Save as "ArithmeticTest.java" 5 public static void main(String[] args) { 6 7 int number1 = 98; // Declare an int variable number1 and initialize it to 98 8 int number2 = 5; // Declare an int variable number2 and initialize it to 5 9 int sum, difference, product, quotient, remainder; // Declare five int variables to hold results 10 11 // Perform arithmetic Operations 12 sum = number1 + number2; 13 difference = number1 - number2; 14 product = number1 * number2; 15 quotient = number1 / number2; 16 remainder = number1 % number2; 17 18 // Print results 19 System.out.print("The sum, difference, product, quotient and remainder of "); // Print description 20 System.out.print(number1); // Print the value of the variable 21 System.out.print(" and "); 22 System.out.print(number2); 23 System.out.print(" are "); 24 System.out.print(sum); 25 System.out.print(", "); 26 System.out.print(difference); 27 System.out.print(", "); 28 System.out.print(product); 29 System.out.print(", "); 30 System.out.print(quotient); 31 System.out.print(", and "); 32 System.out.println(remainder); 33 34 ++number1; // Increment the value stored in the variable "number1" by 1 35 // Same as "number1 = number1 + 1" 36 --number2; // Decrement the value stored in the variable "number2" by 1 37 // Same as "number2 = number2 - 1" 38 System.out.println("number1 after increment is " + number1); // Print description and variable 39 System.out.println("number2 after decrement is " + number2); 40 quotient = number1 / number2; 41 System.out.println("The new quotient of " + number1 + " and " + number2 42 + " is " + quotient); 43 } 44 } //NDT Page 8
declare all the int (integer) variables number1, number2, sum, difference, product, quotient, and remainder, needed in this program. sum = number1 + number2; difference = number1 - number2; product = number1 * number2; quotient = number1 / number2; remainder = number1 % number2; carry out the arithmetic operations on number1 and number2. Take note that division of two integers produces a truncated integer, e.g., 98/5 19, 99/4 24, and 1/2 0. System.out.print("The sum, difference, product, quotient and remainder of "); ...... prints the results of the arithmetic operations, with the appropriate string descriptions in between. Take note that text strings are enclosed within double-quotes, and will get printed as they are, including the white spaces (but without the double quotes). To print the value stored in a variable, no double quotes should be used. For example, System.out.println("sum"); // Print text string "sum" - as it is System.out.println(sum); // Print the value stored in variable sum, e.g., 98 ++number1; --number2; illustrate the increment and decrement operations. Unlike '+', '-', '*', '/' and '%', which work on two operands (binary operators), '++' and '--' operate on only one operand (unary operators). ++x is equivalent to x = x + 1, i.e., increment x by 1. You may place the increment operator before or after the operand, i.e., ++x (pre-increment) or x++ (post-increment). In this example, the effects of pre-increment and post-increment are the same. I shall point out the differences in later section. System.out.println("number1 after increment is " + number1); System.out.println("number2 after decrement is " + number2); print the new values stored after the increment/decrement operations. Take note that instead of using many print() statements as in Lines 17-30, we could simply place all the items (text strings and variables) into one println(), with the items separated by '+'. In this case, '+' does not perform addition. Instead, it concatenates or joins all the items together. Exercises 1. Combining Lines 19-32 into one single println() statement, using '+' to concatenate all the items together. 2. Introduce one more int variable called number3, and assign it an integer value of 77. Compute and print the sum and product of all the three numbers. 3. In Mathematics, we could omit the multiplication sign in an arithmetic expression, e.g., x = 5a + 4b. In programming, you need to explicitly provide all the operators, i.e., x = 5*a + 4*b. Try printing the sum of 31 times of number1 and 17 times of number2 and 87 time of number3.
//NDT
Page 9
An identifier is a sequence of characters, of any length, comprising uppercase and lowercase letters (a-z, A-Z), digits (0-9), underscore "_", and dollar sign "$". White space (blank, tab, new-line) and other special characters (such as +, -, *, /, @, &, commas, etc.) are not allowed. Take note that blank and dash (-) are not allowed, i.e., "max value" and "max-value" are not valid names. An identifier must begin with a letter (a-z, A-Z) or underscore (_). It cannot begin with a digit (09). Identifiers begin with dollar sign ($) are reserved for system-generated entities. An identifier cannot be a reserved keyword or a reserved literal (e.g., class, int, double, if, else, for, true, false, null). Identifiers are case-sensitive. A rose is NOT a Rose, and is NOT a ROSE.
Warning: Programmers don't use blank character in names. It is either not supported (e.g., in Java and C/C++), or will pose you more challenges. Variable Naming Convention A variable name is a noun, or a noun phrase made up of several words with no spaces between words. The first word is in lowercase, while the remaining words are initial-capitalized. For example, thefontSize, roomNumber, xMax, yMin, xTopLeft and thisIsAVeryLongVariableName. This convention is also known as camel-case. For constants (variables whose values cannot be changed), the names shall make up of words in uppercase and joined with underscore. For example, MAX_INTEGER, MIN_DOUBLE. Recommendations 1. It is important to choose a name that is self-descriptive and closely reflects the meaning of the variable, e.g., numberOfStudents or numStudents. 2. Do not use meaningless names like a, b, c, d, i, j, k, i1, j99. 3. Avoid single-letter names like i, j, k, a, b, c, which is easier to type but often meaningless. Exception are common names like x, y, z for coordinates, i for index. Long names are harder to type, but self-document your program. (I suggest you spend sometimes practicing your typing.) 4. Use singular and plural nouns prudently to differentiate between singular and plural variables. For example, you may use the variable row to refer to a single row number and the variable rows to refer to many rows (such as an array of rows - to be discussed later). Variable Declaration To use a variable in your program, you need to first "introduce" it by declaring its name and type, in one of the following syntaxes. The act of declaring a variable allocates a storage (of size capable of holding a value of the type).
Syntax // Declare a variable of a specified type type identifier; // Declare multiple variables of the same type, separated by commas type identifier1, identifier2, ..., identifierN; // Declare a variable and assign an initial value type identifier = initialValue; // Declare multiple variables with initial values type identifier1 = initValue1, ..., identifierN = initValueN; int option; double sum, difference, product, quotient; int magicNumber = 88; String greetingMsg = "Hi!", quitMsg = "Bye!"; Example
//NDT
Page 10
Java is a "strongly type" language. A variable is declared with a type. Once the type of a variable is declared, it can only store a value belonging to this particular type. For example, an int variable can hold only integer such as 123, and NOT floating-point number such as -2.17 or text string such as "Hello". Each variable can only be declared once. You can declare a variable anywhere inside the program, as long as it is declared before used. The type of a variable cannot be changed inside the program.
Expressions An expression is a combination of operators (such as addition '+', subtraction '-', multiplication '*', division '/') and operands (variables or literals), that can be evaluated to yield a single value of a certain type. For example, 1+2*3 // evaluated to int 7
int sum, number; sum + number // evaluated to an int value double principal, interestRate; principal * (1 + interestRate) // Evaluated to a double value Assignment An assignment statement: 1. assigns a literal value (of the RHS) to a variable (of the LHS), e.g., x = 1; or 2. evaluates an expression (of the RHS) and assign the resultant value to a variable (of the LHS), e.g., x = (y + z) / 2. The syntax for assignment statement is: Syntax Example // Assign the literal value (of the RHS) to the variable (of the LHS) variable = literalValue; number = 88; // Evaluate the expression (RHS) and assign the result to the variable (LHS) variable = expression; sum = sum + number; The assignment statement should be interpreted this way: The expression on the right-hand-side (RHS) is first evaluated to produce a resultant value (called rvalue or right-value). The rvalue is then assigned to the variable on the left-hand-side (LHS) or lvalue. Take note that you have to first evaluate the RHS, before assigning the resultant value to the LHS. For examples, number = 8; // Assign literal value of 8 to the variable number number = number + 1; // Evaluate the expression of number + 1, // and assign the resultant value back to the variable number 8 = number; // INVALID number + 1 = sum; // INVALID In programming, the equal symbol '=' is known as the assignment operator. The meaning of '=' in programming is different from Mathematics. It denotes assignment of the LHS value to the RHS variable, instead of equality of the RHS and LHS. The RHS shall be a literal value or an expression that evaluates to a value; while the LHS must be a variable.
//NDT
Page 11
Character Represented in 16-bit Unicode '\u0000' to '\uFFFF'. Can be treated as 16-bit unsigned integers in the range of [0, 65535] in arithmetic operations. Binary boolean Takes a value of either true or false. The size of boolean is not defined in the Java specification, but requires at least one bit.
Built-in Primitive Types Primitive type are built-in to the languages. Java has eight primitive types, as listed in the above table:
There are four integer types: 8-bit byte, 16-bit short, 32-bit int and 64-bit long. They are signed integers in 2's complement representation, and can hold an integer value of the various ranges as shown in the table. There are two floating-point types: 32-bit single-precision float and 64-bit double-precision double, represented as specified by IEEE 754 standard. A float can represent a number between 1.4023984610^-45 and 3.4028234710^38, approximated. A double can represented a number between 4.9406564584124654410^-324 and 1.7976931348623157010^308, approximated. Take note that not all real numbers can be represented by float and double. This Page 12
//NDT
Example: The following program can be used to print the maximum, minimum and bit-length of the primitive types. The maximum, minimum and bit-size of int are kept in constans INTERER.MIN_VALUE, INTEGER.MAX_VALUE, INTEGER.SIZE. // Print the minimum, maximum and bit-length for primitive types public class PrimitiveTypesMinMax { public static void main(String[] args) { // int (32-bit signed integer) System.out.println("int(min) = " + Integer.MIN_VALUE); System.out.println("int(max) = " + Integer.MAX_VALUE); System.out.println("int(bit-length) = " + Integer.SIZE); // byte (8-bit signed integer) System.out.println("byte(min) = " + Byte.MIN_VALUE); System.out.println("byte(max) = " + Byte.MAX_VALUE); System.out.println("byte(bit-length)=" + Byte.SIZE); // short (16-bit signed integer) System.out.println("short(min) = " + Short.MIN_VALUE); System.out.println("short(max) = " + Short.MAX_VALUE); System.out.println("short(bit-length) = " + Short.SIZE); // long (64-bit signed integer) System.out.println("long(min) = " + Long.MIN_VALUE); System.out.println("long(max) = " + Long.MAX_VALUE); System.out.println("long(bit-length) = " + Long.SIZE); // char (16-bit character or 16-bit unsigned integer) System.out.println("char(min) = " + (int)Character.MIN_VALUE); System.out.println("char(max) = " + (int)Character.MAX_VALUE); System.out.println("char(bit-length) = " + Character.SIZE); // float (32-bit floating-point) System.out.println("float(min) = " + Float.MIN_VALUE); System.out.println("float(max) = " + Float.MAX_VALUE); System.out.println("float(bit-length) = " + Float.SIZE); // double (64-bit floating-point) System.out.println("double(min) = " + Double.MIN_VALUE); System.out.println("double(max) = " + Double.MAX_VALUE); System.out.println("double(bit-length) = " + Double.SIZE); } } int(min) = -2147483648 int(max) = 2147483647 int(bit-length) = 32 byte(min) = -128 byte(max) = 127 byte(bit-length)=8 short(min) = -32768 short(max) = 32767 short(bit-length) = 16 long(min) = -9223372036854775808 long(max) = 9223372036854775807 //NDT Page 13
Use int for integer and double for floating point numbers. Use byte, short, long and float only if you have a good reason to choose that specific precision. Use int for counting and indexing, NOT floating-point type (float or double). This is because integer type are precise and more efficient in operations. Use an integer type if possible. Use a floating-point type only if the number contains a fractional part.
//NDT
Page 14
//NDT
Page 15
initialization-statement; while (test) { loop-body; } next-statement; As illustrated in the flow chart, the initialization statement is first executed. The test is then checked. If the test is true, the body is executed. The test is checked again and the process repeats until the test is false. When the test is false, the loop completes and program execution continues to the next statement after the loop. In our program, the initialization statement declares an int variable named number and initializes it to lowerbound. The test checks if number is equal to or less than the upperbound. If it is true, the current value of number is added into the sum, and the statement ++number increases the value of number by 1. The test is then checked again and the process repeats until the test is false (i.e., number increases to upperbound+1), which causes the loop to terminate. Execution then continues to the next statement (in Line 23). In this example, the loop repeats upperbound-lowerbound+1 times. After the loop is completed, Line 17 prints the result with a proper description. System.out.println("The sum from " + lowerbound + " to " + upperbound + " is " + sum); prints the results. Exercises 1. Modify the above program to sum all the numbers from 9 to 888. (Ans: 394680.) 2. Modify the above program to sum all the odd numbers between 1 to 1000. (Hint: Change the post-processing statement to "number = number + 2". Ans: 250000) 3. Modify the above program to sum all the numbers between 1 to 1000 that are divisible by 7. (Hint: Modify the initialization and post-processing statements. Ans: 71071.) 4. Modify the above program to find the sum of the square of all the numbers from 1 to 100, i.e. 1*1 + 2*2 + 3*3 +... (Ans: 338350.) 5. Modify the above program (called RunningNumberProduct) to compute the product of all the numbers from 1 to 10. (Hint: Use a variable called product instead of sum and initialize product to 1. Ans: 3628800.) 10. Conditional (or Decision) What if you want to sum all the odd numbers and also all the even numbers between 1 and 1000? There are many ways to do this. You could declare two variables: sumOdd and sumEven. You can then use a //NDT Page 16
//NDT
Page 17
// if-then if ( test ) { true-body; } // if-then-else if ( test ) { true-body; } else { false-body; } For a if-then statement, the true-body is executed if the test is true. Otherwise, nothing is done and the execution continues to the next statement. For a if-then-else statement, the true-body is executed if the test is true; otherwise, the false-body is executed. Execution is then continued to the next statement. In our program, we use the remainder operator (%) to compute the remainder of number divides by 2. We then compare the remainder with 0 to test for even number. Comparison Operators There are six comparison (or relational) operators: Operator == != > >= < <= //NDT Meaning Equal to Not equal to Greater than Greater than or equal to Less than Less than or equal to Example x == y x != y x>y x >= y x<y x <= y Page 18
Arithmetic operations ('+', '-', '*', '/') of two int's produce an int; while arithmetic operations of two double's produce a double. Hence, 1/2 0 and 1.0/2.0 0.5. Arithmetic operations of an int and a double produce a double. Hence, 1.0/2 0.5 and 1/2.0 0.5.
You can assign an integer value to a double variable. The integer value will be converted to a double value automatically, e.g., 3 3.0. For example, int i = 3; double d; d = i; // 3 3.0, d = 3.0 d = 88; // 88 88.0, d = 88.0 double nought = 0; // 0 0.0; there is a subtle difference between int 0 and double 0.0 However, you CANNOT assign a double value directly to an int variable. This is because the fractional part could be lost, and the compiler signals an error in case that you were not aware. For example, double d = 5.5; int i; i = d; // error: possible loss of precision i = 6.6; // error: possible loss of precision Type Casting Operators To assign an double value to an int variable, you need to explicitly invoke a type-casting operation to truncate the fractional part, as follows: (new-type)expression;
//NDT
Page 20
//NDT
Page 21
//NDT
Page 22