Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 Java Programming Contents 1 Introduction .............................................................................. 3 1.1 1.2 2 WHAT IS JAVA PROGRAMMING? ................................................................................................... 3 HOW TO PREPARE A JAVA PROGRAM? .......................................................................................... 3 Java program structure and data types ................................ 6 2.1 BASIC STRUCTURE OF JAVA PROGRAMS ....................................................................................... 6 2.2 BASIC DATA TYPES IN JAVA ......................................................................................................... 7 2.2.1 Integer data type ..................................................................................................................... 7 2.2.2 Real number data type ............................................................................................................ 8 2.2.3 Character data type ................................................................................................................ 8 2.2.4 String class ............................................................................................................................. 8 2.2.5 Boolean data type ................................................................................................................... 9 2.2.6 Value ranges supported by various Java numeric data types ................................................. 9 3 Basic Java arithmetic operators ........................................... 10 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 4 Basic Input/Output Functions .............................................. 15 4.1 4.2 5 PRINTLN() FUNCTION ...................................................................................................................15 SCANNER() CLASS ......................................................................................................................16 More Java Operators ............................................................ 18 5.1 5.2 5.3 5.4 5.5 6 ADDITION OPERATOR ..................................................................................................................10 SUBTRACTION OPERATOR............................................................................................................10 MULTIPLICATION OPERATOR .......................................................................................................10 DIVISION OPERATOR....................................................................................................................10 MODULUS OPERATOR ..................................................................................................................11 INCREMENT OPERATOR (++)........................................................................................................11 DECREMENT OPERATOR (--) ........................................................................................................12 ADDITIONAL EXAMPLES ..............................................................................................................12 COMPARISON OPERATORS ...........................................................................................................19 EQUALITY OPERATORS ................................................................................................................19 LOGICAL OPERATORS ..................................................................................................................20 OPERATOR PRECEDENCE AND ASSOCIATIVITY.............................................................................21 ADDITIONAL EXAMPLES ..............................................................................................................21 Flow of control ....................................................................... 23 6.1 6.2 6.3 6.4 6.5 6.6 6.7 6.8 EMPTY STATEMENT .....................................................................................................................23 IF AND IF-ELSE STATEMENTS .......................................................................................................23 SWITCH STATEMENT....................................................................................................................25 WHILE STATEMENT ......................................................................................................................27 DO-WHILE STATEMENT ................................................................................................................28 FOR STATEMENT .........................................................................................................................30 COMMA OPERATOR .....................................................................................................................31 BREAK AND CONTINUE STATEMENTS...........................................................................................32 1 ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 7 Arrays...................................................................................... 35 8 Implementing Enumerated Types in Java .......................... 38 9 Elementary Program Design Issues ..................................... 39 9.1 9.2 9.3 9.4 CLASS .........................................................................................................................................40 METHOD DEFINITION ..................................................................................................................40 CALL-BY-VALUE AND CALL-BY-REFERENCE ...............................................................................42 RECURSION .................................................................................................................................42 10 File Handling .......................................................................... 44 2 ALCS Curriculum Programming (JAVA Programming) 1 Introduction 1.1 What is Java programming? V1.1 12/1/2007 Java is a high-level computer programming language, which allows programmers to write instructions like English. Like other high-level programming language, Java has a particular set of rules called syntax, which specifies how instructions to be written. Java was developed in the early 1990s by Sun Microsystems Inc. It begins with basic syntax of the language like C, C++, and Smalltalk. Because it is parsimonious, robust, secure and portable in nature, Java programming is growing very fast all over the world. Java is an object-oriented programming language. Object-oriented programming is a style of programming, where data of a logical entity and program codes that manipulate those data are packaged into a single unit called object. Object-oriented programming promotes software reuse and enhances software maintainability. In this batch of notes, the object-oriented programming features in Java will not be discussed as it is out of the current ALCS curriculum. Apart from being a programming language, Java has evolved to become a platform known as the Java Software Development Kit (SDK). The Java SDK includes programming interfaces and programming tools, and it provides a programming environment for programmers to build different types of Java programs. The Java SDK is available to be downloaded freely from the official site of Sun Microsystems at http://java.sun.com/javase/downloads/index.jsp. 1.2 How to prepare a Java program? To run a Java program, there are four main steps: 1. Writing the program To edit a Java program, simply prepare it with a text editor like notepad. The program file in text format is referred to as the source program. The filename of a Java source program is ended with the extension “.java”. 2. Compiling A Java compiler translates a Java source code to bytecode packaged into a class file (with an extension of “.class”) which a Java Virtual Machine (JVM) can understand. The bytecode format is machine independent such that it can be used across various operation systems. The syntax for compiling the Java program is as follows: 3 ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 javac program_name.java Example: class HelloWorld { public native void displayHelloWorld(); static { System.loadLibrary("This is the helloworld program"); } public static void main(String[] args) { new HelloWorld().displayHelloWorld(); } } 3. Loading “.class” files (in bytecode) are interpreted by the JVM and translated into the native machine code that a CPU can understand. In the process, bytecode is checked against for any unsafe actions so that no damaging instructions will be executed by the host computer. After compiling the above sample Java program, a corresponding ‘.class’ file is formed. 4. Executing the program 4 ALCS Curriculum Programming (JAVA Programming) The native machine code in the form of 1’s and 0’s is executed by the CPU. To run the program, the following syntax can be used: java program_name Note that no ‘.java’ should be included in this command. Result 5 V1.1 12/1/2007 ALCS Curriculum Programming (JAVA Programming) 2 Java program structure and data types 2.1 Basic structure of Java programs V1.1 12/1/2007 The usual structure of Java programs is as follows: public class Class_name //class header { public static void main(String[ ] args) //main method header { … } //method header public datatype method_header(datatype parameter_name) { … } } The first line of the above program fragment is the class header. The class header specifies the name of the class and identifies how the code would be accessed. The “public” keyword indicates that the class can be assessed by any classes. The notion of class in Java public class Class_name { //class header The second line of the above coding is the main method header. In every stand-alone Java application, a main() method must be contained, which act as the starting point for program execution. The instructions in main() method are run essentially in a sequential manner during program execution and they may invoke other methods (of the same or other classes) in the program. “static” and “void” are Java keywords too. The “void”: keyword indicates that no data will be returned by main(). For brevity, we will not discuss the meaning of the “static” keyword here. public static void main(String[ ] args) { //main method header The concept and implementation of Class and Method in Java will be discussed further in chapter 9 of this handout. Teaching remarks 6 ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 Java language is case sensitive. This means that Java complier considers uppercase and lowercase characters as different characters. A class name in Java language must not contain spaces and must not begin with a number. 2.2 Basic data types in Java In Java programming, every variable must be associated with a data type, which defines what data that the variable can contain and the operations that can be performed on the variable. Thus, Java programmers cannot declare an integer data type for a variable and then stores a string of characters into that variable. To declare a variable in Java, a declaration statement is required to associate a data type to the variable. The general form of the declaration statement is as follows: datatype variable_name_1, …variable_name_N In the following sections, several common data types in Java programming language are introduced: int – integer float – floating point value double – a double-precision floating point value char – a single character String - an array of characters (strictly speaking, String is a class instead of a data type) 6. boolean – stores data in only one of two states: true or false 1. 2. 3. 4. 5. 2.2.1 Integer data type The basic integer data type in Java is int. Typically an int is stored in 32 bits. Thus an int variable can store any number ranged from -2,147,483,648 to 2,147,483,647. Two other variants are long and short which stand for long integer and short integer data types. Typically long and short integer types support 64-bit and 16-bit integers respectively. Syntax: int variable_name; Examples: int number_of_students; int number_of_books = 95; 7 ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 The first example declares number_of_students as an integer variable whereas the second example declares the integer variable number_of_books and initializes its value as 95. 2.2.2 Real number data type Integer variables cannot store fractional values. Java uses float and double to store real (or floating point) numbers. A floating number is divided into four parts: integer, decimal point, fractional part, and an exponential part. A floating constant must contain either a decimal point or an exponential part or both. A float variable takes up four bytes whereas a double variable takes up eight bytes Syntax: float variable_name; double variable_name; Examples: float temperature; double pi = 3.141592654; 2.2.3 Character data type The character data type used in Java is char. Characters in Java are stored in unicode. Hence, each char variable usually takes 16-bit to store. Character constant is to be enclosed by a pair of single quotes. Syntax: char variable_name; Examples: char class_code; char sex=’F’; 2.2.4 String class In Java, a string variable can be defined using the system defined String class. Strings in Java are treated as class object. In order to let the Java complier recognize strings, each string constant must be enclosed by a pair of double quotes. Syntax: String string_name; 8 ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 Examples: String student_name; String teacher_name=”Mark Tam”; The first example declares a string instance called student_name. The second example declares a string instance called teacher_name and instantiates it to “Mark Tam”. 2.2.5 Boolean data type Java offers a boolean data type to represent the true or false value. Thus true and false are reserved words in Java. The syntax and examples for declaring a Boolean data type variable is shown as follows: Syntax: boolean Boolean_name; Examples: boolean Mary_absent; boolean John_absent = true; 2.2.6 Value ranges supported by various Java numeric data types The following table summaries the value ranges supported by different Java numeric data types. Note that the actual bounds associated with each data type vary with individual Java implementations but the bounds given below define the narrowest ranges of values that all Java implementation should support. Data type int long short float double Lower bound -2,147,483,648 -9,223,372,036,854,775,808 -32,768 1.40129846432481707 * 10-45 4.94065645841246544 * 10-324 Upper bound 2,147,483,647 9,223,372,036,854,775,807 32,767 3.40282346638528860 * 1038 1.79769313486231570 * 10308 For more information on the topic, readers may reference the following web pages: http://www.cafeaulait.org/course/week2/02.html http://www.wilsonmar.com/DataTypes.htm 9 ALCS Curriculum Programming (JAVA Programming) 3 Basic Java arithmetic operators 3.1 Addition operator V1.1 12/1/2007 To add numeric data variables and/or values, we can use the + operator. An example statement is as follows: total_students = male_students + female_students; The above assignment statement computes the sum of the numeric data objects on the right hand side of the statement and assigns the result as the value of the numeric variable on the left. Multiple numeric data objects may be found on the right hand side of an assignment statement but exactly one single numeric variable can be referenced on the left hand side of the assignment statement. 3.2 Subtraction operator To compute the difference between two numeric data objects, we can use the - operator. An example statement is as follows: male_students = total_students - female_students; 3.3 Multiplication operator To compute the product of two numeric variables, we can use the * operator. An example statement is as follows: total_charge = charge_per_person * num_of_persons; 3.4 Division operator To compute a division between two numeric variables, we can use the / operator to do so. An example statement is as follows: charge_per_person = total_charge / num_of_persons; Note that if both the numerator and denominator on the right hand side of the assignment statement are of integer type, an integer division will be performed. An integer division returns the integral part of the result of a division. Thus 5/3 results in 1, 4/5 results in 0, and -4/3 results in -1. However 4.0/5 returns 0.8 as the numerator is not of an integer type. 10 ALCS Curriculum 3.5 Programming (JAVA Programming) V1.1 12/1/2007 Modulus operator To get the remainder of a division, we can use the modulus operator %. An example statement is as follows: money_remain = total_amount % num_of_persons; Rather surprisingly, the % (modulus) operator in Java works with both integers and floating point numbers, for example, 8.5 % 2.5 returns 1. Care should be exercised when dealing with operands that are negative and such information can be found from this web page. Activity The way that Java interprets a modulus operation may be different from other programming language. Contrast the data type(s) of the operand supported by the modulus operators in Java and other programming languages such as Pascal, C and Visual Basic. Do all those modulus operators behave in the same way? 3.6 Increment operator (++) The numeric variable associated with the ++ operator will have its value increased by one. The variable being incremented can be an integer or a floating point number. Syntax: variable1++; ++ variable1; Examples: int counter=0, num_of_person=10; … counter++; // value of counter will be 1 ++num_of_person; // value of num_of_person will be 11 Putting an increment operator before or after the operand does not make a difference if the Java statement does not have any more components. Otherwise, the position of the increment operator does carry different meanings. If the increment operator is put after its operand, the operand’s value will only be incremented after the rest of the Java statement is executed. This is referred to as post-increment. If the operator is put before its operand, the operand’s value will be incremented before the rest of the Java statement is executed. This is referred to as pre-increment. Examples: int a=0, b=0, c, d; … c = (a++); // c will be assigned with 0 11 ALCS Curriculum d = (++b); Programming (JAVA Programming) V1.1 12/1/2007 // d will be assigned with 1 Activity The ++ operator in Java accepts floating point operand. Do the ++ operators in other programming languages such as Pascal, C and Visual Basic accept floating point operand too? 3.7 Decrement operator (--) The numeric variable associated with the -- operator will have its value decreased by one. The variable being decremented should be an integer or a floating point number. Syntax: variable1---variable1 Examples: int counter=0, num_of_person=10; … counter--; // value of counter will be -1 --num_of_person; // value of num_of_person will be 9 Putting a decrement operator before or after the operand does not make a difference if the Java statement does not have any more components. Otherwise, the position of the decrement operator does carry different meanings. If the decrement operator is put after its operand, the operand’s value will only be decremented after the rest of the Java statement is executed. This is referred to as post-decrement. If the operator is put before its operand, the operand’s value will be decremented before the rest of the Java statement is executed. This is referred to as pre- decrement. Examples: int a=0, b=0, c, d; … c = (a--); // c will be assigned with 0; a will become -1 d = (--b); // d will be assigned with -1; b will become -1 3.8 Additional examples Example 3.8.1: Compute the average weight of three objects. 12 ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 Suppose object1 = 4, object2 = 4, and object3 = 5, a possible implementation of the corresponding Java program is public class ch3_8_1 { public static void main(String[] args) { int weight1, weight2, weight3, avg_weight; weight1 = 4; weight2 = 4; weight3 = 5; avg_weight = (weight1 + weight2 + weight3)/3; System.out.println("The average weight is " + avg_weight); } } Source file: ch3_8_1.java Result 3.8.1 Activity Why is the average weight computed in the above example not 4.3333 but 4? Example 3.8.2: Convert Fahrenheit to Celsius. Suppose the degree in Fahrenheit is 85, a possible implementation of the corresponding Java program to compute the corresponding is public class ch3_8_2 { public static void main(String[] args) { float fahrenheit=85; float celsius; celsius = 5*(fahrenheit - 32)/9; System.out.println(" When Fahrenheit = "+ fahrenheit + " Celsius = " + celsius); } } Source file: ch3_8_2.java Result 3.8.2 13 ALCS Curriculum Programming (JAVA Programming) 14 V1.1 12/1/2007 ALCS Curriculum 4 Programming (JAVA Programming) V1.1 12/1/2007 Basic Input/Output Functions In Java, it performs the input/output using streams. A stream is the abstraction which produces or consumes information. For the input stream, it refers to the keyboard and mouse input. For the output stream it refers to the screen output, file or network connection output. In order to use the input and output streams in Java, we need to use the java.io package. In this package, it defines some simple input and output functions. 4.1 println() function The println() function from the java.io provides a simple way to print formatted text followed by a new line on an output device, e.g. the computer screen. The following Java statement prints out a string, which is delimited by a pair of double quotes, on the output device. System.out.println(“text string”); Example 4.1: A simple program that displays different types of data output on a screen. public class ch4_1 { public static void main(String[] args) { String month="June"; int salary = 14843; System.out.println("A character" + 'A'); System.out.println("A decimal integer " + 100); System.out.println("A floating-point number " + 564.58); System.out.println("A floating-point number in scientific notation " + 564.58); System.out.println("A string " + "CDI, EMB"); System.out.println("My salary in " + month + salary); } } Source file: ch4_1.java Result 4.1 15 ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 As shown in the results above, no space character will be automatically introduced by the string concatenation operator (+) to separate the strings in the output. 4.2 Scanner() class To read the data from the user input, we can use a predefined class called Scanner which is introduced in Java with JDK 1.5. By telling a Scanner object what to read, it can easily get the required data from the system input device. To create a Scanner object that reads from the system input device, the constructor method Scanner() needs to be called with System.in as its argument. Scanner scanner_name = new Scanner(System.in); A Scanner can help to break the input down into manageable units, called tokens, for reading a String, we can use the nextLine() to grab everything typed on the console until the user pass the “Enter” key. The syntax for using the nextLine() as follows: Datatype var_name = scanner.nextLine(); Below, shows a table for the Scanner function: Data type Boolean Double Float Int Short String (read until ‘\n’) String (read until ‘ ’, ‘\t’, ‘\n’) Scanner method Boolean nextBoolean() Double nextDouble() Float nextFloat() Int nextInt() Short nextShort() String nextLine() String next() Note that the Scanner function is provided in Java 1.5 or subsequent versions. To check your Java version, type “java -version” in the command console. 16 ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 To read in a string, we can use the System.in function. The basic syntax as shown below: Datatype var_name = System.in.readLine(); Example 4.2: The following program accepts different types of data input from a keyboard. import java.io.*; import java.util.*; public class ch4_2 { public static void main(String[] args) throws IOException { int age; String sex,name; Scanner in = new Scanner(System.in); System.out.print("Sex -> "); sex = in.nextLine(); System.out.print("Name -> "); name = in.nextLine(); System.out.print("Age -> "); age = in.nextInt(); } } Source file: ch4_2.java Result 4.2 17 ALCS Curriculum 5 Programming (JAVA Programming) V1.1 12/1/2007 More Java Operators So far we have covered a few Java operators like the assignment operator (=) and basic arithmetic operators +, -, *, / and %. In this chapter, we will cover additional assignment operators that combine the above arithmetic operators and the assignment operator. Three other classes of operators, namely the relational operators, equality operators, and logical operators, will also be introduced. Operator precedence and associability will also be discussed. In addition to the basic assignment operator, Java supports several variants of assignment operator that combine both operators for computation and assignment together. Such variants can support a more efficient execution when compared to their corresponding primitive forms. The variants that will be covered in this chapter are as follows: += -= *= /= %= Teaching remark There are a few other assignment operators associated with bitwise operators (i.e., operators deal with bit strings) but they are out of the scope of our discussion. Readers may have already noticed that all the above operators have a similar syntactic structure as follows: variable op= expression Note that an expression can vary from a constant or a variable to a combination of simpler expressions. Syntax: variable += expression; variable -= expression; variable *= expression; variable /= expression; variable %= expression; The semantics of the statement is variable = variable op (expression) The following table gives some Java statements to illustrate the use of the given assignment operators. Compact Form count += 2; Equivalent Form count = count + 2; 18 ALCS Curriculum Programming (JAVA Programming) count -= 2; count *= 2; count /= 2; count %= 2; V1.1 12/1/2007 count = count - 2; count = count * 2; count = count / 2; count = count % 2; Java introduces the compact form of assignment operators mainly for improving execution efficiency. For each of the given compact forms, two operands are involved. For their equivalent forms, three operands are involved. The equivalent form needs to fetch one more operand to the memory before the corresponding instruction can be executed. By the same token, the increment (++) and decrement (--) operators were introduced to reduce the number of operands to be fetched for the corresponding instructions. 5.1 Comparison operators Java supports the following Comparison operators: < > <= >= Each of the operators takes two operands and yields either the integer value of true or false upon evaluation. Syntax: expression1 < expression2 expression1 > expression2 expression1 <= expression2 expression1 >= expression2 The following table gives some examples to illustrate some use of the relational operators. Suppose x, y, and z are set to 1, 2 and 3 respectively. Relational Expression x<y x>y (x + z) <= y (x + z) >= y Evaluation Result True False False True Relational expressions are typically used to test for the satisfaction of conditions. 5.2 Equality operators Java supports the following equality operators: == (equal to) != (not equal to) 19 ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 Syntax: expression1 == expression2 expression1 != expression2 Each of the operators takes two operands and yields either the integer value of true or false upon evaluation. The following table gives some examples to illustrate some use of the equality operators. x-y Zero Non-zero x == y true false x != y false true The table entries indicates that when (x-y) is zero, i.e. x is equal to y, the expressions x==y and x!=y will be evaluated to true and false respectively, and when (x-y) is nonzero, i.e. x is not equal to y, the expressions x==y and x!=y will be evaluated to false and true respectively. Like relational expressions, equality expressions are typically used to test for the satisfaction of conditions. Teaching remark Novice programmers may sometimes mix up the assignment operator (=) with the test of equality operator (==). You cannot compare two String objects using == or != , you need to use x.equals(y) or !x.equals(x). 5.3 Logical operators Java supports the following logical operators: ! (negation) && (logical AND) || (logical OR) The negation operator is unary whereas the logical AND and OR operators are binary. Syntax: ! expression expression1 && expression2 expression1 || expression2 The following tables give some examples to illustrate the use of the three operators. Note that arguments a and b represent arbitrary expressions. a False True !a True False 20 ALCS Curriculum Programming (JAVA Programming) a False False True True a && b False False False True b False True False True V1.1 12/1/2007 a || b False True True True Like relational expressions and equality expressions, logical expressions are typically used to test for the satisfaction of conditions. One interesting property of logical AND and logical OR expressions is known as shortcircuit evaluation. In brief, the evaluation process stops as soon as the outcome is known. For example, when the expression (a && b) is evaluated such that expression a is found to be false, expression b will not be evaluated as the result will be immaterial. Similarly, when the expression (a || b) is evaluated such that expression a is found to be true, expression b will not be evaluated. 5.4 Operator precedence and associativity Like the arithmetic operators, the relational, equality and logical operators have rules of precedence and associativity that determines how expressions involving these operators are evaluated. The rules are summarized in the following table. Operators () ++(prefix) --(prefix) + -(unary) ++(prefix) --(prefix) * / % + < <= > >= == != && || = += -= *= /= 5.5 Precedence Highest Lowest Associativity left to right right to left left to right left to right left to right left to right left to right left to right right to left Additional examples The following table gives some examples regarding operator precedence, associativity, and short-circuit evaluation. The parts of expression which are not evaluated due to short-circuit evaluation are highlighted in red bolded italics. Declarations and initializations int double i=2, j=2, k=2; x=0.0, y=3.2; Expression Equivalent Expression Value i==2 && j==2 && k==2 (i==2 && j==2) && k==2 true 21 ALCS Curriculum Programming (JAVA Programming) x-1!=0 || i!=0 && j-10!=0 i < j && x < y i < j || x < y (x-1!=0)||(i!=0 && (j10!=0)) (i < j) && (x < y) (i < j) || (x < y) 22 V1.1 12/1/2007 true false true ALCS Curriculum 6 Programming (JAVA Programming) V1.1 12/1/2007 Flow of control Like other programming languages, Java statements are normally executed sequentially. In some occasions, sequential flow of control has to be altered to provide for a choice of action, or the repetition of action. In Java, a selection among alterative actions can be implemented with the use of if, if-else, and case, whereas iterative actions statements can be implemented with the use of while, for, and do statements. The equality, logical and relational operators are often used to describe conditions in conditional and repetition statements. 6.1 Empty statement An empty statement is written as a single semicolon (;). It is used in a place where a statement is needed syntactically but no action is required semantically. Since the presence of empty statements in a Java program may appear to be weird and confusing, such statements should be avoided whenever possible. It is important to note that inserting a semicolon inadvertently in some Java statement, e.g. if statement, can result in a mistake that the compiler cannot detect. Example 6.1: if (a > 3); b = 4; In the above example, b is always assigned with a value of 4 disregarding whether or not a is greater than 3. The problem lies on the extraneous semicolon at the end of the conditional expression which makes no action associated with the conditional statement (instead of the original intention of associating the assignment statement in the second line as the action part of the conditional statement). The syntactic structure of if statement will be discussed in the next section. 6.2 if and if-else statements Like in many other programming languages, Java uses the if and if-else statements to implement conditional statements. Syntax: if (expression) statement If the expression is true, statement will be executed; otherwise, statement will be skipped and program execution will continue in the next statement. Although Java ignores any white characters used for indentation. 23 ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 Example 6.2a: int temperature, fan, heater; … if (temperature > 25) { heater = 0; // 0 for “off”; 1 for “on” fan = 1; } Teaching remark For simplicity, the on-and-off status of an electrical appliance is represented by an integer value. A better practice is to use a Boolean value instead. Syntax: if (expression) statement1 else statement2 If the expression is true, statement1 will be executed; otherwise, statement2 will be executed. Afterwards, program execution will continue in the next statement. Example 6.2b: int temperature, fan, heater; … if (temperature > 25) { fan = 1; heater = 0; } else if (temperature > 15) { fan = 0; heater = 0; } else { fan = 0; heater = 1; } //temperature > 25 // 25 >= temperature > 15 // temperature <= 15 24 ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 The above example is self explanatory. However it is worth mentioning the use of the nested if-else statements in the example which allow programmers to model complex selection statements. Example 6.2c: int button, fan, speed; … if (button == 0) { fan = 0; speed = 0; } else if (button == 1) { fan = 1; speed = 900; } else if (button == 2) { fan = 1; speed = 1500; } else if (button == 3) { fan = 1; speed = 2400; } // fan off // slow fan speed // fan on // moderate fan speed // quick fan speed The if-else statement in the above example illustrates a complex nested if statement is required if a selection statement involves a number of possible choices such that each of the choices is corresponding to different actions. Such a problem can be addressed with the use of another selection statement in Java, the switch statement. 6.3 switch statement Compared to the if-else statement, the switch statement offers a much neater way to implement conditional statements that involves a number of choices. Syntax: switch (integer_expression) { case integer_constant_1: statement; break; // optional break statement 25 ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 case integer_constant_2: statement; break; … // additional cases if required default: // optional default statement statement; } The switch statement first evaluates its associated integer expression. It then directs the flow control to an appropriate case label where its associated integer constant is found to be equal to the value of the integer expression. The statement(s) after the matched case label are then executed until a break statement is reached or the switch statement ends. That is why the last statement associated to a case label is usually a break statement. If a break statement does not exist, execution “falls through” to the next statement in the succeeding case. Note that the default label, if appeared, is usually put just before a switch statement ends so that all remaining cases that cannot match to any previous case labels can be dealt with. Teaching remarks Omission of break is one common cause of error in switch statements. Each switch statement is associated with zero or one default label. The break in the last case/default label is usually skipped for brevity. The case and default keywords cannot be used outside of a switch statement. Example 6.3 re-implements the program in Example 6.2 with the use of switch instead of if-else. Example 6.3: import java.util.*; public class ch6_3 { public static void main(String[ ] args) throws Exception { int button, fan, speed; int ON =1; int OFF = 0; Scanner in=new Scanner(System.in); button = in.nextInt(); switch (button) { case 1: // fan off fan = OFF; speed = 0; break; case 2: // slow fan speed 26 ALCS Curriculum Programming (JAVA Programming) fan = ON; speed = 900; break; case 3: fan = ON; speed = 1500; break; case 4: fan = ON; speed = 2400; } V1.1 12/1/2007 // moderate fan speed // quick fan speed } } If the keyword break associated with the case 2 is omitted inadvertently and the value of button is 2, fan and speed will be set to 1 and 1500 respectively as execution falls through to the case 3 label. 6.4 while statement The while statement allows a programmer to repeat a course of actions while a specified condition is satisfied. Syntax: while (expression) statement A while statement first evaluates its associated expression. If the value of the expression (expression) is found to be false, execution is passed to the statement after the while statement. Otherwise, the associated statement (statement) is executed. Execution is then returned to the while statement again. Thus the statement(s) within the body of a while-loop may be executed for zero, one or multiple times. The following example illustrates how a while statement can be used to compute the factorial of an integer value which is read from the system input device, typically the keyboard. Example 6.4: int i, factorial=1; Scanner in=new Scanner(System.in); … // input i from the system input device to compute i’s factorial System.out.print(“i = “); i = in.nextInt(); 27 ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 … // assuming i being a positive integer while (i > 1) { factorial = factorial * i; i--; } Suppose 3 is input as the value of i. As 3 is greater than 1, the body of the while-loop is executed. This changes the values of factorial (1*3) and i to 3 and 2 respectively. Then i is compared to 1 again. Since i (2) is still greater than 1, the body of the while-loop is executed again. This changes the values of factorial (3*2) and i to 6 and 1 respectively. Afterwards, i is compared to 1 again. This time i (1) is no longer greater than 1 and thus execution is skipped to the statement next to the while loop. Due to the power of Java language, the previous while-loop can be implemented in a more compact and efficient manner as below. while (i > 1) factorial *= i--; // statement 1 // statement 2 An execution trace of the above program fragment when i is set to 4 is illustrated in the following table. Iteration number 1 2 3 4 6.5 i (at statement 1) i>1 4 3 2 1 true true true false factorial (after execution of statement 2 if applicable) 4 12 24 24 (no execution of statement 2) do-while statement Like the while statement, the do-while statement allows a program to repeat a course of actions while a specified condition is satisfied. However a do-while statement always executes its associated action statement(s) at least once as the condition associated with the do-while statement is put at the end of the statement. Syntax: do statement while (expression); It is always possible to replace a do-while loop with the use of a while loop as below. statement 28 ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 while (expression) statement The previous example on computing the factorial of an integer value can be reimplemented with the use of a do-while statement as follows: Example 6.5a: int i, factorial=1; Scanner in=new Scanner(System.in); … // input i from the system input device to compute i’s factorial System.out.print(“i = “); i = in.nextInt(); … // assuming i being a positive integer do { factorial = factorial * i; i--; } while (i > 1); Apparently, the conversion between the while loop and the do-while loop given in Examples 6.4 and 6.5a respectively does not entirely follow the syntactic rule given earlier on. According to the given rule, the corresponding while-loop implementation should be as follows: Example 6.5b: int i, factorial=1; Scanner in=new Scanner(System.in); … // input i from the system input device to compute i’s factorial System.out.print(“i = “); i = in.nextInt(); … // assuming i being a positive integer factorial = factorial * i; i--; while (i > 1) { factorial = factorial * i; i--; } On second thought, the Java statements in Example 6.5b are functionally equivalent to the program fragment shown in Example 6.4. The while-loop and the do-while-loop behave slightly different when the input value for variable i is one. In such a case, the 29 ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 statements associated with the while-loop are never executed. However, the value of the factorial of one is still correct as the variable factorial is initialized to 1. 6.6 for statement Like the while and do-while statements, a for statement is used to execute codes iteratively. The syntax of for statements is as follows: Syntax: for (expression1; expression2; expression3) statement It is always possible to replace a for loop with the use of a while loop as below. expression1; while (expression2) { statement expression3; } expression1 is the initialization statement for the loop. It is always executed once. Then expression2 is evaluated. If it is found to be true, then the statement is executed. expression3 is then evaluated and control passes back to the beginning of the for loop again except that expression1 will never be evaluated again. An equivalent implementation of the factorial program with the use of a for loop is illustrated below. Example 6.6a: int i, j, factorial=1; … Scanner in=new Scanner(System.in); … // input i from the system input device to compute i’s factorial System.out.print(“i = “); i = in.nextInt(); … // assuming i being a positive integer for (j = 1; j <= i; j++) factorial = factorial * j; Note that it is quite common to use for statements in a nested manner like the one below. for (int i = 1; i <= 7; i++) { for (int j = 1; j <= i; j++) System.out.print("*"); 30 ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 System.out.print('\n'); } The above problem fragment produces the following output when executed. * ** *** **** ***** ****** ******* 6.7 Comma operator The comma (,) operator has the lowest precedence of all operators in Java. It allows joining of expressions and it associates from left to right. Syntax: expression1, expression2 The comma expression as a whole has the value and type of its right operand. Example 6.7a: int i; double j; … i = 0, j = 10; // comma expression The above comma expression has value 10 and type double. In fact, comma expressions are rarely used. Comma expressions may be used in the expressions of for loops occasionally. For example, Example 6.6 can be written as follows: Example 6.7b: int i, j, factorial; … Scanner in=new Scanner(System.in); … // input i from the system input device to compute i’s factorial System.out.print(“i = “); 31 ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 i = in.nextInt(); … // assuming i being a positive integer for (factorial=1, j = 1; j <= i; j++) factorial = factorial * j; 6.8 break and continue statements The break and continue statements interrupt the normal flow of control. In addition to cause an exit from a switch statement, the break statement also causes an exit from the innermost enclosing loop such as for, while or do-while loops. The break statement exits the loop without executing the rest of the code in the loop. Therefore, it should be very careful for using the break statement as it can exit the loop even if the test condition of the loop is still valid. The continue statement can be used in for, while, and do-while loops. Instead of exiting the loop without executing the remaining statements, a continue statement skips the rest of the code in the loop and moves on to the next iteration. Syntax: break; continue; The following program fragment accepts an integer from the keyboard and computes its square root repeatedly until the input number is negative. Example 6.8a: import java.util.*; import java.lang.*; public class ch6_8a { public static void main(String[ ] args) throws Exception { int i; Scanner in=new Scanner(System.in); for ( ; ; ) { // equivalent to while (true) i = in.nextInt(); if (i < 0) // condition to break from the endless loop break; //sqrt() is system function for computing square root System.out.println(Math.sqrt(i)); 32 ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 } } } The seemingly peculiar clause for ( ; ; ) stands for an endless loop as the second expression, which serves as a test to decide whether the for loop is to continue its execution, is null. The if statement with a break statement as its body gives a way to exit the otherwise endless loop. The following program fragment accepts 10 positive integers from the keyboard and computes their sum. Any negative numbers are skipped. Example 6.8b: import java.util.*; import java.lang.*; public class ch6_9b { public static void main(String[ ] args) throws Exception { int i,j,n; n = 10; i = 0; int sum = 0; Scanner in=new Scanner(System.in); while (i < n) { j = in.nextInt(); if (j <= 0) // to skip any negative number continue; ++i; sum += j; } System.out.print("The sum is : " + sum); } } Result: 33 ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 Teaching remark The use of break and continue statements may make a program’s control flow difficult to comprehend. 34 ALCS Curriculum 7 Programming (JAVA Programming) V1.1 12/1/2007 Arrays A sequence of data items of the same type can be stored in an array. Arrays are indexible and stored contiguously in the memory space. The elements of an array are accessed by the use of subscripts. In Java, the first array element is indexed by a subscript of zero (not one) and the arrays of all types are possible, including arrays of arrays. 0 1 2 3 4 5 6 1st element Array length of 7 The general syntax for defining an array is: Syntax: datatype[ ] array_name; array_name = new datatype[size]; where datatype is any system or user defined data types and size is the array size which can be a either zero or positive integer. 7.1 Array Declaration and Initialization Like other Java variables, an array is also needed to be declared. To declare an array in Java, we need to specify its elements’ data type, followed by a pair of square brackets [], and the name of identifier. For instance: int [] ages; Unlike the primitive data types like int or float, different arrays may take up various amounts of memory to store their elements. Thus, Java is unable to decide the amount of memory to be used when an array variable is declared. The actual space to be used can only be decided when an array object is created. An array variable in Java in fact serves as a pointer to some array object of the same data type. To create an array object, it is necessary to specify the total number of elements (i.e. size) in the array, with a constructor statement =new. For instance: int [] ages = new int[100]; The above statement not only declares ages as an integer array, but also creates an array object that can store up to 100 integers and makes ages point to that newly created array object. 35 ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 Example 7a: public class 7a { public static void main(String[ ] args) throws Exception { double[ ] temperature; temperature = new double[7]; // array to record one week’s average temperature[0] = 23.5; // first day’s temperature temperature[1] = 24.5; // second day’s temperature temperature[2] = 23.6; // third day’s temperature temperature[3] = 22.5; // fourth day’s temperature temperature[4] = 21.3; // fifth day’s temperature temperature[5] = 21.9; // sixth day’s temperature temperature[6] = 22.3; // seventh day’s temperature } } In the above example, the array elements are initialized with the use of multiple assignment statements. A simpler way to initialize the array is as follows: Example 7b: double[ ] temperature = {23.5, 24.5, 23.6, 22.5, 21.3, 21.9, 22.3}; In many Java programs, array elements are initialized in a looping structure. Suppose the temperatures in the above example are to be read in from the keyboard, the following for loop can be used. Example 7c: double[ ] temperature; temperature = new double[7]; … Scanner in=new Scanner(System.in); for (int j = 0; j < 7; j++) { System.out.println(“Enter average temperature of day” + (j+1)); temperature[j] = in.nextDouble(); } It is worth mentioning that multidimensional arrays are also supported. The syntax for defining a two dimensional array is given below. Syntax: datatype[][] array_name; array_name = new datatype[size1][size2] 36 ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 where size1 and size2 are the sizes of the two dimensions. Examples 7d: String[][] fare_table = new String[5][10]; … fare_table[0][1] = “Central to Causeway Bay = 4”; fare_table[0][2] = “Central to North Point = 6”; fare_table[0][3] = “Central to Kowloon Tong = 12”; fare_table[1][2] = “Causeway Bay to North Point = 3.5”; fare_table[1][3] = “Causeway Bay to Kowloon Tong = 12”; fare_table[2][3] = “North Point to Kowloon Tong = 11”; fare_table[...][...] = “...” In the above example, the array stores entries of a fare table in which, the first array dimension indicates source station and the second array dimension indicates the destination station. 37 ALCS Curriculum 8 Programming (JAVA Programming) V1.1 12/1/2007 Implementing Enumerated Types in Java Program maintainability can be enhanced if the program is intuitive and easy to read. Although Java provides a number of basic data types, such data types are not enough to enable programmers to define variables that possess certain characteristics. For example, although it is okay to represent the day of a week with an integer value from 0 to 6, allocating an integer variable to store the day of a week is not the best solution as the variable can take any out-of-range value too. Thus most programming languages offer ways for programmers to define their own data types to accommodate their application needs. Such data type is called enumerated type and is formally supported in Java JDK 1.5. Java’s enumerated type supports is rather sophisticated and a full introduction of it is beyond the scope of this chapter. The syntax for defining an enumerated type in Java is given below. Syntax: enum datatype {enumerator1, enumerator2, …, enumeratorN} Example 8.1: enum Day {MON, TUE, WED, THU, FRI, SAT, SUN} enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES } enum Season { WINTER, SPRING, SUMMER, FALL } Example 8.2: public enum Grade { DISTINCTION, PASS, FAIL }; …Grade myGrade;… switch (myGrade) { case DISTINCTION: System.out.println ("Congratulations!"); break; case PASS: System.out.println ("Good work."); break; case FAIL: System.out.println("Try harder next time.") break; }; 38 ALCS Curriculum 9 Programming (JAVA Programming) V1.1 12/1/2007 Elementary Program Design Issues If the software solution to a real-world problem is coded in a single monolithic piece, it will be difficult for programmers to read and comprehend. More importantly, it will be difficult to maintain. Thus programs are usually developed in accordance with some programming guidelines such as: 1. Flow of control in a program should be as simple as possible. 2. Programs should be developed in a top-down fashion. So far, we have only introduced a Java method called main() where execution begins. In general, a main() method rarely delivers any important program’s function by itself. Instead, it invokes a number of subordinate functions to achieve the program’s objectives. In Java, program functions are implemented by a feature known as method. Unlike C and Pascal in which a program is built with the use of functions and procedures, Java builds a program with classes. A class object or instance is composed of the data that describes some selected entity as well as the methods that manipulate those data. In general, a class instance cannot access the data of another class instance directly. Any access of data of another class instance can only be done with the help of that class instance. That is, if Object 1 needs some information from Object 2, it can only pass a request of information to Object 2. It is entirely up to Object 2 to decide what the request will be entertained. The benefit of such a design is that we know where to look at when any data of a class object is different from its expected value. Such a notion of encapsulating data and related functions in some well-defined structure called object is a core concept in object-oriented programming. Suppose we would like to develop a card game, an indispensable class to be introduced is a pack of cards. Such a pack_of_card class must have some data structure to represent the 52 cards in the pack and the methods that are used to handle the cards, e.g. shuffle cards (shuffle_pack()) and draw a card (draw_card()) from the pack, etc. To implement a particular card game, we may create another class called game which interacts with pack_of_card. If an instance of game needs to draw a card, it calls for the help of pack_of_card. Note that the pack_of_card class can be “reused” in other card games. In general, we should try to keep the code of a method no more than a couple of pages, preferably within one single page. If a method cannot be coded within a couple of pages, the programmers should consider decompose it further into a number of smaller methods. The key advantages of developing small methods are as follows: Problem complexity can be better managed. Collaborative program development is made possible. Well-defined methods can be used by different classes. Programs will be more maintainable. 39 ALCS Curriculum 9.1 Programming (JAVA Programming) V1.1 12/1/2007 Class A class can be considered as a template that defines the data and functional characteristics of some concerned entity. In our previous discussion, the pack_of_card class is composed of data structure to represent the 52 cards in the pack and the shuffle_pack() and draw_card() methods that are used to handle the cards. In general, a Java program does not store data in a class but instances or objects of the class. In fact, a class and its object in Java are analogous to a user-defined data type and its variable in C or Pascal. The word “public” in the class header is an access modifier or a scope identifier, which indicates that the class can be accessed by all objects and can be extended by other classes in the program. Every class must be given a unique class name, which is used to identify it. There are several naming rules to define a class name. Firstly, a class name must begin with a letter, underscore or a dollar sign. It can only contain the letters, digits, underscores or dollar signs. Besides, spaces should not be contained in the class name. As a convention, a class name usually begins with an upper-case letter, but it does not mandatory needed. All the code after the class header, including both data and methods, is considered as the class definition, which is body bounded with the braces {}. All Java applications must have a method called main() where program execution starts. 9.2 Method Definition Method is the basic building block to perform services and operations, which is similar to function and procedure in structured programming language. Every method in Java must begin with a method header. The basic syntax for the method header is as follows: access_modifier datatype method_name(datatype1 parameter1, datatype2 parameter2, …) The method header serves to describe the name of the method, the access modifier of the method, the method’s parameters and their data types (which can be a class), and the data type or class of data that the method returns. A typical method header contains at least the following parts: the data type or class of the return value, the method name and a list of parameters. Return value: For those methods that do not return any value, a “void” keyword is used. Method name: Method name is the name that identifies an individual method. Method parameter: Data that are needed by the method for its execution. Java methods have the following form. 40 ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 Syntax: access_modifier datatype method_name(datatype1 parameter1, datatype2 parameter2, …) { declarations statements } The data type identifier preceded the method name indicates the data type or class of the value returned by this method to its calling method. The value to be returned by a method is preceded by the return keyword. A return statement also returns the control to the caller method. In case of no value, but only the control, is required to be returned to its caller, a keyword void can be used to replace the data type identifier that precedes the method name. The data type identifier preceded a method’s parameter indicates the data type (or class) of the parameter value received from its caller. Note that the parameter list is optional. The radius() method in Example 9.1 lets the users to input the radius of the circle and the parameter() method perform the calculation for the parameter of the circle. Note that the static keyword indicates the method is a class method that is to be executable, even though no class objects have been created. Non-static methods can only be executed for a class instance or object. Example 9.2: public class ch9_1 { public static void main(String args[]) { int a,b,m; a = 9; b = 10; m = max(a,b); System.out.println("The greater value between " + a + " and is : " + m); } public static int max(int v1,int v2) { if (v1>v2) return v1; else return v2; } } Result 9.2 41 " + b + " ALCS Curriculum 9.3 Programming (JAVA Programming) V1.1 12/1/2007 Call-by-value and call-by-reference In many computer languages, the arguments of a function are passed call-by-value from a caller function to the function being invoked. This means that each argument is evaluated, and its value is then copied to the corresponding private (or local) space in the invoked function. Thus changing the value of an argument in an invoked function will not result in a change of the value of the corresponding argument in the caller function. In a call-by-reference parameter passing mechanism, an invoked function is passed an implicit reference to each of its arguments by its caller function rather than the argument value itself. If the invoked function is able to modify such a parameter, then any changes it makes will be visible to the caller function as well. When passing parameters of simple data type to a method, Java uses a call-by-value method. When a class instance or object is passed to a method as its parameter value, Java uses the call-by-reference approach. 9.4 Recursion A recursive method is a method which invokes itself, either directly or indirectly. Recursion can be replaced by iteration in most cases but some tasks can be naturally solved with recursive functions. Example 9.4a: public class test { public static void main(String args[ ]) { System.out.println(" 6 Factorial is : " + factorial(6)); } public static int factorial(int n) { if (n==1) // base case for termination return 1; return (n * factorial(n-1)); } } As shown in the example, a recursive function is composed by two parts: a base case for termination and a recursive part. The base case must be checked before the problem is reduced by calling the recursive part. Failing to achieve this may result in an endless loop. Note that in the above factorial example, the factorial function is executed n times before the base case is reached. This means that n copies of the program status 42 ALCS Curriculum Programming (JAVA Programming) V1.1 12/1/2007 (including all its variables’ values) of the factorial method are kept at one time. In general recursive functions are slow to run and memory-consuming. The major benefit of using recursion is that it may help save programming effort in certain cases that are more complicated to code if iteration is used instead. 43 ALCS Curriculum 10 Programming (JAVA Programming) V1.1 12/1/2007 File Handling The java.io.* header file is required for using the file handling functions in Java. The basic file handling functions are: 1. open a file for reading or writing 2. read/write the contents of a file 3. close the file Since the topic is rather factual, we do not intend to re-invent the wheel. Instead, readers are suggested to read the relevant parts at: http://www.javacoffeebreak.com/java103/java103.html 44