Appendix ava Primer In this appendix,we present a primer for people who are unfamiliar with the Java language.This introduction is intended to allow you to develop the Java skills necessary to understand the programs in this text.It is not a complete Java reference;for a more thorough coverage of Java,consult the Bibliographical Notes.We do not assume that you are familiar with object-oriented principles, such as classes,objects,and encapsulation,although some knowledge of these topics would be helpful.If you are already familiar with C or C++,the transition to Java will be smooth,because much Java syntax is based on C/C++. E.1 Basics In this section,we cover basics such as the structure of a basic program,control statements,methods,classes,objects,and arrays. E.1.1 A Simple Program A Java program consists of one or more classes.One class must contain the main()method.(A method is equivalent to a function in C/C++.)Program execution begins in this main method.Figure E.1 illustrates a simple program that outputs a message to the terminal.The main()method must be defined as public static void main(String args[]),where String args[]are /* The first simple program */ public class First f public static void main(String args[]){ /output a message to the screen System.out.println("Java Primer Now Brewing!"); Figure E.1 A first Java program. 1
E Appendix Java Primer In this appendix, we present a primer for people who are unfamiliar with the Java language. This introduction is intended to allow you to develop the Java skills necessary to understand the programs in this text. It is not a complete Java reference; for a more thorough coverage of Java, consult the Bibliographical Notes. We do not assume that you are familiar with object-oriented principles, such as classes, objects, and encapsulation, although some knowledge of these topics would be helpful. If you are already familiar with C or C++, the transition to Java will be smooth, because much Java syntax is based on C/C++. E.1 Basics In this section, we cover basics such as the structure of a basic program, control statements, methods, classes, objects, and arrays. E.1.1 A Simple Program A Java program consists of one or more classes. One class must contain the main() method. (A method is equivalent to a function in C/C++.) Program execution begins in this main method. Figure E.1 illustrates a simple program that outputs a message to the terminal. The main() method must be defined as public static void main(String args[]), where String args[] are /* The first simple program */ public class First { public static void main(String args[]) { // output a message to the screen System.out.println("Java Primer Now Brewing!"); } } Figure E.1 A first Java program. 1
Appendix E Java Primer optional parameters that may be passed on the command line.Output to the screen is done via the call to the method System.out.println().Note that Java supports the C++style of comments,including /This string is a comment for single-line comments and /And this string too is a comment for multiline comments. The name of the file containing the main()method must match the class name in which it appears.In this instance,the main()method is in the class First.Therefore,the name of this file must be First.java.To compile this program using the Java Development Kit (JDK)command line compiler,enter javac First.java on the command line.This will result in the generation of the file First.class.To run this program,type the following on the command line java First Note that java commands and file names are case sensitive. E.1.2 Methods A program usually consists of other methods in addition to main().Figure E.2 illustrates the use of a separate method to output the message Java Primer Now Brewing!In this instance,the String is passed to the static method printIt(), where it is printed.Note that both the main()and printIt()methods return void.Later examples throughout this chapter will use methods that return values.We will also explain the meaning of the keywords public and static in Section E.1.6. public class Second public static void printIt(String message){ System.out.printIn(message); } public static void main(String args[]){ printIt ("Java Primer Now Brewing!"); } Figure E.2 The use of methods
2 Appendix E Java Primer optional parameters that may be passed on the command line. Output to the screen is done via the call to the method System.out.println(). Note that Java supports the C++ style of comments, including // This string is a comment for single-line comments and /* And this string too is a comment */ for multiline comments. The name of the file containing the main() method must match the class name in which it appears. In this instance, the main() method is in the class First. Therefore, the name of this file must be First.java. To compile this program using the Java Development Kit (JDK) command line compiler, enter javac First.java on the command line. This will result in the generation of the file First.class. To run this program, type the following on the command line java First Note that java commands and file names are case sensitive. E.1.2 Methods A program usually consists of other methods in addition to main(). Figure E.2 illustrates the use of a separate method to output the message Java Primer Now Brewing! In this instance, the String is passed to the static method printIt(), where it is printed. Note that both the main() and printIt() methods return void. Later examples throughout this chapter will use methods that return values. We will also explain the meaning of the keywords public and static in Section E.1.6. public class Second { public static void printIt(String message) { System.out.println(message); } public static void main(String args[]) { printIt("Java Primer Now Brewing!"); } } Figure E.2 The use of methods
E.1 Basics 3 E.1.3 Operators Java uses the +-*operators for addition,subtraction,multiplication,and division,and the operator for the remainder.Java also provides the C++ autoincrement and autodecrement operators +and--.The statement ++T;is equivalent to TT 1.In addition,Java provides shortcuts for all the binary arithmetic operators.For example,the +operator allows the statement T =T 5;to be written as T +=5. The relational operators are ==for equality and !for inequality.For example,the statement 4 ==4 is true,whereas 4 !4 is false.Other relational operators include <=>=>Java uses&as the and operator and II as the or operator. Unlike C++,Java does not allow operator overloading.However,you can use the operator to append strings.For example,the statement System.out.println("Can you hear "+"me?"); appends me?to Can you hear. E.1.4 Statements In this section,we cover the basic statements for controlling the flow of a program. E.1.4.1 The for statement The format of the for loop is as follows: for (initialization;test;increment){ /body of for loop } For example,the following for loop prints out the numbers from 1 to 25. int i; for(i=1;i<=25;i++){ System.out.println("i="+i); Note that,when the body of the for loop consists of only one line,the braces of the loop can be eliminated.Also,the index of the for loop can be declared within the for statement,rather than prior to the statement.Therefore,the previous loop could have been written as follows: for (int i=1;i <=25;i++) System.out.println("i="+i); When the index is declared in the for loop,the scope of the index is only within the for statement.The index of a for loop must be an integer(int).Java data types are discussed in Section E.1.5
E.1 Basics 3 E.1.3 Operators Java uses the +-*/ operators for addition, subtraction, multiplication, and division, and the & operator for the remainder. Java also provides the C++ autoincrement and autodecrement operators ++ and --. The statement ++T; is equivalent to T = T + 1. In addition, Java provides shortcuts for all the binary arithmetic operators. For example, the += operator allows the statement T=T + 5; to be written as T += 5. The relational operators are == for equality and != for inequality. For example, the statement 4 == 4 is true, whereas 4 != 4 is false. Other relational operators include < <= >= >. Java uses && as the and operator and || as the or operator. Unlike C++, Java does not allow operator overloading. However, you can use the + operator to append strings. For example, the statement System.out.println("Can you hear " + "me?"); appends me? to Can you hear. E.1.4 Statements In this section, we cover the basic statements for controlling the flow of a program. E.1.4.1 The for statement The format of the for loop is as follows: for (initialization; test; increment) { // body of for loop } For example, the following for loop prints out the numbers from 1 to 25. int i; for (i = 1; i <= 25; i++) { System.out.println("i = " + i); } Note that, when the body of the for loop consists of only one line, the braces of the loop can be eliminated. Also, the index of the for loop can be declared within the for statement, rather than prior to the statement. Therefore, the previous loop could have been written as follows: for (int i = 1; i <= 25; i++) System.out.println("i = " + i); When the index is declared in the for loop, the scope of the index is only within the for statement. The index of a for loop must be an integer (int). Java data types are discussed in Section E.1.5
Appendix E Java Primer E.1.4.2 The while statement The format of the while loop is as follows: while(boolean condition is true){ /body of loop The format of the do-while loop is as follows: do /body of loop while (boolean condition is true); As is the case for the for loop,if the body of either the while or the do-while loops is only one statement,the braces can be eliminated. E.1.4.3 The if statement The format of the if statement is as follows: if (boolean condition is true){ /statement(s) else if (boolean condition is true){ /other statement(s) else /even other statement(s) If there is only a single statement to be performed if the Boolean expression is true,then the braces can be eliminated. E.1.5 Data Types Java provides two different varieties of data types:primitive and reference(or nonprimitive).Primitive data types include boolean,char,byte,short, int,long,float,and double.Reference data types include objects and arrays. E.1.6 Classes and Objects Objects are at the heart of Java programming.An object consists of data and methods that access(and possibly manipulate)the data.An object also has a state,which consists of the values for the object's data at a particular time. Objects are modeled with classes.Figure E.3 is a class for a Point.The data for this class are the x and y coordinates for the point.An object-which is an instance of this class-can be created with the new statement.For example,the statement Point ptA new Point(0,15);
4 Appendix E Java Primer E.1.4.2 The while statement The format of the while loop is as follows: while (boolean condition is true) { // body of loop } The format of the do-while loop is as follows: do { // body of loop } while (boolean condition is true); As is the case for the for loop, if the body of either the while or the do-while loops is only one statement, the braces can be eliminated. E.1.4.3 The if statement The format of the if statement is as follows: if (boolean condition is true) { // statement(s) } else if (boolean condition is true) { // other statement(s) } else { // even other statement(s) } If there is only a single statement to be performed if the Boolean expression is true, then the braces can be eliminated. E.1.5 Data Types Java provides two different varieties of data types: primitive and reference (or nonprimitive). Primitive data types include boolean, char, byte, short, int, long, float, and double. Reference data types include objects and arrays. E.1.6 Classes and Objects Objects are at the heart of Java programming. An object consists of data and methods that access (and possibly manipulate) the data. An object also has a state, which consists of the values for the object’s data at a particular time. Objects are modeled with classes. Figure E.3 is a class for a Point. The data for this class are the x and y coordinates for the point. An object—which is an instance of this class—can be created with the new statement. For example, the statement Point ptA = new Point(0,15);
E.1 Basics creates an object with the name ptA of type Point.Furthermore,the state of this object is initialized to x=0 and y=15.We initilize objects using a constructor. A constructor looks like an ordinary method except that it has no return value and it must have the same name as the name of the class.The constructor is called when the object is created with the new statement.In the statement Point ptA new Point(0,15);,the values 0 and 15 are passed as parameters to the constructor,where they are assigned to the data xCoord and yCoord. With the Point class written the way it is,we could not create a point using the statement Point ptA new Point () because there is no constructor that has an empty parameter list.If we wanted to allow the creation of such an object,we have to create a matching constructor. For example,we could add the constructor shown in Figure E.4 to the class Point.Doing so allow us to create an object using the statement Point ptA new Point();.In this case,the x and y coordinates for the point are initialized to 0. Having two constructors in the Point class leads to an interesting issue.In some ways,a constructor behaves like an ordinary method.Two constructors for this class essentially means two methods with the same name.This feature of object-oriented languages is known as method overloading.A class may class Point /constructor to initialize the object public Point(int i,int j){ xCoord =i; yCoord j; /exchange the values of xCoord and yCoord public void swap(){ int temp; temp xCoord; xCoord yCoord; yCoord temp; public void printIt()f System.out.println("X coordinate ="xCoord); System.out.println("Y coordinate ="yCoord); } /class data private int xCoord;//X coordinate private int yCoord;//y coordinate Figure E.3 A point
E.1 Basics 5 creates an object with the name ptA of type Point. Furthermore, the state of this object is initialized to x = 0 and y = 15. We initilize objects using a constructor. A constructor looks like an ordinary method except that it has no return value and it must have the same name as the name of the class. The constructor is called when the object is created with the new statement. In the statement Point ptA = new Point(0,15);, the values 0 and 15 are passed as parameters to the constructor, where they are assigned to the data xCoord and yCoord. With the Point class written the way it is, we could not create a point using the statement Point ptA = new Point(); because there is no constructor that has an empty parameter list. If we wanted to allow the creation of such an object, we have to create a matching constructor. For example, we could add the constructor shown in Figure E.4 to the class Point. Doing so allow us to create an object using the statement Point ptA = new Point();. In this case, the x and y coordinates for the point are initialized to 0. Having two constructors in the Point class leads to an interesting issue. In some ways, a constructor behaves like an ordinary method. Two constructors for this class essentially means two methods with the same name. This feature of object-oriented languages is known as method overloading. A class may class Point { // constructor to initialize the object public Point(int i, int j) { xCoord = i; yCoord = j; } // exchange the values of xCoord and yCoord public void swap() { int temp; temp = xCoord; xCoord = yCoord; yCoord = temp; } public void printIt() { System.out.println("X coordinate = " + xCoord); System.out.println("Y coordinate = " + yCoord); } // class data private int xCoord; // X coordinate private int yCoord; // Y coordinate } Figure E.3 A point