Professional Documents
Culture Documents
Java Lab Manual: Al-Quds University
Java Lab Manual: Al-Quds University
Table of Contents
Session 1...............................................................................................................................................4 HTML and Webdisk (Revision)...........................................................................................................4 1.1 Creating Web Pages using HTML.............................................................................................4 1.2 Adding Content to Web Page....................................................................................................5 Exercises..........................................................................................................................................5 Session 2...............................................................................................................................................6 Introduction to Java..............................................................................................................................6 2.1 Programming Languages...........................................................................................................6 2.2 Java Programming Language.....................................................................................................6 2.3 Setting Up Your Machine for Java Development......................................................................6 2.4 Writing, Compiling and Running Your First Java Application.................................................9 Exercises........................................................................................................................................11 Lab Extras......................................................................................................................................11 Session 3.............................................................................................................................................12 Working with NetBeans IDE..............................................................................................................12 3.1 IDE Software...........................................................................................................................12 3.2 NetBeans IDE..........................................................................................................................12 3.3 Debugging Your Program........................................................................................................14 3.4 Error Types in Java..................................................................................................................14 Exercises........................................................................................................................................16 Lab Extras......................................................................................................................................16 Session 4.............................................................................................................................................17 Variables, Data Types and Operations...............................................................................................17 4.1 Variables and Data Types........................................................................................................17 4.2 Operations on Variables...........................................................................................................19 4.3 Conversion between Data Types.............................................................................................22 4.4 Literal Values and Expressions................................................................................................23 Exercises........................................................................................................................................24 Lab Extras......................................................................................................................................24 Session 5.............................................................................................................................................25 Working with Java Applets................................................................................................................25 5.1 Idea of Applets.........................................................................................................................25 5.2 Writing and Compiling Applets...............................................................................................25 5.3 Embedding Applets into HTML..............................................................................................26 Exercises........................................................................................................................................27 Session 6.............................................................................................................................................28 Conditional Statements and User Input..............................................................................................28 6.1 if and if-else Statements...........................................................................................................28 6.2 Reading User Input..................................................................................................................29 6.3 Decision Making Based on User Input....................................................................................30 6.4 switch-case Statement..............................................................................................................31 Exercises........................................................................................................................................34 Lab Extras......................................................................................................................................34 Session 7.............................................................................................................................................36 Decision-Tree Applet.........................................................................................................................36 7.1 Adding User Controls to Applets.............................................................................................36 7.2 Handling Events of User Controls...........................................................................................38 7.3 Applets with NetBeans............................................................................................................39 Java Lab Manual by Yasser Jaffal (2008) 2
Exercises........................................................................................................................................40 Lab Extras......................................................................................................................................40 Session 8.............................................................................................................................................41 Loops and Variable scope..................................................................................................................41 8.1 What Are Loops?.....................................................................................................................41 8.2 while and do-while Loops........................................................................................................41 8.3 for Loop...................................................................................................................................43 8.4 Variable Scope.........................................................................................................................45 Exercises........................................................................................................................................46 Lab Extras......................................................................................................................................47 Session 9.............................................................................................................................................48 Arrays and Strings..............................................................................................................................48 9.1 What Are Arrays?....................................................................................................................48 9.2 Using Arrays in Java................................................................................................................48 9.3 Multidimensional Arrays (Arrays of Arrays)..........................................................................51 9.4 String as Arrays.......................................................................................................................53 Exercises........................................................................................................................................53 Lab Extras......................................................................................................................................54 Session 10...........................................................................................................................................55 Applications on Arrays (Databases)...................................................................................................55 10.1 What Are Databases?.............................................................................................................55 10.2 Implementing Databases using Arrays..................................................................................55 Exercises........................................................................................................................................56 Session 11...........................................................................................................................................57 Applets and Graphics.........................................................................................................................57 11.1 paint() Method.......................................................................................................................57 Exercises........................................................................................................................................59 Session 12...........................................................................................................................................60 Methods..............................................................................................................................................60 12.1 What Are Methods.................................................................................................................60 12.2 Writing and Calling Methods................................................................................................61 12.3 Passing by Value and Passing by Reference.........................................................................63 12.4 Recursion...............................................................................................................................63 Exercises........................................................................................................................................64 Session 13...........................................................................................................................................65 Object-Oriented Programming: Classes and Members......................................................................65 13.1 What is Object-Oriented Programming?...............................................................................65 13.2 Writing Classes in Java..........................................................................................................65 13.3 Different Properties of Class Members.................................................................................67 13.4 Methods and Constructors Overloading................................................................................69 Exercises........................................................................................................................................70 Lab Extras......................................................................................................................................71 Session 14...........................................................................................................................................73 Exceptions and Error Handling..........................................................................................................73 14.1 Exception-Throwing Methods...............................................................................................73 14.2 try-catch Exception Handling................................................................................................74 14.3 Writing Custom Exceptions...................................................................................................74 Exercises........................................................................................................................................76 Lab Extras......................................................................................................................................76
Creating web pages with rich contents. Uploading web pages to Webdisk. Accessing web pages from the Internet. Adding content to an uploaded web page.
5. Under operation field, write public_html and click on MkDir button, by doing this, you are creating a folder named public_html, this is the folder in which you will put your web pages. 6. Click on public_html to open it. It is now the current working directory. 7. Inside public_html, create another folder called lab1. After preparing your Webdisk, you are ready to create a web page and upload it, to create a simple HTML page, follow the following steps: 1. Start the notepad from Start --> All Programs --> Accessories --> Notepad (or simply type notepad in the run dialog Start --> Run) 2. Enter the following text: <html> <body> <h1> This is a Major Heading </h1> <ul> <li> List item one <li> List item two </ul> </body> </html> 3. Save your file as index.html 4. Back to Webdisk, under upload field, browse for your file (index.html) and click on Upload to upload your file to the server, make sure to upload it inside lab1 folder. 5. Using browser, confirm page at http://mail.alquds.edu/~s999/lab1 (where s999 should be replaced by your student profile login id). Java Lab Manual by Yasser Jaffal (2008) 4
The table that resulted from the above code is shown in figure 1.1 below.
Figure 1.1: HTML Table To link two pages together, we user the Hyperlink, to create a Hyperlink to another HTML page, use the following syntax: <a href="target_page"> Display Text </a>
Exercises
1. Create a page named index.html and upload it to lab1 folder in your public_html directory. 2. Modify index.html by adding a. A table, b. A Hyperlink to university's homepage (http://www.alquds.edu), and c. At least one image.
http://java.sun.com. After downloading the installation file (about 60 MB) you are ready to start the installation process. Follow the following procedure to prepare your machine. Step 1: Double click on jdk-1_5_0_06-windows-i586-p.exe icon, the setup wizard appears as in figure 2.2.
Figure 1.2: First step of JDK setup wizard Select I accept the terms in the license agreement and click on Next. Custom setup dialog appears as in figure 2.3.
Figure 2.3: Setup options It is advisable that you change the installation path by clicking on Change button and selecting the path "C:\jdk" as installation directory. After you have done changing the path, click on Next to start the installation and wait until its done. When installation is complete, click on Finish to terminate installation wizard. Java Lab Manual by Yasser Jaffal (2008) 7
Step 2: You need now to define some environment variables to be able to use the tools you've just installed. To define an environment variable, right-click on My Computer icon on the desktop or start menu, then select Properties from the pop-up menu. The System Properties dialog appears, from the top of the dialog box select Advanced tab as shown in figure 2.4. From Advanced tab, click on Environment Variables button, Environment Variables dialog appears as shown in figure 2.5.
2.4: Windows advanced settings To add new environment variable, click on New button in User Variables field, note that you may not modify system variables unless you have administrator privileges. Once you click on New button, variable addition dialog appears as in figure 2.6. In Variable name field enter the name of your variable, in Variable value field enter the value of the variable then click on OK. You need to add two variables to use with JDSK: PATH: points to bin directory in JSDK home directory (e. g. c:\jdk\bin) CLASSPATH: points to the folder in which you will create you Java programs (e. g. c:\Documents and Settings\Student\Desktop\java). Your computer is ready now to be used for Java development.
Figure 2.7: Command prompt To write a new Java program using the notepad, enter the command notepad filename. For instance, we will write a class named HelloWorld, so we will use the command notepad HelloWorld.java (Figure 2.8). Note that we use a .java extension for all Java source files, and we always use upper case characters in the beginning of a class name. After starting the notepad, it will Java Lab Manual by Yasser Jaffal (2008) 9
ask you whether you wish to create a new file with the name specified, confirm file creation. It is important to keep in mind that file name and class name must be the same, otherwise the compiler will generate an error message and the file will not compile.
Figure 2.8: notepad command with parameters In the notepad, write the following code (always keep in mind that Java is case-sensitive language, for example if you typed Class instead of class the compiler will report a syntax error) //HelloWorld.java /* This is my first java program. */ class HelloWorld{ public static void main(String[] args){ System.out.println("Hello World!"); System.out.println("How r u 2day?"); }//end of main method }//end of class When you are done with code writing, save the file and exit notepad. Your source code file is now ready for compilation, to compile a Java source code file, use the command javac filename. In our example, javac HelloWorld.java. If everything is alright, the compiler will terminate without any messages and go back to command prompt as shown in figure 2.9. After compilation, if you run dir command, you will notice that the compiler generated a new file called HelloWorld.class, this is the binary file JVM will execute. To run you application, use the command java ClassName , for our program, we will use java HelloWorld, if everything is alright, you shall see the program output on the screen. Notice that some lines in the program begin with //, these are called comments, compiler does not read comments, so whatever your write in them it will not affect the functionality of your program, the notations /* and */ declare the beginning and ending of a block of comments, so we call them multi-line comments.
10
Exercises
1. Change the HelloWorld.java program so that it displays Hola Mundo! instead of Hello World! 2. Try printing the following strings, what do they do? 1. "Hello \t World" 2. "Hello \n World" 3. Try to use print method instead of println. 4. Consider the following Useless class. Compile and run it, what does it do? public class Useless{ public static void main(String[] args){ System.out.println(java.util.Locale.getDefault()); }}
Lab Extras
Batch files are common in executing a series of shell commands, for example, you can write a batch file to create and delete folder instantly, by writing the appropriate commands in the notepad and saving the file with .bat extension. The file will look like the following: MD MyFolder RD MyFolder Note that we put each command in separate line. You can create a Java program that runs everywhere by putting it together with a batch file that does the following steps: 1. Adds the current folder to CLASSPATH by using the command SET CLASSPATH=. 2. Compiles the .java file. 3. Executes the program. Try to write a batch file that holds your name and runs a Java program that types your name on the command line. Add PAUSE command at the end of the batch file in order to freeze the screen after program execution to be able to see the results.
11
IDE NetBeans Forte for Java Borland JBuilder Microsoft Visual Studio Borland C++ Macromedia Dreamweaver Microsoft Visual Studio .NET Sharp Develop
We can notice from table above that we have various brands of IDEs, since we are interested in Java programming language in this course, we will focus on its IDEs. NetBeans is the best offered IDE for us as Java learners, because it is free compared to JBuilder, more advanced and stable compared to Forte. So lets start having a look at NetBeans.
Figure 3.1: NetBeans IDE main screen 2. After creating a project, you are ready to start coding, on the project explorer you will see a tree that has the project name you specified as root. Project is split into four folders: Source packages, Test packages, Libraries and Test libraries. Source packages is the folder containing the source code files (.java files) and hence it is the folder we are interested in. Source code is usually split into packages, so we can group classes of related functionality together. Once you create a project, a default package that holds project name is created. 3. In the code editor, you will see the created Main class, with its main method already coded, so you need just to start programming. 4. In the main method, try to write some statements you've learned from session 1, after you are done, you may compile and run the program by selecting Run > Run main project, pressing F6 key on the keyboard, or clicking Run button on the toolbar 5. The output window appears at the bottom of the IDE and shows the outputs of compilation and running processes. Java Lab Manual by Yasser Jaffal (2008) 13
Figure 3.2: Break points To show how debugging works, make a small test by following the procedure below: 1. Write the HelloWorld program from session 1. 2. Add a break point in the second line (System.out.println("How r u 2day?");). 3. Debug the program by pressing F5 key on the keyboard or by clicking on Debug button on the toolbar. 4. Observe the output of the program, what do you notice? 5. Notice that when debugger reaches a break point, it turns to green, this means that this is the next statement will be executed, as we put a break point on the second line, the statement is not executed until we select to continue, this can be done by pressing Ctrl +F5 or by clicking on Continue button on the toolbar. 6. To stop debugging, press Sift+F5 on the keyboard, or click on Stop button on the toolbar.
In Java (and other programming languages) there are two major types of errors: Compile-Time errors (Syntax errors). 14
Run-Time errors, these errors fall into two categories: exceptions and semantic errors. Compile time errors are those the compiler detects while translating your program from Java language to machine language, the most common reason for these errors is there is something in your code does not follow Java syntax (that's why we call them syntax errors). The following examples show some of these errors:
1. 2. 3. 4. 5. 6.
System.out.println("Hellow") system.out.println("Hello"); System.out.println("Hello); class Hello World{ Class HelloWorld{ public Static void main(string[] args){
OK, let's start with statement 1, what is wrong with it? Clearly Hello don't have "w" at the end of it! However, this is not the error we are looking for, we are looking for violation of Java language rules not English language rules. As we know, each statement in Java should be terminated with semicolon ";" which is absent in our case. The message the compiler will generate in this case is "';' expected", error message also includes the line in which error exists as shown in figure 3.3.
Figure 3.3: Compile-Time error message. In statement 2, you can notice that system is written in lower case, as we've learned before, Java is case sensitive, and as System is a class in Java, it starts with upper case letter. The message you will see in this case is "Cannot find symbol". This message means the keyword or member name you are calling is not recognized as valid one. The most common reason for this error is a spelling mistake. In statement 3 , the error message is "unclosed string literal", because the opening double quotation (") does not have a matching closing one. In statement 4, the error is that the given class name is not valid, as class name cannot have spaces according to naming conventions in Java (as we shall see in next session). The error message in this case is "'{' expected", the compiler assumes that class name finishes when it finds space, after the space it is expecting the opening bracket "{". In statement 5, the message generated is "class or interface expected", it is clear that class keyword must start with lower case letter as all keywords in Java do so. In statement 6, the message generated is "<identifier> expected", because Static is not a valid keyword. Notice that in this statements we have another error which is "cannot find symbol" because string is written mistakenly in lower case, but it will not be detected until first error is fixed because it appears first. Run-Time errors appear when program run, the compiler cannot detect them because there are no errors or rules violations. First category of run-time errors is exceptions, exception is a non expected error happens while executing a code, an example of exceptions is Java Lab Manual by Yasser Jaffal (2008) 15
ArithmeticException which occurs when you try to divide by zero. The second category are semantic errors, those are not actual errors detected by compiler, nor exceptions occur at runtime, but they are unexpected results or outputs of your program, for example, if your program is supposed to calculate the sum of three numbers, and we give it 1, 2 and 3 as inputs, its output should be 6, otherwise we have a semantic error. NetBeans can detect syntax errors while you type your program, so you can find them before compiling you program. The statement containing an error is underlined by red line, and you can see the error message by positioning the mouse pointer over the line as shown in figure 3.4. We will have a closer look at run-time errors and how to deal with them in the coming sessions.
Exercises
1. Create a project using NetBeans called MyFirstProject, and type a program to print your name and student ID each in separate line using only one println statement. 2. What is the error message expected from each of the following statements? (Also show if there is more than one error, and mention which one is detected first) 1. System.out.println(Hello World!); 2. System.out.pint("How are you?"); 3. public static void main(String[] args);{ 4. class My Class{ 5. public static void main(String() args){ 6. System.out.Print ln("Hi man!"); 7. System.out.print('What's up'); 8. System.out.println("I wonder where is the error?\m");
Lab Extras
You can add a new class to your default package and make it the default class to be run instead of Main class. To do this, right-click package in the project explorer, open Add menu and select Java Class from the list. Enter new class name and click OK to see your newly added class. Note that the Main class is still open and you can navigate between two class using tabs above source editor. To make your new class the default one (that is, it will run when you run the project), rightclick the project icon (Java cup) in the project explorer and select Properties from the menu. This will open up Project Properties dialog. From the tree on the left, select Run category, and type your class name in place of Main in Main Class text field. Be ware not to delete package name mistakenly. Now type a main method in your new class and put some code in it, run the project and you will see the result. You may also run a non-default class by right-clicking it in the project explorer and selecting run or using Shift + F6 keys while opening its code in the editor. Java Lab Manual by Yasser Jaffal (2008) 16
Table 4.1: Primitive data types in Java To declare a variable, use a statement with the following format: datatype variableName; Data type is one of primitive data types shown in table 4.1, variable name is a valid Java Java Lab Manual by Yasser Jaffal (2008) 17
variable name, the name is valid if it: Is not a reserved word. Is not the name of a previously defined variable, even of different type (unique). Starts with a letter ('A' to 'Z' or 'a' to 'z'), a dollar sign '$' or an underscore '_'. Contains only letters, dollar signs '$', underscores '_' and numbers. Has no spaces. In addition to previous conditions, we have some optional conventions but they are highly recommended to follow them in order to stay up with the global standards of Java. One of these conventions is to start class name (and each fragment in the name if it has more than one) with an upper-case letter like ClassName and MyFirstJavaClass. We will be talking about conventions as they appear. Here are some examples of declaring data types: int anInt; double d; float average; boolean done; long x1, x2, x3; As you can see, the first part is a primitive data type from table 4.1, and the second type is a valid name. You can notice from the last statement that we can define several variables of the same type by using commas ',' between names on the following format: datatype var_1, var_2, ..., var_n; A notable naming conventions in Java is the one we've used in the first statement, a variable name should start with a small letter, and each following fragment with a capital letter like variableName and averageOfMarks. So whats next? We have to assign some values in the variables we have just declared. Value and variable must be of the same type, for example, you cannot store 7.34 in a variable of type int (unless you convert). Table 4.2 shows examples of values and their appropriate data types.
Table 4.2: Examples of values and data types Java Lab Manual by Yasser Jaffal (2008) 18
As you can see, numerical values with decimal point are treated as double by default, if you want to assign them to a float variable, you have to explicitly define it as float using F after the value. The value 26.77e3 is equal to 26.77 * 103. To assign a value to a declared variable, we use assignment operation denoted by equality sign '=' in the following format variable = value; for example, to assign a value 10 to some integer x int x; x = 10; Assignment can be done in the same statement in which we declare the variable float average = 81.5f; boolean b = false; System.out.println(average);//prints "81.5" System.out.println(b);//prints "false"
Modulus (division remainder) % var1 % var Table 4.3: Arithmetic operations We have seen assignment before, and we know that is stores the value of right operand on the variable on the left operand. Addition, subtraction, multiplication and division operations generate expressions, an expression is a series of calculations that produces a single value. Here are some examples of expression: int a = c = d = a, b, c, d, e = 3; //variables definition b = 5; //multiple assignment 6; c % a;//d = 1 19
e = e + (a + b * c d);//expression evaluation (e = 37) System.out.println("The value of e is " + e); Comments on the previous code: It is valid to define multiple variables in the same statements and assign values to them (statement 1). You can assign single value to multiple variables in the same statement (statement 2). We can use brackets '(' and ')' to specify which expressions must be evaluated first (precedence overriding). By default, multiplication has the highest precedence, followed by division then addition and subtraction (in statement 5, b * c is calculated first). Mod operator calculates the remainder when dividing first operator on the second. We can concatenate a string with an integer by using "+" operator (last statement). We have some shortcuts with binary operations, for example, expression a = a + b, could be written in the form a += b, this way is valid for other operations as table 4.4 illustrates. Expression a = a + b a = a - b a = a * b a = a / b a = a % b a = a + 1 Shortcut a += b a -= b a *= b a /= b a %= b a++, ++a
a = a 1 a--, --a Table 4.4: shortcuts of expressions The difference between a++ and ++a is the value of the expression itself; at the end, both of them increment the value of a by one, but the value of a++ when evaluated is the original value of a, and the value of ++a is the incremented value. The following example shows the difference. int a, b, c; a = b = c = 1; a = ++b + c; System.out.println("a = " + a + ", b = " + b + ", c = " + c); b = a++ - 1; System.out.println("a = " + a + ", b = " + b + ", c = " + c); c = a + a++ + --b + b; System.out.println("a = " + a + ", b = " + b + ", c = " + c); If you compile and run the above program, you should see the following output: a = 3, b = 2, c = 1 a = 4, b = 2, c = 1 a = 5, b = 1, c = 10 Java Lab Manual by Yasser Jaffal (2008) 20
To clearly understand how it works, let's monitor the value of b before, during and after the execution of the statement a = ++b + c;. Before the execution, it is clear that b = 1, once the statement ++b executed, the value of b is incremented by 1, then the rest of expression is evaluated using the new value of b. This happened because we used pre-increment. If we use post-increment, the value of b will also be incremented, but when b++ itself is evaluated, it gives the old value of b before increment, so post increment does not affect the expression in which it is, but the following expressions. Boolean variables have different set of unary and binary operations according to the special data type they store, which is logical. Table 4.5 shows primary boolean operations. Operation Logical AND Logical AND Logical OR Logical OR Logical NOT Operator && & || | Usage op1 && op2 op1 & op2 op1 || op2 op1 | op2
Discussing the difference between && and &, and | and ||, when we use && or ||, op2 is not evaluated when the value of the whole expression could be determined by the value of op1 and the operation. For example, true || false expression does not evaluate the second operand, because the logical OR between true and any other boolean expression is always true, similarly, false && true does not evaluate the second operand because logical AND between false and any other boolean expression is always false. In addition to these operations, there are also comparison operations which we apply to numerical variables to get boolean results, table 4.6 shows comparison operations. Operation Equals Greater than Greater or equals Less than Less or equals Operator == > >= < <= Usage op1 == op2 op1 > op2 op1 >= op2 op1 < op2 op1 <= op2
!= op1 != op2 Does not equal Table 4.6: Comparison operations The following example evaluates some boolean expressions and prints their results. boolean b1, b2, b3; b1 = true || false; b2 = b1 && (5 > 3); b3 = b2 && (13 == 6); System.out.println("b1=" + b1 + ", b2=" + b2 + ", b3=" + b3); Java Lab Manual by Yasser Jaffal (2008) 21
If you compile and run the above code you should get the following output: b1=true, b2=true, b3=false Once again, we have used concatenation to convert the whole output to string, the next section focuses more on conversion.
conversion explicitly, another type of conversion is called implicit conversion (promotion), because it is done automatically without requiring the programmer to request that conversion, for example, concatenating an integer or a character with a String converts them automatically to a string. int x = 10; String s = "x equals " + x; In the above code, the value of x which is 10 is converted from integer to string and concatenated with the previous string "x equals ". Promotion also occurs when an expression of values from different types is evaluated. In general, promotion converts all operands to the largest data type among them. The following code shows an example. int x = 10; double d = 12.5; float f = 1.5f; double result = (d/f) + x; System.out.println("The result is " + result); If you run the above code, you will see the output The result is 18.33333333. The expression was evaluated as the following: 1. The value of f is converted to double and d/f is evaluated, clearly, the result is of type double. 2. The value of x is converted to double and added to the previous expression. 3. The whole expression is evaluated to type double And stored in result.
From the above example we can notice different expression types: literal value: by defining the value we wish to store in the variable literally. For example, assigning 8 directly to an integer, 'a' directly to a character or "Hello" directly to a string. Expression: expressions are evaluated in runtime to generate a single value, for example, the expression 1 + 3 5 evaluate at runtime and generate a final value of -1. Methods: Some methods returns a value of certain type, one of them is the previously discussed parseInteger() method which returns an integer generated from some string.
23
Exercises
1. Assuming that a = 3, b = 5, c = 1, x = 2, y = -2, and z = 6 and following precedence rules. Evaluate each expression of the following independently and mention any changes in the variable values after expression is evaluated (all variables are integers): (a / c) + z / a c++ + b / x y x + ++x * x- --a * ++a (z++ * z++) (true && (5 > 7)) || ((3 <= 10) && !false)) (3 < 6) || (c++ == x) 2. Write a program that evaluates all the expressions in exercise 1 and prints the result on the screen. 3. Write a program that calculates a + b + c + d and prints the result on the screen where: a, b, c and d are integers. a is assigned a literal value of 3. b is assigned a value of 6 using an arithmetic expression of 3 literal values. c is assigned a value of 2 generated from an expression of a and b. d is assigned a value of 4 converted from a string using parseInt() method. The result is printed directly without defining a new variable to store the result.
Lab Extras
Some variables are declared using final keyword, final means that the value remains constant at the time of execution and it is assigned during compile time. The value of a final variable cannot be modified once it is assigned. The final keyword is used before specifying data type in variable declaration. final int MAX_VALUE = 100; It is important to realize that you can assign a value to a final variable only once. You can only assign the value in the same statement in which you define the variable, so the following statements are invalid. final int MAX_VALUE; MAX_VALUE = 100;
//Error
As you can see, the naming convention of final variables is to use upper letters and underscores "_".
24
You cannot run Applets using java command. Applets have no main(String[] args) method, instead, there is a method called init(). To run an Applet, you have to embed it in a HTML page using special tag. Applets are graphical, not command-line applications.
There are some important notes about writing Applet code: We use import keyword to get classes from libraries into our source files. Class should be declared using public keyword, this enables access to it from web browsers. To let Java deal with this class as Applet, add extends Applet to class declaration. Applets have two important methods: init() method: This method is like main(String[] args) method in Java applications, the Applet starts execution from this method. paint(Graphics g) method: This method is dedicated for painting on the Applet, the variable g (called object) has a lot of drawing methods like drawString(), drawLine(), drawOval() and so on. We will discuss them in details later. After writing the class, we compile it as usually with javac command. To run the applet, we need to put it inside HTML page. The following section discusses this task.
26
Notice that our Applet does nothing except drawing the text Hello World at the point (50, 25) of the frame. To see exactly where this point is located, we have to understand the coordinations of the Applet. Have a look at figure 5.2 below. x+ (50, 25)
(0, 0) y+
(getWidth(), getHeight()) Figure 5.2: Coordinations of Applet As you can see, the upper-left corner has the coordinates (0, 0). The value of x increases from left to right, and the value of y increases from up to down. So to locate the point (50, 25), start from the upper-left corner and take 50 pixels to right then 25 pixels downward. To get the width of the whole Applet, call getWidth() method, to get the height of the whole Applet, call getHeight() method.
Exercises
1. Write the HelloApplet class and compile it. 2. Create a web page to run HelloApplet. 3. Create a new folder in your public_html folder on Webdisk named lab2 and upload HelloApplet.class and the web page into it. 4. Run your Applet from the web.
27
else{ System.out.println("x is negative"); } } Using technique like on in the above example may make the code more complex and harder to understand, instead, we can use else-if statement, by which we can check unlimited number of condition, and making decision for each one separately. The format of if-else statement is the following: int x = 5; if(x > 0){ System.out.println("x is positive"); } else if(x < 0){ System.out.println("x is negative"); } else if(x == 0){ System.out.println("x is zero"); } Using else before each if statement means that if one of the conditions is met no other condition will be checked.
29
import java.io.*; class ReadFromUser{ public static void main(String[] args) throws IOException{ String userName; BufferedReader in; in = new BufferedReader( new InputStreamReader(System.in)); System.out.println("Enter your name: "); userName = in.readLine(); System.out.println("Welcome " + userName); } } The above code asks the user to enter his name, reads the input using readLine() method which returns a String value that represents user input from keyboard, then concatenates it with "Welcome" and prints it on the screen.
30
//x is even if(x % 2 == 0){ System.out.println("positive and even"); } //x is odd else{ System.out.println("positive and odd"); } } //x is negative else{ //x is even if(x % 2 == 0){ System.out.println("negative and even"); } //x is odd else{ System.out.println("negative and odd"); } } }//end of main() }//end of class As you can see, we converted the String we read from user to integer because it is easier to compare, another reason may lead us to this conversion, is that switch-case statement accepts only integers and numerical values or characters, and it cannot accept strings. The following section covers switch-case statement.
//Statement(s) to be executed if //variable = value_n break; } As you can see, we put some variable in switch then follow it by several case blocks. Execution goes through cases one by one comparing each one with the value of the variable specified in switch statement, then executes it and all cases that follows, unless we use break keyword to avoid the execution from expanding to unwanted statements. The following example shows how to use switch-case statement. import java.io.*; class SwitchCaseDemo{ public static void main(String[] args) throws IOException{ BufferedReader in; in = new BufferedReader( new InputStreamReader(System.in)); System.out.println("1. Print your name"); System.out.println("2. Print your age"); System.out.println("3. Exit"); int choice; choice = Integer.parseInt(in.readLine()); switch(choice){ case 1: System.out.print("Enter your name: "); String name = in.readLine(); System.out.println("Welcome " + name"); break; case 2: System.out.print("Enter your age: "); String age = in.readLine(); System.out.println("You are " + age); break; case 3: System.exit(0); }//End switch }//End main }//End class The following code shows how cases are executed, the following program enters all cases.
32
int x = 1; switch(x){ case 1: System.out.println("x = 1"); case 2: System.out.println("x = 2"); case 3: System.out.println("x = 3"); } You can notice that the value of x meets the first case only, but all three cases are executed, this states that switch-case statement does not automatically exit after one a case value is met. So the output of the previous code is the following: x = 1 x = 2 x = 3 To prevent such behavior, use break statement after the end of each case, which exits the whole switch block. A special case that is executed without checking the value of the variable is called default case, we use default keyword instead of case keyword to specify the default case. Because we usually use break after each case, default block is executed when the value of the variable did not match any of specified cases value. To see how this works, add a default case to our previous SwitchCaseDemo class (shown in boldface) and try to enter any value other than 1, 2 and 3. switch(choice){ case 1: System.out.print("Enter your name: "); String name = in.readLine(); System.out.println("Welcome " + name"); break; case 2: System.out.print("Enter your age: "); String age = in.readLine(); System.out.println("You are " + age); break; case 3: System.exit(0);
33
Exercises
1. Write a program that specifies whether a given number (x) falls in one of the following categories (give x a value from the code, don't read from user): 0 to 9 10 to 19 20 to 29 None of the categories For example, if x = 5, program should print "0 to 10", and if x = 44 it should print "None". Hint: use if statements with boolean expressions combined using &&. 2. Write a program that reads two integers and prints their sum like the code below (text shown in boldface is supposed to be user input). Enter the first number: 3 Enter the second number: 4 2. The sum is 7 3. Write a program that asks the user to enter two numerical values (integers) and then select an operation (addition, subtraction, multiplication and division) then prints the result based on operation selected. The code below shows examples of the output (text shown in boldface is supposed to be user input). Enter first number: 4 Enter second number: 2 1. 2. 3. 4. Addition (+). Subtraction (-). Multiplication (*). Division (/).
Lab Extras
There is an easier way to read from user, which depends on showing a dialog box for the user and let him enter his input in a text box inside that dialog. To use this input dialog we import the library called javax.swing, this library contains classes that deal with GUI. What we interested in among the classes of this library is a class called JOptionPane and a method inside it called showInputDialog(). The following example shows how to use this technique to read from user. import javax.swing.*; class EasyRead{ Java Lab Manual by Yasser Jaffal (2008) 34
public static void main(String[] args){ String userInput; userInput = JoptionPane.showInputDialog("your name: "); System.out.println("Hello " + userInput + " !"); } } You can notice here that we do not declare any objects and no exceptions to throw. An easy and straight forward method. The output of the above code is a dialog box like the image 7.1. If user clicks OK the input is read and returned as String, if he click Cancel dialog box closes without returning any input entered.
35
Adding user controls to Applets. Handling events of user controls. Reading and writing values to user controls. Including external packages.
public void init(){ b = new Button("Click Me!"); t = new TextField("Type in me!"); } As the above code shows, we use the new keyword to initialize the controls. The statement that follows new keyword is a call to the constructor, which is a special type of methods written specifically to initialize objects. Don't bother yourself with it now. The string we pass to Button constructor is the text we want to appear on it. Similarly, the text we pass to TextField constructor is the default text that will appear in it. We have now declared and initialized controls, the step left is to add these controls to the Applet. Although these controls are declared inside Applet's class, they are not graphically added hence not yet visible to the user. To make them visible, we add them to the Applet using add() method. Code below shows a full example. //Step 1: import import java.awt.*; import java.applet.Applet; public class SimpleApplet extends Applet{ //Step 2: declare controls Button b1, b2; TextField tf; public void init(){ //Step 3: initialize controls b1 = new Button("Button 1"); b2 = new Button("Button 2"); tf = new TextField("Type something"); //Step 4: add controls (adding order affects appearance) add(b1); add(tf); add(b2); } } If you compile and run the above Applet, you'll get something like this (figure 7.1).
37
public class SimpleApplet extends Applet implements ActionListener{ //Step 2: declare controls Button b1, b2; TextField tf; public void init(){ //Step 3: initialize controls b1 = new Button("Button 1"); b2 = new Button("Button 2"); tf = new TextField("Type something"); //Step 4: add controls (adding order affects appearance) add(b1); add(tf); Java Lab Manual by Yasser Jaffal (2008) 38
add(b2); //Step 5: add action listener b1.addActionListener(this); b2.addActionListener(this); } //This method will run when buttons are clicked. public void actionPerformed(ActionEvent e){ Object cause = e.getSource(); if(cause == b1){ tf.setText("Button 1 Was Clicked"); } else if(cause == b2){ tf.setText("Button 2 Was Clicked"); } } } Code inside actionPerformed() method needs some explanation, we call e.getSource() to know which button was clicked, then store it in cause. Then we compare cause which all buttons we have to find out which button was clicked in order to perform the appropriate action. To change the value displayed in the text field, call setText() method and pass a String representing text you want to appear in it. To read the text typed in the text field call its getText() method. String valueOfTextField = tf.getString(); You can also use a control name Label to add text labels to the Applet. Label l = new Label("Some text"); add(l);
39
Exercises
1. Write a calculator Applet that has two int fields (Use awb.IntField class), named register and accumulator, and four buttons named setReg, setAccum, add and power. The behavior of these buttons should be as the following: Button Set Reg Set Accum Add Job Sets register int field to 0 Sets accumulator int field to 0 Sums the values in register and accumulator and leaves the result in accumulator Raises accumulator value to the power of the value of register leaving the result in accumulator
Power
Lab Extras
You can specify the width of text field by providing the number of columns in the constructor. For example, the following code creates a text field with 20 columns width. TextField t = new TextField(20); TextArea a = new TextArea(20, 20; //Text field with multiple lines
40
3 4 5 6 7 8 9 10 It is clear that the value of x affected the execution of the loop, as you can derive from the output, the condition is true until x reaches 11. We can also use break to exit the loop. int x = 1; while(true){ //infinite loop System.out.println(x); if(x == 10){ break; } } using break in the above code exits the loop when x = 10. The do-while loop like while loop uses boolean expression to determine whether or not go to next iteration. The difference between it and while loop is the sequence of execution, do-while loop body appears before the condition, this implies that even if the condition is false, the loop will execute at least one time. The format of the do-while loop is the following. do{ //Loop body }while(condition); if we repeat the last example using do-while, the code will look like this: int x = 1; do{ System.out.println(x++); }while(x <= 10); The output will be the same of previous example. So how can we clearly see the difference? Consider the following two loops. //while //do-while int x = 0; int x = 0; while(x != 0){ System.out.println(x); } Output: do{ System.out.println(x); }while(x != 0); Output: 0 Java Lab Manual by Yasser Jaffal (2008) 42
As you can see, although the condition was initially false, do-while loop executed one time, but while loop was not executed.
To better understand the concept of for loop, write and execute the following program. class ForLoopDemo{ public static void main(String[] args){ for(int x = 1; x <= 10; x++){ System.out.println(x); } } } The flow of execution of for loop is the following: 1. Initialization is executed once. 2. Test-condition is checked to determine whether or not loop body should be executed. 3. Loop body execution. 4. Post-statement are executed. 5. Back to step 2 through 4 until the stop condition is false, then loop exits. Another example of for loop is the program that prints out the results of multiplications from 1 to 12. class MultiplicationTable{ public static void main(String[] args){ for(int i = 1; i <= 12; i++){ for(int j = 1; j <= 12; j++){ Java Lab Manual by Yasser Jaffal (2008) 43
int k = i * j; System.out.println(i + " * " + j + " = " + k); } } } } In the above example, we used nested loops, that is, a loop inside the body of another loop, we can use as many levels of nesting as we need. Be ware that when we use nested loops, the inner loop executes until the end in one iteration of the outer loop, because the whole inner loop is one statement in the body of outer loop. Combining loops and conditional statements, we can build powerful applications that do complex jobs. For instance, we will create a program that determines whether a given number is a prime or not. import javax.swing.*; class Prime{ public static void main(String[] args){ int x; String userInput; userInput=JOptionPane.showInputDialog("Enter a number"); x = Integer.parseInt(userInput); //1, 2 and 3 are prime numbers if(x == 1 || x == 2 || x == 3){ System.out.println(x + " is prime"); } //All even numbers > 2 are not prime else if(x % 2 == 0){ System.out.println(x + " is not prime"); }else{ //We have to check using division remainder //we initially suppose that x is prime boolean prime = true; //No number has factor greater than it's half for(int i = 3; i <= x / 2; i++){ if(x % i == 0){ //We have found a factor //so x is not prime prime = false; break; } } if(prime){ System.out.println(x + " is prime"); } else{ System.out.println(x + " is not prime"); } Java Lab Manual by Yasser Jaffal (2008) 44
} } } To get more familiar, try to understand the following program that keeps reading numbers (integers) from user until input is 0, then prints average, sum, maximum and minimum. import java.io.*; class Numbers{ public static void main(String[] args) throws IOException{ int min, max, x, sum = 0, count = 0; boolean firstNumber = true; BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); while(true){ System.out.print("Enter a number: "); x = Integer.parseInt(in.readLine()); if(x == 0){ break; }
if(firstNumber){ min = max = x; firstNumber = false; } sum += x; if(x > max){ if(x < min){ count++; } System.out.println("Sum = " System.out.println("Average System.out.println("Minimum System.out.println("Maximum } } + = = = sum); " + sum / count); " + min); " + max); max = x; min = x; } }
45
int x = -3; if(x < 0){ int y = x * -1; System.out.println("Absolute value of " + x + " is " + y); } In the previous code, x has scope inside and outside if block, while y is only visible inside if block, if you try to call y from outside if block, you will get error message "Cannot resolve symbol". int x = -3; if(x < 0){ int y = x * -1; } System.out.println("Absolute value of " + x + " is " + y); //Error Variable scope extends from outer block to inner blocks regardless of the number of levels, but not vise-versa. //Visible: None for(int i = 1; i <= 12; i++){ //Visible: i for(int j = 1; j <= 12; j++){ //Visible: i, j, k int k = i * j; System.out.println(i + " * " + j + " = " + k); } //Visible: i } //Visible: None
Exercises
1. Write a program that reads 10 numbers from the user then prints out how many positive numbers and negative numbers user has entered (consider 0 a positive number). 2. Modify calculation program in session 4 exercise 3 by adding the following question at the end of the program: Do you want to make another calculation? 1. Yes 2. No Enter your option: If user selects yes (by entering 1), program will ask him again to enter new two numbers and select operation, if user selects no (by entering 2), program exits. Use appropriate loop to accomplish this. 3. Write a program that asks the user to enter certain number, after that asks him to enter Java Lab Manual by Yasser Jaffal (2008) 46
another 20 numbers, after entering them all, it prints out the number of occurrences of the first number. See the below example (text shown in boldface is supposed to be user input). Enter number to search for: 2 Enter a number: (20 times) 2 3 56 7 9 2 4 5 5 6 2 21 33 19 32 88 0 32 100 20 The number (2) occurred 3 times in your input. 4. What is the output of the following program? for(int i = 0; i < 5; i++){ for(int j = 0; j < i; j++){ System.out.print(" "); } System.out.print(i * j); System.out.println(""); }
Lab Extras
We use continue keyword to skip some statements inside loop body and start new iteration, consider the following program that prints out factors of 30. for(int i = 1; i <= 30; i++){ if(30 % i != 0){ continue; } System.out.println(i); } As you can see, when 30 is not divisible by i, we use continue to jump to the next iteration without executing the next line that prints the output.
47
Figure 9.1: Array Structure As Figure 9.1 shows, the size of an array is fixed, we will refer to array maximum size as array length, it is also clear that indices of an array are zero-based, that is, they start from 0 to length 1; for example, the array shown in Figure 9.1 has a length of 10 (stores up to 10 elements), and the last index is 9.
48
To access array members, use array name with desired index specified between square brackets [ ]. int[] x = new int[3]; x[0] = 5; //Store 5 in the first index x[1] = 10; //Store 10 in the second index x[2] = 15; //Store 15 in the third index System.out.println(x[2] + x[1]); //Prints 25 If you try to access an index out of the range of array (greater or equals array length) JVM will throw an IndexOutOfRangeException. int[] x = new int[3]; //Valid indices are 0, 1 and 2 x[3] = 7; //IndexOutOfRangeException Another technique to declare an array is to directly provide its members between brackets { and }, separated using commas ','. int[] x = {10, 15, 20, 25, 100}; //Length = 5 System.out.println(x[3]); //Prints 25 String[] days = {"Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri"}; //We are leaving in Monday System.out.println("We are leaving in " + days[2]); It is common to deal with arrays using for loop, we can use length property to determine the length of the array. The following code stores multiples of 3 in an array then prints them from greater to smaller. int[] a = new int[20]; for(int i = 0; i < a.length; i++){ a[i] = i * 3; } for(int i = a.length 1; i >= 0; i){ System.out.print(a[i] + " "); } The following example stores names and numbers of n students and performs search. import javax.swing.*; class Students{ public static void main(String[] args){ int[] numbers; String[] names; String input = JOptionPane.showInputDialog("Enter number of students");
49
int size = Integer.parseInt(input); numbers = new int[size]; names = new String[size]; for(int i = 0; i < numbers.length; i++){ names[i] = JOptionPane.showInputDialog("Enter Student name"); input = JOptionPane.showInputDialog("Enter Student number"); numbers[i] = Integer.parseInt(input); } /* Now we have all numbers and names, index will bind two arrays together, that is, student in index 5 has his name in names[5] and his number stored in numbers[5] */ //Search for student int x; do{ input = JOptionPane.showInputDialog("Enter student number"); x = Integer.parseInt(input); boolean found = false; for(int i = 0; i < numbers.length; i++){ if(numbers[i] == x){ JOptionPane.showMessageDialog(null, "Name: " + names[i]); found = true; break; } } if(!found){ JoptionPane.showMessageDialog(null, "Not found"); } //Ask if the user wants to perform another search. input = JoptionPane.showInputDialog("Search again? Y/N"); }while(!input.equalsIgnoreCase("N")); } }
Comments on the previous program: Array index could be used to relate data from different arrays together. Java Lab Manual by Yasser Jaffal (2008) 50
Output could be provided using JOptionPane.showMessageDialog() method (Remember to provide null as first parameter (parent window) ). String class has method called equalsIgnoreCase that compares two strings together regardless of their case. There is also another method called equals that makes casesensitive comparison between strings.
System.out.print(a[i][j] + " "); } System.out.println(""); } The output of the above code is the following: 0 0 1 0 1 2 0 1 2 3 As you can see, we filled the array above with sub-arrays. Two dimensional arrays are common in representing matrices, for example, we can write a program that adds two matrices (remember that matrices must have same number of rows and same number of columns when it comes to addition). import javax.swing.*; class Matrices{ public static void main(String[] args){ String input; int rows, columns; input = JOptionPane.showInputDialog("Enter number of rows"); rows = Integer.parseInt(input); input = JOptioPane.showInputDialog("Enter number of columns"); columns = Integer.parseInt(input); int[][] matrix1 = new int[rows][columns]; int[][] matrix2 = new int[rows][columns]; String m1 = "Enter first matrix elements\n"; String m2 = "Enter second matrix elements\n"; for(int i = 0; i < rows; i++){ for(int j = 0; j < columns; j++){ input = JOptionPane.showInputDialog(m1+"["+i+"]["+j+"]"); matrix1[i][j] = Integer.parseInt(input); } } for(int i = 0; i < rows; i++){ for(int j = 0; j < columns; j++){ input = JOptionPane.showInputDialog(m2+"["+i+"]["+j+"]"); matrix2[i][j] = Integer.parseInt(input); } Java Lab Manual by Yasser Jaffal (2008) 52
} int[][] result = new int[rows][columns]; String output = ""; for(int i = 0; i < rows; i++){ for(int j = 0; j < columns; j++){ result[i][j] = matrix1[i][j] + matrix2[i][j]; output += result[i][j] + "\t"; } output += "\n"; } JOptionPane.showMessageDialog(null, "Result is\n" + output); } }
Exercises
1. Write a program that reads 10 integers from the user and then prints them out in reverse order. 2. Write a program that reads names and marks of 10 students then prints the names of the Java Lab Manual by Yasser Jaffal (2008) 53
students with the highest and lowest marks. 3. Write a program that reads 16 integers from the user, stores them in 5 by 4 matrix, the last row of the matrix should contain the sums of the columns (see figure 9.2) calculated by your program. Then the whole matrix is printed. 4 User input 3 1 8 7 8 3 1 1 9 4 5 8 5 5 6
Lab Extras
You may have noticed that when we declare the main method we specify an array of strings String[] args. This array stores command-line arguments and it could be used as input method in addition to input methods we discussed earlier. To see how it works, first we should know how to provide command line arguments, when we run a class we use the following command. java ClassName arg_1 arg_2 ... arg_n The arguments we provide after class name are stored in args array, the number of arguments determine the length of the array, notice that arguments are separated by spaces. The following example shows how to read numbers from command line and print their sum. class QuickSum{ public static void main(String[] args){ int sum = 0; for(int i = 0; i < args.length; i++){ sum += Integer.parseInt(args[i]); } System.out.println("sum = " + sum); } } Here is an example of the the execution of the above code. java QuickSum 3 4 6 2 sum = 15 In NetBeans IDE, you can add command line arguments by opening project properties, selecting "run" node from properties tree on the left, then entering arguments in "Arguments" field separated by spaces.
54
Understand the concept of databases. Implementing databases using arrays. Performing search and update.
What we are willing to do now is to see how can we represent this table in Java and modify or retrieve data from it.
vendor[0] = "Mazda"; color[0] = "Red"; model[0] = 1988; To represent the whole table, we can declare arrays as following. String[] vendor = {"Mazda", "Honda" , "Fiat", "Honda", "Nissan"}; String[] color = {"Red" , "Silver" , "Blue", "Red" , "Black" }; int[] model = { 1988 , 1995 , 2000 , 2002 , 2000 }; It is possible now to search inside this table, for example, to find the cars manufactured in year 2000, we can do something like this. for(int i = 0; i < model.length; i++){ if(model[i] == 2000){ System.out.println(vendor[i] + " - " + color[i]); } } In a similar way, we can search by color or by vendor. Additionally, we can update table data by updating arrays contents. For example, the following code sets all cars colors to red. for(int i = 0; i < color.length; i++){ color[i] = "Red"; }
Exercises
1. Write Java Applet that implements cars table. Your applet should have three buttons, a text field and a text area (TextArea class is like TextField but have multiple lines). It should look like figure 10.2 below. The following table shows how should this Applet behave. Button Vendor Model Color Behavior Performs search using car's vendor and gives full details about each matching car in the text area Similar to By Vendor, but performs search using model Similar to By Vendor, but performs search using color
56
Using paint() method to draw on Applets. Calling getGraphics() to draw after Applet initialization. Introducing different methods of Graphics object.
57
Figure 11.1: Line Applet The following example draws a circle at the upper-left corner of the Applet with the specified radius. Notice how do we use drawOval() method. import java.awt.*; import java.awt.event.*; import java.applet.Applet; public class Circles extends Applet implements ActionListener{ TextField value; Button draw; public void init(){ resize(400, 400); draw = new Button("Draw"); value = new TextField(); draw.addActionListener(this); add(value); add(draw); } public void actionPerformed(ActionEvent e){ Graphics g = getGraphics(); int diameter = Integer.parseInt(value.getText()) * 2; g.drawOval(0, 0, diameter, diameter); } } Figure 11.2 on the next page shows an example of circles Applet. Java Lab Manual by Yasser Jaffal (2008) 58
Exercises
1. Write a Java Applet that has 5 int fields, named x1, x2, y1, y2 and radius. Add two buttons to your Applet named line and circle. The behavior of these buttons should be as shown in table 11.3 below. Button Line Circle Functionality Draws line from (x1, y1) to (x2, y2) Draws circle centered on (x1, y1) and has the radius of the value entered in radius text field Table 11.3
Session 12 Methods
Objectives Introducing method structure. Writing and calling methods. Understanding return types and void methods. Differentiating between passing by value and passing by reference.
60
instead of just printing it out, consider the situation in which we need to use our method to calculate the sum of four values instead of two, it can be reached using second technique through calling the method more than one time. int z = sum(sum(2, 3), sum(1, 6));//z = 12 In the above example, sum is called 3 times, first time with 2 and 3 so it returns 5, second time with 1 and 6 so it returns 7, and the third time with the result of two previous calls 5 and 7 so it returns 12 which is the final result that is stored in z. Lets have a look at more complex methods, and more useful ones. In the next example, we will try to simplify the process of reading input by putting all of its steps in a single method with single call. import java.io.*; class ReadingSimplifier{ public static void main(String[] args){ String name = readString("Enter your name:"); int age = readInt("Enter your age:"); System.out.println("Welcome " + name); System.out.println("Your birth year is " + (2007 age)); } static String readString(String message){ System.out.print(message); BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); try{ String input = in.readLine(); return input; }catch(Exception e){} return ""; } static int readInt(String message){ String input = readString(message); return Integer.parseInt(input); } } You can see how we simplified reading from user by putting all necessary statements in a method called readString that takes a string as parameter, this string is the message that will be displayed for the user as input prompt, readString also returns a string that represents the value entered by user. We use try and catch instead of throwing the exception, this eases code writing by handling the exception so we no more need to declare our methods to throw it. The second method we used is called readNumber, it takes a string to display for the user, passes it to readString and get the value returned from it, then converts the returned value to integer and returns it. Java Lab Manual by Yasser Jaffal (2008) 62
12.4 Recursion
We can write a method that calls itself, these methods are called recursive methods, a recursive method calls itself with different parameters to do certain job. For example, consider the following method that calculates the factorial of a given integer n. static int factorial(int n){ //Base case if(n == 0 || n == 1){ return 1; } Java Lab Manual by Yasser Jaffal (2008) 63
//Recursive call return n * factorial(n 1); } As you can see, we build recursive methods using a base case and a recursive call, the base case is the condition at which we stop the recursion. In the above code, for example, the base case is when n is equal to 0 or 1, both numbers have the factorial 1. The recursive call is executed if the base case is not reached yet (i.e. there are more recursive calls until job is done), in case of factorial, we build our recursive call using the mathematical fact which states that n! = n (n 1)!, so we return n multiplied by the factorial of n 1. For example, if we tried to get the factorial of 4, the execution of the method will flow like this: 1. (n = 4) Is 4 = 0 or 4 = 1? No, so return 4 * (4 1)! (recursive call) 2. (n = 3) Is 3 = 0 or 3 = 1? No, so return 3 * (3 1)! (recursive call) 3. (n = 2) Is 2 = 0 or 2 = 1? No, so return 2 * (2 1)! (recursive call) 4. (n = 1) Is 1 = 0 or 1 = 1? Yes, so return 1 (base case) 5. 1 is returned to the previous call and multiplied by 2 6. The result of multiplication (2) is returned to the previous call and multiplied by 3 7. The result of multiplication (6) is returned to the previous call and multiplied by 4 8. The result of multiplication (24) is returned by the method as final result.
Exercises
1. Write a method named maxPosition that takes an array of integers as array and returns the index of the maximum element in the array. 2. Write a method named countChar that takes two parameters: a string and a character, then returns an integer representing number of occurrences of the character in the string. 3. Write a method named average that takes array of doubles as parameter then returns the average of the values inside the array. Sum calculation process should also be included in method called sum that takes the array as parameter and returns the sum of its elements. 4. Write a void method called reverse that takes a string as parameter and prints it in reverse order and inverted letter case, for example if the input is "Java", the output should be "AVAj". Hint: use integer values of characters to determine upper and lower cases. 5. You will be given a lab on recursion on separate sheet and you have to solve it.
64
We define this set of attributes and behavior in a class called Car, after creating this class, we can define several objects of this class, that is, the class defines common properties among all cars, and each object represents different car, so we may have, for example, objects like these: 1. Car A: Color: red, Manufacturer: Nissan, Man. year: 1998, Transmission: Normal. 2. Car B: Color: black, Number of wheels: 6. 3. A.Start engine, A.Move forward and so on. By the same way, we can represent any real-life object or any other object at any field, like circles and triangles in representation of geometrical shapes.
//Constructor public Circle(double r){ radius = r; } //Methods public double getRadius(){ return radius; } public double getArea(){ return (radius * radius) * Math.PI; } public double getCircumference(){ return 2 * Math.PI * radius; } public double getDiameter(){ return radius * 2; } } The above class contained members declared using public keyword, this keyword means that the member is accessible from outside the class, that is, when we declare an object from the class Circle, we can access all public members, even if we declare the object outside Circle class. You can also notice a method that holds the same name of the class and does not has a return value, actually, we call it constructor, constructors are used to determine the initial values necessary to build objects and are used after new keyword in declaration, for example, when declaring a Circle object, we need to specify the radius of that circle, because all circle measurements are based on the radius, so we write a constructor that takes radius as double. If we don't write a constructor for our class, Java creates a default constructor that takes no parameters, but once we write a constructor, the default constructor is no more available. To declare a Circle object, we use something similar to variable declaration. Circle c1 = new Circle(10); Circle c2 = new Circle(12); System.out.println("c1 Area is " + c1.getArea()); System.out.println("c2 Diameter is " + c2.getDiameter()); As shown above, declaring objects is straight forward, all you have to do is to specify class name from which you create the object followed by object name, then you initialize the object using new keyword followed by a constructor with necessary parameters. When we call a member from the object, we use dot '.' to access the members then specify member name. As we declared radius to be public, we can access it just like any other members to change the radius after declaration. Circle c1 = new Circle(10); Java Lab Manual by Yasser Jaffal (2008) 66
System.out.println("c1 Area is " + c1.getArea()); c1.radius = 15; System.out.println("c1 Area is now " + c1.getArea());
} } The following example shows the difference between static and non-static variables: class StaticTest{ private static int a; private int b; public StaticTest(){ a = 0; b = 0; } //Accessors public static int getA(){ return a; } public int getB(){ return b; } //Mutators public static void setA(int newA){ a = newA; } public void setB(int newB){ b = newB; } } class Main{ public static void main(String[] args){ StaticTest s1 = new StaticTest(); StaticTest s2 = new StaticTest(); System.out.println("s1 values:"); System.out.println("a =" + s1.getA() + ", b =" + s2.getB()); System.out.println("s2 values:"); System.out.println("a =" + s2.getA() + ", b =" + s2.getB()); s1.setA(5); s1.setB(3); System.out.println("\ns1 values:"); System.out.println("a =" + s1.getA() + ", b =" + s2.getB()); System.out.println("s2 values:"); System.out.println("a =" + s2.getA() + ", b =" + s2.getB()); } } Compiling and running the above code shows the following output: s1 values: a =0, b =0 s2 values: a =0, b =0
68
s1 values: a =5, b =3 s2 values: a =5, b =0 So what can be concluded from the output? The value of b is different for each object, changing the value of b in object s1 did not affect the value of b in s2, which is not the situation with a, because changing the value of a in s1 had its effect in a when called from s2, thats because static members are shred among all objects as stated, variable a and methods related to it could be called from the class name directly as shown below: StaticTest.setA(13); System.out.println(s1.getA() + " " + s2.getA()); In the above code, println method will print 13 two times. Remember to declare static methods when dealing with static variables, back to StaticTest class definition, for example, you can notice that getA and setA methods are declared static.
Rectangle c = new Rectangle(3, 4);//First constructor It is important to realize that discriminating between constructors and methods holding the same name are: 1. Number of parameters. 2. Order of parameters. 3. Types of parameters. So it is important to know that parameter name has nothing to do with overloading, the following example shows this. //This code generates error message. class A{ private int value; public void setValue(int t){ value = t; } public void setValue(int s){ value = s; } } To better understand classes and objects, lets analyze a well-known statement we've been using repeatedly: System.out.println("Hello World"); System is a name of a class, inside System class, there is a public and static member (object) of class PrintWriter, the name of this object is out. Inside PrintWriter class, there is a public, non-static method called println that has several overloads.
Exercises
1. Write a class that represents triangle named Triangle, the class must have the following members: private double height;//Height private double base;//Base length public Triangle(double h, double b);//Constructor public void setHeight(double x);//Sets height public double getHeight();//Gets height public void setBase(double x);//Sets base length public double getBase();//Gets base length public double getArea();//Returns the area of the triangle 2. Write a class Employee that represents an employee of some organization, the class should contain the following members: private int id;//Employee id private String name;//Employee name private int type;//1 = employee, 2 = manager Java Lab Manual by Yasser Jaffal (2008) 70
private double baseSalary;//Base salary public Employee(int _id, String _name);//Constructor public void setID(int x);//id mutator public void setName(int x);//name mutator public int getID();//id accessor public String getName();//name accessor public double getSalary(); //if manager, add 10% to base salary public void setBaseSalary(double bs);//sets base salary.
Lab Extras
When we wish to specify a member from the class, we can use this keyword, this refers to the current object of the class. For example, to discriminate between local and global variables in a class that have the same name, we use this to specify which one in in the scope of whole class. class Square{ private int sideLength; public Square(int sideLength){ this.sideLength = sideLength; } public void setSideLength(int sideLength){ //global local this.sideLength = sideLength; } } As you can see, we have two variables called sideLength, one is global for the whole class and it is where we store the value, and other is local for the constructor (or method), when we call this., we are returning back to the scope of the class, so if we are to specify any member after this, it has to be a global member. Another use of this keyword is to call a constructor from within another constructor, this itself represents the call, so what you have to do is to pass parameters to this just like the way you pass them to any constructor. This technique is common when writing default constructor that does not require user to specify parameters. class Vector{ private double length; private double angle; public Vector(double length, double angle){ this.length = length; this.angle = angle; } public Vector(){ /* Calling the previous constructor, Java Lab Manual by Yasser Jaffal (2008) 71
passing 1 as length and 0 as angle */ this(1, 0); } } If you need to specify additional statements in the constructor from which you are calling another constructor, these statements should be specified after this call, in other words, when using this to call another constructor, it should be in the first statement.
72
is to read method, which originally called it, because this last one is also declared to throw that exception, it also throws it as it is to main method, which originally called it, finally, the exception is throws to JVM which prints it out on the screen so the user can know there was error.
exceptions to handle custom errors that may occur during program execution. A custom exception is a class that inherits Exception class or any of its subclasses, since inheritance is beyond the scope of this course, we will define it as using extends Exception in class declaration. class MyCustomException extends Exception{ private String message; public MyCustomException(String message){ this.message = message; } public String toString(){ return message; } } To use your custom exception, declare an object of it and throw that object using throw keyword. It is optional to declare the method containing throw statement with throws keyword. In the following example, the program reads student id, this id should be of length 7 and consists only of digits, otherwise it throws an exception.
class InvalidIDException extends Exception{ private String message; public InvalidIDException(String message){ this.message = message; } public String toString(){ return message; } } Import javax.swing.*; class StudentsData{ public static void main(String[] args){ String id, name; name = JOptionPane.showInputDialog("Enter student name"); id = JOptionPane.showInputDialog("Enter student ID"); try{ verfyID(id); } catch(InvalidIDException e){ JoptionPane.showMessageDialog(null, e.toString()); } Java Lab Manual by Yasser Jaffal (2008) 75
} public static void verifyID(String id) throws InvalidIDException{ if(id.length() != 7){ throw new InvalidIDException("Check ID length"); } try{ Long.parseLong(id); } catch(Exception err){ throw new InvalidIDException("ID can contain only digits"); } } }
Exercises
1. Write a program that count how many prime numbers between minimum and maximum values provided by user. If minimum value is greater than or equal to maximum value, the program should throw a InvalidRange exception and handle it to display a message to the user on the following format:Invalid range: minimum is greater than or equal to maximum. For example, if the user provided 10 as maximum and 20 as minimum, the message should be: Invalid range: 20 is greater than or equal to 10.
Lab Extras
In order to access the exception from the class it uses, there is an important aspect one should be aware of which is packaging, packaging means putting two or more classes in the same package by stating package name before declaring class (and also exceptions). When two classes are in the same package, it is possible to access any one of them from the other, for example, if we have a class named Student that represents a student, another class named Main to run a program that manages student information, and a third class called StudentDataException that represent any errors in student information, we can access Student and StudentDataException classes from Main class and define several objects of it if we use the following statement before each class declaration: package studentinfo; In NetBeans IDE, there is no need to manually write the above statement, by adding new class to any package of your project, that class is automatically declared as a part of that package. Figure 14.1 shows packages and classes in NetBeans IDE project explorer.
76
Figure 14.1: Packages (shown as golden cubes) and classes in NetBeans IDE project explorer To access a class from its package we simply provide package name followed by dot '.' then desired class name. For example, we can access Main class show in Figure 14.1 by calling it in the following statement: linkedlist.Main
77