Al-Quds University

Faculty of Science and Technology Computer Science Department

Java Lab Manual
(Version 2)

(For CS102: Programming Fundamentals)

Prepared by: Yasser Jaffal

Java Lab Manual by Yasser Jaffal (2008)

1

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

Java Lab Manual by Yasser Jaffal (2008)

3

Under operation field. 5. to create a simple HTML page. this task is achieved by following the instructions below. Accessing web pages from the Internet.1 Creating Web Pages using HTML As you have learned in CS101. Inside public_html. After preparing your Webdisk. 3.html 4. First of all. It is now the current working directory. To create the web folder. Click on public_html to open it. Java Lab Manual by Yasser Jaffal (2008) 4 . you are creating a folder named public_html. you have to create you personal web folder (if you haven't do so yet). you are ready to create a web page and upload it. follow the following steps: 1. 4. by doing this. browse for your file (index. From the tool bar. 5. Run Internet Explorer. make sure to upload it inside lab1 folder. What you are asked to do today is to create a web page and uploading it to your Webdisk. 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. Adding content to an uploaded web page. Using browser.html) and click on Upload to upload your file to the server. Save your file as index. Uploading web pages to Webdisk.edu/~s999/lab1 (where s999 should be replaced by your student profile login id).edu Enter your student profile login information to access your mailbox. confirm page at http://mail. this is the folder in which you will put your web pages. images and other media. Start the notepad from Start --> All Programs --> Accessories --> Notepad (or simply type notepad in the run dialog Start --> Run) 2. 1.alquds. Go to web page: http://mail. follow the following steps: 1.Session 1 HTML and Webdisk (Revision) Objectives: ● ● ● ● Creating web pages with rich contents. create another folder called lab1.alquds. 6. tables. 2. Back to Webdisk. Pages written with HTML could contain text. click Webdisk icon. write public_html and click on MkDir button. 7. under upload field. we use HTML language to write web pages.

Create a page named index. 2.1: HTML Table To link two pages together. use the following code: <img src="image_name"></img> Also.1. At least one image.1 below.html and upload it to “lab1” folder in your public_html directory. and c. A table. you can add a table to your page by using the following code (Suppose we are creating a 2 by 2 tabls) by adding the following code. to create a Hyperlink to another HTML page. Java Lab Manual by Yasser Jaffal (2008) 5 . we user the Hyperlink. use the following syntax: <a href="target_page"> Display Text </a> Exercises 1. A Hyperlink to university's homepage (http://www.html by adding a. Figure 1. Modify index. <table border=1> <tr> <td> Row 1 Column <td> Row 1 Column </td> <tr> <td> Row 2 Column <td> Row 2 Column </tr> </table> 1 </td> 2 </td> 1 </td> 2 </td> The table that resulted from the above code is shown in figure 1.2 Adding Content to Web Page To add an image to your web page.edu).alquds. b.

1 shows a Java technology overview. compile and execute Java applications. ● Software Development Kit (SDK) that contains the following: ■ Libraries: also known as Application Programming Interface (API). Figure 2. but they instead compile it into partially compiled file that could be executed by a program called interpreter.1 Programming Languages By programming language. ● Introduce Java programming language. grammar and libraries that construct a language we can use to write computer programs. ■ Interpreter: some programming languages does not compile the source code file into directly executable form (native code). that is. ● Syntax (grammar): set of rules that constraint the way in which programs are written. A program that does not follow these rules has one or more syntax errors. ● Show how to set up your system environment for Java development. when the source code is compiled into binary file.Session 2 Introduction to Java Objectives: ● Introduce programming languages. This SDK could be obtained from Java official site at Java Lab Manual by Yasser Jaffal (2008) 6 .exe. Figure 2. we mean a set of vocabulary. compile and run your first Java application "Hello World". ■ Compiler: the program that translates files written in Java language (human language) into binary files (machine language) in order for the computer to be able to execute them. ● Write. these files are previously written classes and methods that contain some common functionality.exe.1: Java technology 2. and interpreter is called java.3 Setting Up Your Machine for Java Development To be able to write. Java compiler is called javac. 2. A programming language consists of the following: ● Vocabulary: set of meaningful keywords that have specific meaning in the programming language (also called reserved words). 2. it needs an interpreter called Java Virtual Machine (JVM) to run it.2 Java Programming Language Java programming language is an interpreted programming language. you need a set of tools called Java Software Development Kit (JSDK).

the setup wizard appears as in figure 2. Step 1: Double click on jdk-1_5_0_06-windows-i586-p. After downloading the installation file (about 60 MB) you are ready to start the installation process. click on Next to start the installation and wait until its done. Java Lab Manual by Yasser Jaffal (2008) 7 . When installation is complete. Follow the following procedure to prepare your machine.exe icon.sun.com. 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. Custom setup dialog appears as in figure 2.2: First step of JDK setup wizard Select I accept the terms in the license agreement and click on Next.http://java. Figure 1. After you have done changing the path.3.2. click on Finish to terminate installation wizard.

Java Lab Manual by Yasser Jaffal (2008) 8 . To define an environment variable. note that you may not modify system variables unless you have administrator privileges. 2.Step 2: You need now to define some environment variables to be able to use the tools you've just installed.4. You need to add two variables to use with JDSK: ● PATH: points to bin directory in JSDK home directory (e. c:\Documents and Settings\Student\Desktop\java). Environment Variables dialog appears as shown in figure 2. click on New button in User Variables field.5. Your computer is ready now to be used for Java development. In Variable name field enter the name of your variable. Once you click on New button. in Variable value field enter the value of the variable then click on OK. click on Environment Variables button. g. The System Properties dialog appears. From Advanced tab. then select Properties from the pop-up menu. g. right-click on My Computer icon on the desktop or start menu.4: Windows advanced settings To add new environment variable. from the top of the dialog box select Advanced tab as shown in figure 2. variable addition dialog appears as in figure 2. c:\jdk\bin) ● CLASSPATH: points to the folder in which you will create you Java programs (e.6.

7. so we will use the command notepad HelloWorld. After starting the notepad.8). For instance.Figure 2. Figure 2.4 Writing.java extension for all Java source files. Change to the directory you have selected as Java directory (for example c:\Documents and Settings\Student\Desktop\java) by using cd command. open the command prompt by selecting run from start menu and entering the command cmd in the dialog box. Compiling and Running Your First Java Application To write a Java program. show in figure 2. enter the command notepad filename. the command prompt console appears. it will Java Lab Manual by Yasser Jaffal (2008) 9 . we will write a class named HelloWorld. Note that we use a .java (Figure 2.5: Environment Variables Figure 2.6: Adding new environment variable dialog box 2.7: Command prompt To write a new Java program using the notepad. and we always use upper case characters in the beginning of a class name.

use the command java ClassName . Notice that some lines in the program begin with //. It is important to keep in mind that file name and class name must be the same. the notations /* and */ declare the beginning and ending of a block of comments. */ class HelloWorld{ public static void main(String[] args){ System.8: notepad command with parameters In the notepad.9: successful compilation Java Lab Manual by Yasser Jaffal (2008) 10 .out. for example if you typed Class instead of class the compiler will report a syntax error) //HelloWorld. to compile a Java source code file.java. javac HelloWorld. this is the binary file JVM will execute.out. if everything is alright. In our example.class.9. write the following code (always keep in mind that Java is case-sensitive language. we will use java HelloWorld. }//end of main method }//end of class When you are done with code writing.println("How r u 2day?"). Figure 2. After compilation. Your source code file is now ready for compilation. Figure 2. otherwise the compiler will generate an error message and the file will not compile. save the file and exit notepad.println("Hello World!"). compiler does not read comments. these are called comments. so we call them multi-line comments.ask you whether you wish to create a new file with the name specified. if you run dir command. so whatever your write in them it will not affect the functionality of your program. you shall see the program output on the screen. To run you application. If everything is alright. confirm file creation. you will notice that the compiler generated a new file called HelloWorld.java /* This is my first java program. the compiler will terminate without any messages and go back to command prompt as shown in figure 2. System. for our program. use the command javac filename.

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. 2. "Hello \n World" 3. The file will look like the following: MD MyFolder RD MyFolder Note that we put each command in separate line. Executes the program.util. Try to write a batch file that holds your name and runs a Java program that types your name on the command line.println(java. }} Lab Extras Batch files are common in executing a series of shell commands. Java Lab Manual by Yasser Jaffal (2008) 11 .java program so that it displays Hola Mundo! instead of Hello World! 2. You can create a Java program that runs everywhere by putting it together with a batch file that does the following steps: 1. what does it do? public class Useless{ public static void main(String[] args){ System. Try printing the following strings. 4. by writing the appropriate commands in the notepad and saving the file with . Adds the current folder to CLASSPATH by using the command SET CLASSPATH=. "Hello \t World" 2.bat extension.Locale. Consider the following Useless class. Change the HelloWorld. Compile and run it. for example. Compiles the .java file. you can write a batch file to create and delete folder instantly.getDefault()).out. 3. Try to use print method instead of println. what do they do? 1.Exercises 1.

Java Lab Manual by Yasser Jaffal (2008) 12 . compile.0). more advanced and stable compared to Forte. ● Introducing error types in Java and understanding error messages ● Discriminating between run-time (semantic) errors and compile-time (syntax) errors. run and debug programs.2 NetBeans IDE Figure 3. Create a new project by going to File > New Project. Project creation is a simple process consists of two steps. Once you have JDK 1. So lets start having a look at NetBeans. because it is free compared to JBuilder. we will focus on its IDEs. Follow these steps: 1. or by clicking on New Project button on the toolbar. we leave the default settings.NET ● ● ● ● ● We can notice from table above that we have various brands of IDEs.Session 3 Working with NetBeans IDE Objectives: ● Showing how IDE software facilitates the process of programming. 3.1 IDE Software IDE stands for Integrated Development Environment. NetBeans is the best offered IDE for us as Java learners. NetBeans installation is a straight-forward process. ● Introduce the basics of NetBeans IDE. 3. all programs written using NetBeans must be included in projects to be able to be compiled and run.com.1 shows the main screen of NetBeans IDE (version 5.NET Sharp Develop C/C++ PHP/JSP/ASP ASP. To use NetBeans for writing and running your Java programs.5 installed. ● Introducing debugging and its importance. You can download NetBeans from http://java. since we are interested in Java programming language in this course. General category and Java Application type. that is. First step is defining project category and type. the following table shows well-known IDE programs: Programming Languages Java ● ● ● IDE NetBeans Forte for Java Borland JBuilder Microsoft Visual Studio Borland C++ Macromedia Dreamweaver Microsoft Visual Studio .sun. Second step is specifying project name and main class. IDE is a software that helps us to write. IDE programs vary and each one of them usually targeted to certain programming language. In our case.

Once you create a project. The output window appears at the bottom of the IDE and shows the outputs of compilation and running processes.1: NetBeans IDE main screen 2.java files) and hence it is the folder we are interested in. you may compile and run the program by selecting Run > Run main project. on the project explorer you will see a tree that has the project name you specified as root. pressing F6 key on the keyboard. after you are done. try to write some statements you've learned from session 1. Test packages. Project is split into four folders: Source packages. Libraries and Test libraries. or clicking Run button on the toolbar 5. In the main method. After creating a project. 4. you will see the created Main class. so we can group classes of related functionality together. Java Lab Manual by Yasser Jaffal (2008) 13 . you are ready to start coding. Source packages is the folder containing the source code files (. 3. so you need just to start programming. a default package that holds project name is created. In the code editor. with its main method already coded.Figure 3. Source code is usually split into packages.

as we put a break point on the second line. press Sift+F5 on the keyboard.2 shows a break point added in some lines. Figure 3. click on the left of the line you want to insert the break point in. 6. To stop debugging.). Write the HelloWorld program from session 1. or click on Stop button on the toolbar.3 Debugging Your Program The importance of debugging arises from the ability to trace the code statement by statement and monitor values of variables at every moment.3. the statement is not executed until we select to continue.out. 14 Java Lab Manual by Yasser Jaffal (2008) . what do you notice? 5. Figure 3.4 Error Types in Java ● In Java (and other programming languages) there are two major types of errors: Compile-Time errors (Syntax errors). make a small test by following the procedure below: 1. To add a break point. 3.2: Break points To show how debugging works. it hangs allowing you to review the values of variables at that moment. break point is a sign you may put on any line of your program to have the debugger stop at it. Notice that when debugger reaches a break point. Observe the output of the program. 2. it turns to green. NetBeans allows you to debug your program and trace any run time errors that may exist. 3. this can be done by pressing Ctrl +F5 or by clicking on Continue button on the toolbar. when the execution of the program reaches a break point. this means that this is the next statement will be executed. Debugging in NetBeans IDE means that you define one or more break points in your code. Add a break point in the second line (System.println("How r u 2day?"). Debug the program by pressing F5 key on the keyboard or by clicking on Debug button on the toolbar. 4.

Run-Time errors. In statement 2. Java is case sensitive. because Static is not a valid keyword. an example of exceptions is Java Lab Manual by Yasser Jaffal (2008) 15 . it starts with upper case letter. and as System is a class in Java.out. after the space it is expecting the opening bracket "{". In statement 4." which is absent in our case.println("Hellow") system. the error message is "unclosed string literal".println("Hello). we are looking for violation of Java language rules not English language rules. exception is a non expected error happens while executing a code. As we know. System. this is not the error we are looking for. 5. The message you will see in this case is "Cannot find symbol". In statement 3 . 3. let's start with statement 1.3: Compile-Time error message. In statement 5. 4. This message means the keyword or member name you are calling is not recognized as valid one.3. the compiler assumes that class name finishes when it finds space. the error is that the given class name is not valid.println("Hello"). as we've learned before. The message the compiler will generate in this case is "'. The most common reason for this error is a spelling mistake. error message also includes the line in which error exists as shown in figure 3. what is wrong with it? Clearly Hello don't have "w" at the end of it! However. each statement in Java should be terminated with semicolon ". it is clear that class keyword must start with lower case letter as all keywords in Java do so. but it will not be detected until first error is fixed because it appears first.out. class Hello World{ Class HelloWorld{ public Static void main(string[] args){ OK.' expected". Notice that in this statements we have another error which is "cannot find symbol" because string is written mistakenly in lower case. First category of run-time errors is exceptions. the compiler cannot detect them because there are no errors or rules violations. The error message in this case is "'{' expected". Run-Time errors appear when program run. Compile time errors are those the compiler detects while translating your program from Java language to machine language. because the opening double quotation (") does not have a matching closing one. the message generated is "<identifier> expected". you can notice that system is written in lower case. In statement 6. 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). 2. these errors fall into two categories: exceptions and semantic errors. as class name cannot have spaces according to naming conventions in Java (as we shall see in next session). the message generated is "class or interface expected". The following examples show some of these errors: ● 1.out. Figure 3. 6. System.

print('What's up'). Note that the Main class is still open and you can navigate between two class using tabs above source editor. We will have a closer look at run-time errors and how to deal with them in the coming sessions. and we give it 1. but they are unexpected results or outputs of your program. its output should be 6.out. System.out. if your program is supposed to calculate the sum of three numbers. public static void main(String[] args). 2. and type a program to print your name and student ID each in separate line using only one println statement. This will open up Project Properties dialog. and mention which one is detected first) 1.4. 2. select Run category. The second category are semantic errors. public static void main(String() args){ 6. What is the error message expected from each of the following statements? (Also show if there is more than one error. Now type a main method in your new class and put some code in it. 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.4: Error detection in NetBeans Exercises 1. Java Lab Manual by Yasser Jaffal (2008) 16 . System. for example.{ 4. Be ware not to delete package name mistakenly. nor exceptions occur at runtime. class My Class{ 5. and type your class name in place of Main in Main Class text field. To make your new class the default one (that is. From the tree on the left. 3. 8.ArithmeticException which occurs when you try to divide by zero. right-click package in the project explorer. and you can see the error message by positioning the mouse pointer over the line as shown in figure 3. it will run when you run the project). 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. run the project and you will see the result. open Add menu and select Java Class from the list. The statement containing an error is underlined by red line. otherwise we have a semantic error. System.out.out. To do this. Figure 3. so you can find them before compiling you program. NetBeans can detect syntax errors while you type your program.pint("How are you?").out. System. 7. Enter new class name and click OK to see your newly added class. Create a project using NetBeans called MyFirstProject. System.Print ln("Hi man!"). rightclick the project icon (Java cup) in the project explorer and select Properties from the menu. those are not actual errors detected by compiler. 2 and 3 as inputs.println(Hello World!).println("I wonder where is the error?\m").

Table 4.1. variable name is a valid Java Java Lab Manual by Yasser Jaffal (2008) 17 .1 Variables and Data Types Variables are reserved areas in computer memory. Data Types and Operations Objectives: ● Identifying variables and data types in Java. Table 4. ● Understanding literal values and expressions. holding unique name and expecting some data format to store called data type. ● Applying operations to variables. 4. ● Converting between data types.Session 4 Variables.1 shows primitive data types in Java. Primitive data types are declared using special keywords. ● Discriminating between primitive data types and classes (user-defined data types). Data type is one of primitive data types shown in table 4. use a statement with the following format: datatype variableName. Data types in Java fall into two categories: primitive data types and user-defined data types (classes). Primitive data types are Java built-in data types representing most common data types like numbers and characters.1: Primitive data types in Java To declare a variable.

a dollar sign '$' or an underscore '_'. the name is valid if it: ● Is not a reserved word.. and each following fragment with a capital letter like variableName and averageOfMarks. boolean done. ● Contains only letters. underscores '_' and numbers. we have some optional conventions but they are highly recommended to follow them in order to stay up with the global standards of Java. the first part is a primitive data type from table 4. var_2. Here are some examples of declaring data types: int anInt. In addition to previous conditions.. long x1. you cannot store 7.variable name. ● Starts with a letter ('A' to 'Z' or 'a' to 'z'). x3. We will be talking about conventions as they appear. . So whats next? We have to assign some values in the variables we have just declared. and the second type is a valid name.2 shows examples of values and their appropriate data types.1. 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. double d. A notable naming conventions in Java is the one we've used in the first statement. ● Has no spaces. You can notice from the last statement that we can define several variables of the same type by using commas '. for example. float average. a variable name should start with a small letter. ● Is not the name of a previously defined variable. var_n.34 in a variable of type int (unless you convert). Table 4. Table 4. dollar signs '$'.2: Examples of values and data types Java Lab Manual by Yasser Jaffal (2008) 18 . x2. even of different type (unique).' between names on the following format: datatype var_1. As you can see.. Value and variable must be of the same type.

we use assignment operation denoted by equality sign '=' in the following format variable = value.3 shows arithmetic operators. if you want to assign them to a float variable. Operation Assignment Addition Subtraction Multiplication Division Operator Usage = + * / var1 = var2 var1 + var2 var1 – var2 var1 * var2 var1 / var2 Modulus (division remainder) % var1 % var Table 4. c. e = 3. numerical values with decimal point are treated as double by default.println(b). c % a.77e3 is equal to 26.out. Assignment can be done in the same statement in which we declare the variable float average = 81. x = 10.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.2 Operations on Variables As we have seen. Addition. Table 4. Here are some examples of expression: int a = c = d = a.println(average). those arithmetic operations are called binary operations because they are used with exactly two operands. so we can perform binary operations on them (addition. The value 26. b.5f.5" System. //variables definition b = 5. boolean b = false. multiplication and division operations generate expressions. you have to explicitly define it as float using F after the value. an expression is a series of calculations that produces a single value.//prints "false" 4. subtraction. d. To assign a value to a declared variable. to assign a value 10 to some integer x int x. most primitive data types are numerical. for example.As you can see. subtraction. multiplication and division).//prints "81. //multiple assignment 6. System.out.//d = 1 19 Java Lab Manual by Yasser Jaffal (2008) .77 * 103.

and the value of ++a is the incremented value. c = " + c). Comments on the previous code: ● It is valid to define multiple variables in the same statements and assign values to them (statement 1). ++a a = a – 1 a--. b = 1. If you compile and run the above program.println("a = " + a + ". b = 2. c = " + c). c. b * c is calculated first). System.println("The value of e is " + e). c = 10 Java Lab Manual by Yasser Jaffal (2008) 20 . b = " + b + ". --a Table 4.4 illustrates.out. expression a = a + b. both of them increment the value of a by one. ● Mod operator calculates the remainder when dividing first operator on the second. c = 1 a = 5.out.1. a = ++b + c. c = " + c). followed by division then addition and subtraction (in statement 5. ● You can assign single value to multiple variables in the same statement (statement 2). this way is valid for other operations as table 4. The following example shows the difference. a = b = c = 1. Expression a = a + b a = a .//expression evaluation (e = 37) System.4: shortcuts of expressions The difference between a++ and ++a is the value of the expression itself. b = a++ . c = a + a++ + --b + b. int a. ● We can concatenate a string with an integer by using "+" operator (last statement).println("a = " + a + ". b = " + b + ".println("a = " + a + ". ● We can use brackets '(' and ')' to specify which expressions must be evaluated first (precedence overriding). for example. b = " + b + ". b. c = 1 a = 4.e = e + (a + b * c – d). multiplication has the highest precedence. at the end. System.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++. you should see the following output: a = 3. b = 2. but the value of a++ when evaluated is the original value of a. We have some shortcuts with binary operations. System.out. ● By default.out. could be written in the form a += b.

similarly. System. b2. the value of b is incremented by 1. then the rest of expression is evaluated using the new value of b. Operation Logical AND Logical AND Logical OR Logical OR Logical NOT Operator && & || | Usage op1 && op2 op1 & op2 op1 || op2 op1 | op2 ! !op1 Table 4. This happened because we used pre-increment.To clearly understand how it works. true || false expression does not evaluate the second operand. there are also comparison operations which we apply to numerical variables to get boolean results. In addition to these operations. b3=" + b3).println("b1=" + b1 + ". b3. when we use && or ||. For example.out.6 shows comparison operations. b1 = true || false. so post increment does not affect the expression in which it is. during and after the execution of the statement a = ++b + c. If we use post-increment. table 4. Table 4. Before the execution. but the following expressions. Boolean variables have different set of unary and binary operations according to the special data type they store. the value of b will also be incremented.5: logical operations Discussing the difference between && and &.. b2=" + b2 + ". let's monitor the value of b before. because the logical OR between true and any other boolean expression is always true. once the statement ++b executed. b3 = b2 && (13 == 6). it gives the old value of b before increment. boolean b1. false && true does not evaluate the second operand because logical AND between false and any other boolean expression is always false. Java Lab Manual by Yasser Jaffal (2008) 21 .6: Comparison operations The following example evaluates some boolean expressions and prints their results. and | and ||. b2 = b1 && (5 > 3). it is clear that b = 1. but when b++ itself is evaluated.5 shows primary boolean 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. op2 is not evaluated when the value of the whole expression could be determined by the value of op1 and the operation. which is logical.

notice that we but a large value into a smaller data type. the following example shows how to use it. the following discussion shows the difference between them. f = (float)d. because double data type is normally wider than int. One of them is a well known method that converts a String to integer which is Integer. Types of conversion mentioned above are called explicit conversion.parseFloat() and Long.parseLong(). because we request that Java Lab Manual by Yasser Jaffal (2008) 22 .4f.3 Conversion between Data Types We can convert the value of a variable to the format of another variable of different type and make an assignment between them. we have used concatenation to convert the whole output to string. in this case.If you compile and run the above code you should get the following output: b1=true. 4. there is absolutely no risk storing int in double. int i.out. The above code does the following: ● Converts the value of i to double and stores it in d.parseDouble(). This conversion is done automatically by the compiler. d = 5.parseInt(s). we use casting to tell to compiler that we know what we are doing! Another way to convert between variables is using some defined methods that converts between variables. Because that. Float. we can also use Double. compiler (by default) refuses to store float value in int.println(x). b2=true. int x = Integer. a possible loss of data occurs in which we have to be aware of. float f. System. f = 4. conversion is different from another operation called casting. or double in float. Because of that. b3=false Once again. i = 1.println("i = " + i + " f = " + f + " d = " + d). toString() method will be covered in more details later.5. String s = "115". System. double d.out. ● In the following two statements.parseInt() method. x++. A common method among all objects in Java is toString() method which converts the object to a string. the next section focuses more on conversion. d = i. //prints 116 Similarly. i = (int)f.

double result = (d/f) + x. float f = 1. clearly. one of them is the previously discussed parseInteger() method which returns an integer generated from some string. for example. Java Lab Manual by Yasser Jaffal (2008) 23 . The following code shows an example. the result is of type double.5f. //literal value //Constant expression //Method return type //Expression From the above example we can notice different expression types: literal value: by defining the value we wish to store in the variable literally. The following example shows how to express integer value of 8 in different ways. another type of conversion is called implicit conversion (promotion). because it is done automatically without requiring the programmer to request that conversion. String s = "x equals " + x. 3. you will see the output “The result is 18. the expression 1 + 3 – 5 evaluate at runtime and generate a final value of -1.parseInt("8"). 'a' directly to a character or "Hello" directly to a string. for example. In general. int x = 10. For example. Methods: Some methods returns a value of certain type. Integer. In the above code. and all of them are equivalent. assigning 8 directly to an integer. the value of x which is 10 is converted from integer to string and concatenated with the previous string "x equals ". (x + y) / 2. double d = 12.conversion explicitly. Promotion also occurs when an expression of values from different types is evaluated.33333333”.4 Literal Values and Expressions It is important to realize that a value of any type can be expressed in different ways. promotion converts all operands to the largest data type among them.out. If you run the above code. The value of f is converted to double and d/f is evaluated. 2.5. 5 + 3. The expression was evaluated as the following: 1. The whole expression is evaluated to type double And stored in result. int x = 10. The value of x is converted to double and added to the previous expression. System. concatenating an integer or a character with a String converts them automatically to a string. int int int int x y z w = = = = 8. 4. Expression: expressions are evaluated in runtime to generate a single value.println("The result is " + result).

final int MAX_VALUE. final means that the value remains constant at the time of execution and it is assigned during compile time. ● d is assigned a value of 4 converted from a string using parseInt() method.Exercises 1. The final keyword is used before specifying data type in variable declaration. MAX_VALUE = 100. c = 1. ● c is assigned a value of 2 generated from an expression of a and b. c and d are integers. Write a program that calculates a + b + c + d and prints the result on the screen where: ● a. x = 2. 3. b. You can only assign the value in the same statement in which you define the variable. so the following statements are invalid. Lab Extras Some variables are declared using final keyword. y = -2. It is important to realize that you can assign a value to a final variable only once. ● a is assigned a literal value of 3. ● b is assigned a value of 6 using an arithmetic expression of 3 literal values. The value of a final variable cannot be modified once it is assigned. Assuming that a = 3. ● The result is printed directly without defining a new variable to store the result. Write a program that evaluates all the expressions in exercise 1 and prints the result on the screen. the naming convention of final variables is to use upper letters and underscores "_". b = 5. final int MAX_VALUE = 100. 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. //Error As you can see. and z = 6 and following precedence rules. Java Lab Manual by Yasser Jaffal (2008) 24 .

Applets are Java programs that are written with *. In general.2 Writing and Compiling Applets Applets are written in ordinary Java source files that has the name of the class inside it. Applets are something different. 25).1 Idea of Applets So far. } //We use this code to draw on the applet public void paint(Graphics g){ //Drawing text on the specified point g.Graphics.25). not command-line applications. Applets have no main(String[] args) method. import java. //These two classes are necessary.Session 5 Working with Java Applets Objectives: ● ● Writing and compiling Applets. instead. Embedding Applets into web pages. we can claim that our Java applications are console applications. } } Java Lab Manual by Yasser Jaffal (2008) 25 . so we //need to import them from the libraries import java. 50.applet. 5. because the run mainly on console (command prompt in Windows. To run an Applet.awt. shell in Unix). you have to embed it in a HTML page using special tag. from the context in which they run. ● ● 5. Applets are graphical. but they are different from another perspective: ● ● You cannot run Applets using java command.Applet.drawString("Hello world!". there is a method called init(). //This is the way to define an Applet class public class HelloApplet extends Applet{ //This code will be executed when Applet runs public void init(){ //Setting Applet window size resize(150.java file extension and compiled using javac command. The following code shows a simple example (read comments carefully).

create an HTML page (in the same folder) and add the following HTML code in it. 5. you'll get the result shown in figure 5. not the name of the file. ● To let Java deal with this class as Applet. <html> <body> <applet code="HelloApplet" width=400 height=200></applet> </body> </html> The highlighted part is the most important tag in out page. Figure 5. so don't add the extension . The following section discusses this task. <applet> tag tells the browser where to add the Applet. you get a file called HelloApplet.There are some important notes about writing Applet code: ● We use import keyword to get classes from libraries into our source files.class. ○ paint(Graphics g) method: This method is dedicated for painting on the Applet. we need to put it inside HTML page. code property specifies the name of the class from which the Applet should be loaded. we compile it as usually with javac command. drawLine(). ● Class should be declared using public keyword. the Applet starts execution from this method. the variable g (called object) has a lot of drawing methods like drawString(). To run the applet.class to the name.2. Saying it again. To run this file. When you open the web page. ● Applets have two important methods: ○ init() method: This method is like main(String[] args) method in Java applications. We will discuss them in details later.1 below. the name of the class.3 Embedding Applets into HTML After compiling the code in section 5. After writing the class.1: Hello World Applet Java Lab Manual by Yasser Jaffal (2008) 26 . add extends Applet to class declaration. this enables access to it from web browsers. drawOval() and so on. and everything is alright.

class and the web page into it. Create a new folder in your public_html folder on Webdisk named lab2 and upload HelloApplet. 25). Java Lab Manual by Yasser Jaffal (2008) 27 . start from the upper-left corner and take 50 pixels to right then 25 pixels downward. call getWidth() method.2 below. to get the height of the whole Applet. The value of x increases from left to right. Create a web page to run HelloApplet. To get the width of the whole Applet. x+ (50. 25) of the frame. 4. and the value of y increases from up to down. Have a look at figure 5.Notice that our Applet does nothing except drawing the text “Hello World” at the point (50. call getHeight() method. 3. the upper-left corner has the coordinates (0. Run your Applet from the web. 25) (0. 2. getHeight()) Figure 5. Write the HelloApplet class and compile it.2: Coordinations of Applet As you can see. Exercises 1. we have to understand the coordinations of the Applet. 0). 0) y+ (getWidth(). So to locate the point (50. To see exactly where this point is located.

if(x > 0){ System.Session 6 Conditional Statements and User Input Objectives ● Introducing the logic of if and if-else statements.println("x is positive").1 if and if-else Statements Sometimes we need to make a decision between two choices or two actions based on some information or conditions. we can use nested if statement inside the block of else as follows: int x = 5.println("x is negative").println("x is positive"). if the result of the boolean condition is true then the condition is met and the appropriate action(s) is made. we can check whether some value is positive or negative: int x = 5.out. Choices are made by one or more conditions being satisfied or not. The statements in by which we make this decision are called conditional statements. if(x > 0){ System. } else{ if(x == 0){ System. ● Making decisions based on user input. } Java Lab Manual by Yasser Jaffal (2008) 28 . We use if statement to determine whither the condition is me or not.out. we can use >= operator instead of >. The problem of the above statement is that 0 is considered negative. ● Using switch-case statement to make decisions based on some value. but if we wish to detect 0 itself.out. we express those conditions by boolean expressions. that is. To solve this problem. The format of if statement is as follows: if(condition){ //statement(s) to be executed if the condition is true } For example.out. } else{ System. ● Reading user input. } Notice that we use else block to enclose statements that we want to perform if the condition is NOT met.println("x is zero"). 6.

*. we can use else-if statement.io. public static void main(String[] args) throws IOException{ Butting it all together. we use import statement as follows. The format of if-else statement is the following: int x = 5. } } Using technique like on in the above example may make the code more complex and harder to understand. by which we can check unlimited number of condition.out. } else if(x < 0){ System. By using character * here we identify that we import all classes in this library.else{ System. in order to import it. if(x > 0){ System. } else if(x == 0){ System. } Using else before each if statement means that if one of the conditions is met no other condition will be checked.println("x is negative").readLine(). we will do this by changing the definition of main() method to throw that exception.println("x is zero").out. String input = in. import java. be sure to import the library which contain this class. 6. this library is called java.out. instead.in)). for instance. a simple program that reads user name and prints it on screen. Before using BufferedReader. To use BufferedReader class. you need to deal with the exception it throws through readLine() method which is IOException. import statements are used before class definition.println("x is negative").println("x is positive").out. Java Lab Manual by Yasser Jaffal (2008) 29 .io. and making decision for each one separately.2 Reading User Input You can read input from the user using BufferedReader class in this way: BufferedReader in = new BufferedReader( new InputStreamReader(System.

userName = in.in)).*.println("zero"). import java.out. in = new BufferedReader( new InputStreamReader(System. in = new BufferedReader( new InputStreamReader(System. negative or zero. class Numbers{ public static void main(String[] args) throws IOException{ BufferedReader in. System. if(x == 0){ System.io.out. } //x is positive else if(x > 0){ Java Lab Manual by Yasser Jaffal (2008) 30 . as well as determining whether the number is odd or even. class ReadFromUser{ public static void main(String[] args) throws IOException{ String userName. System. 6.out. System. BufferedReader in.parseInt(userInput). x = Integer.import java. String userInput. then concatenates it with "Welcome" and prints it on the screen. we will write a program that uses if-else to determine that the number provided by user is positive. int x. reads the input using readLine() method which returns a String value that represents user input from keyboard. } } The above code asks the user to enter his name.println("Enter your name: ").in)). userInput = in.*.3 Decision Making Based on User Input It is clear now that you can write a program that responds to user actions depending on the input provided by user.io.print("Enter a number: ").out.readLine().readLine(). For instance.println("Welcome " + userName).

and it cannot accept strings.println("positive and odd"). we converted the String we read from user to integer because it is easier to compare. 6. it makes choice among several options based on a numerical value. . } } }//end of main() }//end of class As you can see.4 switch-case Statement This statement is a special type of decision making techniques.out. case value_n: Java Lab Manual by Yasser Jaffal (2008) 31 .out. is that switch-case statement accepts only integers and numerical values or characters. another reason may lead us to this conversion. . The format of switch-case statement is the following: switch(variable){ case value_1: //Statement(s) to be executed if //variable = value_1 break. } //x is odd else{ System. } //x is odd else{ System.println("negative and odd"). case value_2: //Statement(s) to be executed if //variable = value_2 break.println("positive and even").out. The following section covers switch-case statement.out.//x is even if(x % 2 == 0){ System. .println("negative and even"). } } //x is negative else{ //x is even if(x % 2 == 0){ System.

println("Welcome " + name").out. The following example shows how to use switch-case statement.println("You are " + age). we put some variable in switch then follow it by several case blocks. } As you can see. choice = Integer. Execution goes through cases one by one comparing each one with the value of the variable specified in switch statement. System. System. the following program enters all cases.exit(0). Print your name").out. import java. Print your age").//Statement(s) to be executed if //variable = value_n break.println("2. Exit"). in = new BufferedReader( new InputStreamReader(System. break.readLine()). break. System.out.io. }//End switch }//End main }//End class The following code shows how cases are executed.readLine().*. int choice.out.out. String age = in.println("1. System.readLine().println("3. case 3: System.print("Enter your age: "). String name = in.in)). class SwitchCaseDemo{ public static void main(String[] args) throws IOException{ BufferedReader in.print("Enter your name: "). Java Lab Manual by Yasser Jaffal (2008) 32 . switch(choice){ case 1: System. unless we use break keyword to avoid the execution from expanding to unwanted statements.out. System. case 2: System.parseInt(in.out. then executes it and all cases that follows.

switch(choice){ case 1: System.print("Enter your age: "). case 2: System. switch(x){ case 1: System. break. 2 and 3. String age = in.readLine(). default block is executed when the value of the variable did not match any of specified cases value. String name = in.println("Welcome " + name"). but all three cases are executed. Because we usually use break after each case.exit(0). we use default keyword instead of case keyword to specify the default case.out. } You can notice that the value of x meets the first case only.out.println("Invalid choice").println("You are " + age).int x = 1. add a default case to our previous SwitchCaseDemo class (shown in boldface) and try to enter any value other than 1.out. System.out. default: //User did not enter 1.println("x = 3"). A special case that is executed without checking the value of the variable is called default case. use break statement after the end of each case. 2 or 3 System. case 2: System.println("x = 2").out. this states that switch-case statement does not automatically exit after one a case value is met.out.readLine(). So the output of the previous code is the following: x = 1 x = 2 x = 3 To prevent such behavior. System.out.print("Enter your name: "). }//End switch Java Lab Manual by Yasser Jaffal (2008) 33 . case 3: System. which exits the whole switch block. To see how this works. break. case 3: System.println("x = 1").out.

Exercises 1. Write a program that asks the user to enter two numerical values (integers) and then select an operation (addition. Enter first number: 4 Enter second number: 2 1. which depends on showing a dialog box for the user and let him enter his input in a text box inside that dialog. multiplication and division) then prints the result based on operation selected. class EasyRead{ Java Lab Manual by Yasser Jaffal (2008) 34 . Addition (+).*. subtraction. this library contains classes that deal with GUI. Enter operation number: 3 The result is 8 Lab Extras There is an easier way to read from user.swing. Enter the first number: 3 Enter the second number: 4 2. 2. don't read from user): ○ 0 to 9 ○ 10 to 19 ○ 20 to 29 ○ None of the categories For example. 3. The following example shows how to use this technique to read from user.swing. Division (/). Multiplication (*). What we interested in among the classes of this library is a class called JOptionPane and a method inside it called showInputDialog(). Write a program that specifies whether a given number (x) falls in one of the following categories (give x a value from the code. 2. if x = 5. Subtraction (-). program should print "0 to 10". 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). The sum is 7 3. To use this input dialog we import the library called javax. 4. The code below shows examples of the output (text shown in boldface is supposed to be user input). import javax. Hint: use if statements with boolean expressions combined using &&. and if x = 44 it should print "None".

} } You can notice here that we do not declare any objects and no exceptions to throw.1.showInputDialog("your name: ").out. If user clicks OK the input is read and returned as String.1: Input Dialog Java Lab Manual by Yasser Jaffal (2008) 35 . userInput = JoptionPane. if he click Cancel dialog box closes without returning any input entered. Image 6. The output of the above code is a dialog box like the image 7. System. An easy and straight forward method.public static void main(String[] args){ String userInput.println("Hello " + userInput + " !").

lets focus on the first four steps and leave step 5 to the next section. import java. this means that we have reserved the variables names for them. 7. Well. It is important to realize that you need to declare these variables outside init(). to summarize. we have just declared these controls. we use code like the following. applets can do more. 2. Declaring user controls variables (or objects).. The initialization step is the one which makes them really exist. Notice that these types start with upper-case letter. Adding the controls to the Applet. It is advisable that you initialize these controls at the beginning of init() method.. Importing the library is achieved by using import statement followed by library name and class name. Adding user controls is a simple yet relatively long process. For now. Handling events of user controls. For example. they should be declared directly inside the class body. . text fields. 5. but they does not actually exist. Importing the library in which they are located (java. 4. Up to now.*.awt). in other words. etc) to the Applet. Handling controls events. we use *. Initializing the controls. so it is reasonable to start learning how to add user controls (buttons. Reading and writing values to user controls. The second step is to declare the controls variables. Including external packages. 3. TextField t.Session 7 Decision-Tree Applet Objectives: ● ● ● ● Adding user controls to Applets.1 Adding User Controls to Applets So far. The main objective of Applets is to provide a dynamic user interface on the web. if we want to add a button and a text field to our Applet.. The following code shows the necessary import statement. it involves the following steps: 1. Lets now discuss these steps in details.awt. we have been creating Applets that do nothing but drawing text on the screen. Java Lab Manual by Yasser Jaffal (2008) 36 . Button b. To import all classes in a library. unlike primitive data types. These controls have data types just like primitive data types discussed in session 3 but their initialization is slightly different.

the step left is to add these controls to the Applet.*. TextField tf. you'll get something like this (figure 7.1: Simple Applet Java Lab Manual by Yasser Jaffal (2008) 37 . we add them to the Applet using add() method.awt. //Step 1: import import java. } As the above code shows. b2. add(tf).public void init(){ b = new Button("Click Me!"). which is a special type of methods written specifically to initialize objects. Figure 7. } } If you compile and run the above Applet. Code below shows a full example.Applet. b2 = new Button("Button 2"). The statement that follows new keyword is a call to the constructor. the text we pass to TextField constructor is the default text that will appear in it.1). Don't bother yourself with it now. To make them visible. public void init(){ //Step 3: initialize controls b1 = new Button("Button 1").applet. Similarly. we use the new keyword to initialize the controls. they are not graphically added hence not yet visible to the user. public class SimpleApplet extends Applet{ //Step 2: declare controls Button b1. t = new TextField("Type in me!"). add(b2). import java. The string we pass to Button constructor is the text we want to appear on it. We have now declared and initialized controls. tf = new TextField("Type something"). //Step 4: add controls (adding order affects appearance) add(b1). Although these controls are declared inside Applet's class.

This addition requires you to write a new method called actionPerformed(). which is java.. public void init(){ //Step 3: initialize controls b1 = new Button("Button 1"). add(tf). First step of adding this functionality is to import the necessary library.*.Applet. Next. TextField tf.*. in addition to being Applet. Your Applet is ready now for event handling. b.awt.event. that is. //Step 4: add controls (adding order affects appearance) add(b1). this is achieve by calling addActionListener() from button's object. but how? When user clicks on a button. Java Lab Manual by Yasser Jaffal (2008) 38 .addActionListener(this). Modifications are shown in boldface. public void actionPerformed(ActionEvent e){ } One thing left. letting the current Applet be the event handler for buttons we have added. java.awt.event. we need to alter the definition of our class. there is no point in adding buttons that do nothing and text fields we are not able to read/write to. //Step import import import 1: import java.awt. the method actionPerformed() is executed.7.event. import java. b2 = new Button("Button 2"). public class SimpleApplet extends Applet implements ActionListener{ //Step 2: declare controls Button b1.*. b2. java. The following code shows how can you decide which button was clicked (modified version of SimpleApplet). //Assume that Button b is already defined. our class should now serve as ActionListener. public class MyApp extends Applet implements ActionListener Notice the addition (implements ActionListener) at the end of the class definition.awt.2 Handling Events of User Controls The last thing remained in this session is to add some functionality to these controls. being able to handle actions raised by controls (mainly buttons)..applet. at the end. tf = new TextField("Type something"). So the definition of the class will be the following.

7.add(b2). } } } Code inside actionPerformed() method needs some explanation. String valueOfTextField = tf. //Step 5: add action listener b1. Java Lab Manual by Yasser Jaffal (2008) 39 .jar file. call setText() method and pass a String representing text you want to appear in it.alquds. this tool can run your Applet without the need of creating HTML page. 2.getSource() to know which button was clicked. b2. add(l). You can also use a control name Label to add text labels to the Applet. you need to add an external library that is not present in JDK. follow the following steps: 1. select it and click “Open”.*. Expand your project tree from project explorer (on the left). then store it in cause.addActionListener(this). Then we compare cause which all buttons we have to find out which button was clicked in order to perform the appropriate action. } //This method will run when buttons are clicked. to do this.getSource().jar.edu/~f3576/102/resources/ModelAwb. To change the value displayed in the text field.getString(). public void actionPerformed(ActionEvent e){ Object cause = e. 4. if(cause == b1){ tf. } else if(cause == b2){ tf. To do the exercises at the end of this session.addActionListener(this). Label l = new Label("Some text").3 Applets with NetBeans NetBeans facilitates developing Java Applets by using applet viewer tool.jar and can be downloaded from the following link http://mail.setText("Button 1 Was Clicked"). we call e. 3. Right-click libraries node and select “Add JAR/Folder” Browse for ModelAwb. you have to add it to your NetBeans project. You can now use the statement import awb. To read the text typed in the text field call its getText() method. this library is called ModelAwb.setText("Button 2 Was Clicked"). After downloading the file.

Write a calculator Applet that has two int fields (Use awb. named register and accumulator. 20. the following code creates a text field with 20 columns width. //Text field with multiple lines Java Lab Manual by Yasser Jaffal (2008) 40 . add and power. TextField t = new TextField(20).2. For example.IntField class). setAccum.2: Exercise 1 Lab Extras You can specify the width of text field by providing the number of columns in the constructor. 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 Your Applet should look like figure 7. Figure 7. TextArea a = new TextArea(20.Exercises 1. and four buttons named setReg.

Session 8 Loops and Variable scope
Objectives ● Understanding the concept of loops. ● Using while and do-while loops. ● Using for loop. ● Variable scope.

8.1 What Are Loops?
We use loops to make one or more statements repeat for specified number of times. Clearly this have an importance when we wish to take more than one input from user or do some calculations. For example, to calculate the sum of numbers from 1 to 10, we define a variable named sum, initialize it with 0, then use another variable i to have values from 1 to 10. The following sections discuss loops in more details.

8.2 while and do-while Loops
This is the simplest type of loops, it consists of a condition (boolean expression) and a body which contain one or more statements; as long as condition is true, statement(s) in the body keep to execute, after each execution, the condition is checked again, this implies that if the condition was initially false, statements in loop body will never execute. The format of while loop is the following. while(condition){ //Statement(s) to execute as long as condition is true. //Also known as loop body. } Here is an exmple of while loop: class Loops{ public static void main(String[] args){ //Prints numbers from 1 to 10 int x = 1; while(x <= 10){ System.out.println(x); x++; } } } The output of the above program is the following: 1 2 Java Lab Manual by Yasser Jaffal (2008) 41

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.

8.3 for Loop
The base of for loop is similar to while and do-while loops; but there is slight different in format that makes for loop more powerful, specially with numerical values. Let's first have a look at for loop format, after that we will discuss its contents. for(initialization; test-condition; post-statements){ //Loop body } We can notice that for loop consists of three major parts: Initialization: a statement to be executed before the loop begins, this statement is usually used to define a variable or set of variables that control the flow of the loop. Test-condition: This is the boolean expression that is used to determine whether or not the loop should execute the next iteration, similar to conditions previously discussed in while and do-while loops. Post-statements: a set of statements (separated by commas ',') to be executed after each iteration. These statements are usually used to change (increment or decrement) the value of controlling variable(s) declared in initialization, sometimes we call it post-increment.

● ●

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

we can build powerful applications that do complex jobs. 2 and 3 are prime numbers if(x == 1 || x == 2 || x == 3){ System. //1.out. } //All even numbers > 2 are not prime else if(x % 2 == 0){ System. }else{ //We have to check using division remainder //we initially suppose that x is prime boolean prime = true.println(i + " * " + j + " = " + k). For instance. a loop inside the body of another loop. userInput=JOptionPane.out. because the whole inner loop is one statement in the body of outer loop. we can use as many levels of nesting as we need. class Prime{ public static void main(String[] args){ int x. } } } } In the above example. import javax.println(x + " is not prime").showInputDialog("Enter a number"). Combining loops and conditional statements.out. //No number has factor greater than it's half for(int i = 3.println(x + " is prime").out. String userInput. we used nested loops.int k = i * j. break.out. we will create a program that determines whether a given number is a prime or not. Be ware that when we use nested loops.println(x + " is not prime"). } Java Lab Manual by Yasser Jaffal (2008) 44 . the inner loop executes until the end in one iteration of the outer loop. that is.println(x + " is prime").swing. System.*. i <= x / 2. i++){ if(x % i == 0){ //We have found a factor //so x is not prime prime = false.parseInt(userInput). x = Integer. } else{ System. } } if(prime){ System.

boolean firstNumber = true. class Numbers{ public static void main(String[] args) throws IOException{ int min.parseInt(in.println("Minimum System.io. try to understand the following program that keeps reading numbers (integers) from user until input is 0.println("Average System. any access of variable out of its scope will be reported as compilation error. " + sum / count). we mean the region or block the variable is visible within. sum.*.out. if(x == 0){ break. BufferedReader in = new BufferedReader( new InputStreamReader(System.in)).readLine()). count = 0. } if(firstNumber){ min = max = x. " + max).} } } To get more familiar. if(x > max){ if(x < min){ count++.println("Maximum } } + = = = sum). maximum and minimum. import java.out. Java Lab Manual by Yasser Jaffal (2008) 45 .out. max = x. x. then prints average. } sum += x. x = Integer.print("Enter a number: "). } System. max.4 Variable Scope By variable scope.out.println("Sum = " System. while(true){ System. firstNumber = false. min = x. sum = 0. } } 8.out. " + min). Consider the following code.

Use appropriate loop to accomplish this. } In the previous code. //Error Variable scope extends from outer block to inner blocks regardless of the number of levels. if you try to call y from outside if block. System. you will get error message "Cannot resolve symbol".out.println("Absolute value of " + x + " is " + y). but not vise-versa. k int k = i * j. } //Visible: i } //Visible: None Exercises 1. 3. while y is only visible inside if block. j <= 12.out. i++){ //Visible: i for(int j = 1.int x = -3. after that asks him to enter Java Lab Manual by Yasser Jaffal (2008) 46 . i <= 12. j. //Visible: None for(int i = 1. Write a program that asks the user to enter certain number.println(i + " * " + j + " = " + k). program exits. x has scope inside and outside if block. 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). Yes 2. 2. No Enter your option: If user selects yes (by entering 1). j++){ //Visible: i. } System. System. 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.println("Absolute value of " + x + " is " + y). program will ask him again to enter new two numbers and select operation.out. if(x < 0){ int y = x * -1. if(x < 0){ int y = x * -1. if user selects no (by entering 2). int x = -3.

i <= 30. } As you can see. Java Lab Manual by Yasser Jaffal (2008) 47 . See the below example (text shown in boldface is supposed to be user input).print(i * j).out.out. i++){ if(30 % i != 0){ continue.another 20 numbers. consider the following program that prints out factors of 30. when 30 is not divisible by i.out. we use continue to jump to the next iteration without executing the next line that prints the output.out. j++){ System. j < i. What is the output of the following program? for(int i = 0. i++){ for(int j = 0. System. 4. } Lab Extras We use continue keyword to skip some statements inside loop body and start new iteration. } System. it prints out the number of occurrences of the first number.print(" "). } System. after entering them all. for(int i = 1.println(i). 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. i < 5.println("").

it is also clear that indices of an array are zero-based. and this is clearly very hard and not practical. in such case you need to use arrays.1 shows. the array shown in Figure 9. ● Multidimensional arrays. the size of an array is fixed. you have to specify data type and name. Arrays are indexed data types. Imagine the situation that you need to store 20 names of students as strings and 20 integers as marks. Here are some examples of array declaration: int[] a = new int[6].1 What Are Arrays? Arrays are special data types that let us store specified number of variables from the same type using one variable name. //Array of integers of length 6 String[] b = new String[10]. that means they are storing different elements discriminating between them using unique index for each one. they start from 0 to length – 1. Figure 9. that is.2 Using Arrays in Java Declaring and using an array in Java is similar to declaration of any variable. for example. then you need to define 40 variables. Figure 9. you have also to specify the length of the array before using it. 9.1: Array Structure As Figure 9. in addition to this. //Array of strings of length 10 Java Lab Manual by Yasser Jaffal (2008) 48 . and the last index is 9.Session 9 Arrays and Strings Objectives ● Understand the concept of arrays.1 has a length of 10 (stores up to 10 elements). ● Strings as arrays. arrayName = new DataType[length]. Array definition format is as follows: DataType[] arrayName. use new keyword and specify the length. 9.1 shows the structure of an array. we will refer to array maximum size as array length. ● Defining and using arrays in different types. To initialize the array.

To access array members. //Store 5 in the first index x[1] = 10. //Valid indices are 0.out.println("We are leaving in " + days[2]). It is common to deal with arrays using for loop.showInputDialog("Enter number of students"). 100}. we can use length property to determine the length of the array.out. 1 and 2 x[3] = 7. String[] names.println(x[2] + x[1]). separated using commas '. for(int i = 0. //Store 15 in the third index System.out.length.swing.*. x[0] = 5. import javax. i >= 0. //Length = 5 System. The following code stores multiples of 3 in an array then prints them from greater to smaller. //We are leaving in Monday System. int[] x = {10. "Wed". int[] x = new int[3]. //IndexOutOfRangeException Another technique to declare an array is to directly provide its members between brackets { and }.length – 1. i—){ System. String input = JOptionPane. "Sun". "Mon". //Prints 25 String[] days = {"Sat". "Tue". } for(int i = a. //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.println(x[3]). 25. int[] a = new int[20].print(a[i] + " "). 20.out. i++){ a[i] = i * 3. } The following example stores names and numbers of n students and performs search.'. "Fri"}. class Students{ public static void main(String[] args){ int[] numbers. "Thu". 15. Java Lab Manual by Yasser Jaffal (2008) 49 . use array name with desired index specified between square brackets [ ]. i < a. //Store 10 in the second index x[2] = 15. int[] x = new int[3].

equalsIgnoreCase("N")).showInputDialog("Enter Student name"). for(int i = 0. break. names = new String[size].showMessageDialog(null. Java Lab Manual by Yasser Jaffal (2008) 50 . } } Comments on the previous program: ● Array index could be used to relate data from different arrays together. i < numbers.parseInt(input). numbers[i] = Integer. do{ input = JOptionPane. index will bind two arrays together.parseInt(input).showInputDialog("Search again? Y/N"). }while(!input. input = JOptionPane. boolean found = false.showInputDialog("Enter student number"). } //Ask if the user wants to perform another search. that is.parseInt(input). } } if(!found){ JoptionPane. found = true.int size = Integer. student in index 5 has his name in names[5] and his number stored in numbers[5] */ //Search for student int x. for(int i = 0. x = Integer. i++){ names[i] = JOptionPane.showInputDialog("Enter Student number"). numbers = new int[size]. "Not found"). i < numbers.showMessageDialog(null.length. i++){ if(numbers[i] == x){ JOptionPane. input = JoptionPane. } /* Now we have all numbers and names.length. "Name: " + names[i]).

Lets first consider the declaration of multidimensional arrays.print(x[i][j] + " ").out. //a[2] {0.println(""). 2}. we were storing elements in linear manner. j++){ Java Lab Manual by Yasser Jaffal (2008) 51 . int[][] x = new int[5][4]. i < 5. } You can see from the previous example that we deal with each element in the array as array itself. DataType[][] arrayName. arrayName = new DataType[rows][columns] The following example shows a definition of a 5 by 4 array of integers. j < x[i]. j < 4. we call x[i].length.length.3 Multidimensional Arrays (Arrays of Arrays) Up to this point.out. this means that x[i] is an array of integers that may has its own length. for example. } } //Print array for(int i = 0. i++){ //j indicates column (column by column) for(int j = 0. These arrays are also called multidimensional arrays. //a[1] {0. i++){ for(int j = 0.length. 1. each element in that array is an array itself. 9.showMessageDialog() method (Remember to provide null as first parameter (parent window) ). The following example shows that. we provide one index to locate the element in one-dimensional structure. 3} //a[3] }. j++){ x[i][j] = i * j. i < x. i++){ for(int j = 0. } System. j < a[i]. this means we create an array. for(int i = 0. because it is not necessary that all rows have the same number of columns. //a[0] {0. j++){ System. 1}. int[][] a = { {0}.length. 1. //i indicates row (row by row) for(int i = 0. that is. i < a. Java also provides arrays of arrays.● ● Output could be provided using JOptionPane. There is also another method called equals that makes casesensitive comparison between strings. String class has method called equalsIgnoreCase that compares two strings together regardless of their case. 2.length.

out. i < rows. matrix2[i][j] = Integer. String m1 = "Enter first matrix elements\n". int rows. j < columns. int[][] matrix2 = new int[rows][columns]. } Java Lab Manual by Yasser Jaffal (2008) 52 . } The output of the above code is the following: 0 0 1 0 1 2 0 1 2 3 As you can see.parseInt(input). for example.showInputDialog("Enter number of rows"). class Matrices{ public static void main(String[] args){ String input. int[][] matrix1 = new int[rows][columns].parseInt(input).parseInt(input). i < rows.parseInt(input).showInputDialog(m2+"["+i+"]["+j+"]"). we filled the array above with sub-arrays.print(a[i][j] + " "). matrix1[i][j] = Integer.System. import javax. } } for(int i = 0. for(int i = 0. columns. j < columns. input = JOptionPane. rows = Integer.showInputDialog(m1+"["+i+"]["+j+"]"). i++){ for(int j = 0. columns = Integer.swing. Two dimensional arrays are common in representing matrices. } System.println(""). input = JOptioPane.showInputDialog("Enter number of columns"). i++){ for(int j = 0. j++){ input = JOptionPane. j++){ input = JOptionPane.*.out. 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). String m2 = "Enter second matrix elements\n".

for(int i = 0. Exercises 1. i++){ for(int j = 0. } Be ware of the difference between strings and arrays when accessing length.} int[][] result = new int[rows][columns].print("There are " + count + " spaces in the string").out. this could be accomplished through two methods in String class called length() and charAt().out. String a = "a string with four spaces". but in string. length in arrays is a variable so we call it without brackets. String output = "". for(int i = 0. the following example prints a string putting each character in separate line. i++){ System. Write a program that reads 10 integers from the user and then prints them out in reverse order. } JOptionPane. output += result[i][j] + "\t". } } System. calling charAt(3) in the previous example returns 'Q'. } } 9. int count = 0. for example. String s = "Al-Quds".length().4 String as Arrays We can deal with strings as array of characters. for(int i = 0.showMessageDialog(null. "Result is\n" + output). i < rows. 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 . j++){ result[i][j] = matrix1[i][j] + matrix2[i][j].charAt(i) == ' '){ count++. i < s. 2. length() is a method so we call it with brackets. i < a. i++){ if(a.charAt(i)).length(). } output += "\n". j < columns. charAt() method simply returns the character contained in the provided zero-based index within the string.println(s. The following example counts how many spaces there are in certain string.

} } Here is an example of the the execution of the above code. Then the whole matrix is printed. you can add command line arguments by opening project properties. The following example shows how to read numbers from command line and print their sum. java QuickSum 3 4 6 2 sum = 15 In NetBeans IDE. the last row of the matrix should contain the sums of the columns (see figure 9.println("sum = " + sum). stores them in 5 by 4 matrix. i < args. first we should know how to provide command line arguments.. 3. Write a program that reads 16 integers from the user. arg_n The arguments we provide after class name are stored in args array.2 (Exercise 3) Lab Extras You may have noticed that when we declare the main method we specify an array of strings String[] args. when we run a class we use the following command. i++){ sum += Integer. 4 User input 3 1 8 7 8 3 1 1 9 4 5 8 5 5 6 Sum 16 19 19 24 Figure 9. for(int i = 0.out.parseInt(args[i]). Java Lab Manual by Yasser Jaffal (2008) 54 . selecting "run" node from properties tree on the left. then entering arguments in "Arguments" field separated by spaces. the number of arguments determine the length of the array.length. notice that arguments are separated by spaces.students with the highest and lowest marks. } System. java ClassName arg_1 arg_2 .. class QuickSum{ public static void main(String[] args){ int sum = 0. To see how it works. This array stores command-line arguments and it could be used as input method in addition to input methods we discussed earlier.2) calculated by your program.

which is adding data to this table.2 Implementing Databases using Arrays In Java. Declare an array for each column of its selected data type. Vendor Mazda Honda Fiat Honda Nissan Model 1988 1995 2000 2002 2000 Table 10. We have to declare three arrays for them. int[] model = new int[5]. Java Lab Manual by Yasser Jaffal (2008) 55 . 2. 10. Lets say that we have selected String data type for both “Vendor” and “Color” columns and int for “Model”. in the large picture. Each row in the table will take a common index in all arrays. Specify appropriate data type for each column. we have to do the following: 1.1). What we are interested in right now is to understand the concept of tables and how to implement them using Java arrays. Consider for example that we have a table to store data about cars. One thing left.1 using arrays. 10.Session 10 Applications on Arrays (Databases) Objectives: ● ● ● Understand the concept of databases. Insert data to arrays by putting each row entry in the same index in all arrays. Implementing databases using arrays. String[] color = new String[5].1: Cars database Color Red Silver Blue Red Black 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. 3. For example.1 What Are Databases? Databases are used to store large amount of data in one or more tables. this table is shown below (table 10. we represent the first row by setting the following. for example. This is a simple task based in array index. if we wish to represent the table 10. Performing search and update. these tables have relations between them. String[] vendor = new String[5]. you can use arrays to simulate tables of databases.

model[0] = 1988. "Fiat". } Exercises 1. i < color. It is possible now to search inside this table. 2002 . "Nissan"}. 2000 }. for(int i = 0.2 below. "Red" . we can search by color or by vendor. for(int i = 0.length. Your applet should have three buttons. 1995 . i++){ color[i] = "Red". "Black" }. but performs search using model Similar to “By Vendor”. we can update table data by updating arrays contents. 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”. } } In a similar way. To represent the whole table. to find the cars manufactured in year 2000. String[] color = {"Red" .out. "Silver" . the following code sets all cars colors to red. Write Java Applet that implements cars table. we can do something like this. For example. for example. "Honda" . color[0] = "Red".println(vendor[i] + " . 2000 . a text field and a text area (TextArea class is like TextField but have multiple lines). i++){ if(model[i] == 2000){ System. "Blue". "Honda". String[] vendor = {"Mazda". but performs search using color Figure 10. The following table shows how should this Applet behave.length." + color[i]). Additionally. int[] model = { 1988 .2: Cars Applet Java Lab Manual by Yasser Jaffal (2008) 56 . we can declare arrays as following.vendor[0] = "Mazda". It should look like figure 10. i < model.

class MyApp extends Applet{ public void paint(Graphics g){ } } The object g is used to draw on the Applet. 0. To solve this problem. for example. The code below shows this method.Applet. import java.awt. getWidth().1 (in the next page). } public void paint(Graphics g){ g.1 paint() Method As you have seen in session 5. 200).*. Applets have two important methods. we can draw a line from the upper-left to lower-right corners of the Applet.drawLine(0. so you cannot control which graphics should be drawn at runtime. init() and paint().Session 11 Applets and Graphics Objectives: ● ● ● Using paint() method to draw on Applets. Introducing different methods of Graphics object. getHeight()). } } The weakness of paint() method is that it is called automatically each time Applet repaints. 11. Java Lab Manual by Yasser Jaffal (2008) 57 . public class LineApp extends Applet{ public void init(){ resize(200. Result is shown in figure 11. and it is now the time to have a look at paint(). import java. Calling getGraphics() to draw after Applet initialization. we obtain Graphics object from any other method using getGraphics() method. We have discussed init() method earlier. This example is shown in the code below.applet.

addActionListener(this). diameter). Java Lab Manual by Yasser Jaffal (2008) 58 .drawOval(0.Figure 11. value = new TextField(). draw = new Button("Draw").*. draw.1: Line Applet The following example draws a circle at the upper-left corner of the Applet with the specified radius. Button draw. add(value). import java.awt. } public void actionPerformed(ActionEvent e){ Graphics g = getGraphics().parseInt(value. import java.getText()) * 2.awt.2 on the next page shows an example of circles Applet. public class Circles extends Applet implements ActionListener{ TextField value. 0. } } Figure 11. Notice how do we use drawOval() method. 400). int diameter = Integer. diameter. add(draw).event. public void init(){ resize(400.*.Applet. import java. g.applet.

x2. Button Line Circle Functionality Draws line from (x1.4 shows how should your Applet look like. Write a Java Applet that has 5 int fields. y1) and has the radius of the value entered in radius text field Table 11. y1) to (x2.Figure 11. y2 and radius. Add two buttons to your Applet named “line” and “circle”. Figure 11. named x1.3 below. y2) Draws circle centered on (x1. The behavior of these buttons should be as shown in table 11.4: Exercise 1 Java Lab Manual by Yasser Jaffal (2008) 59 . y1.2: Circles Applet Exercises 1.3 Figure 11.

so we call it void method.1 What Are Methods In programming.Session 12 Methods Objectives ● Introducing method structure. these statements are executed when method is called. separated by commas. printing output on the screen and so on. Java Lab Manual by Yasser Jaffal (2008) 60 . The contents of method definition are the following: ● static: because we will be calling our methods from the main method which is static. ● Method body: statements of the method.parseInt() method returns integer data type. The naming convention for method name is like variable name. first word starts with lower case letter. use the following definition format. and println method does not return any thing. we have introduced a number of known methods like println and readLine. param_2.. like reading input from user. Integer. To define a void method. ● Writing and calling methods. param_n){ //Method body return returnValue. for example. ● return: when a method has return type (not void). println method takes one parameter as string and prints that string on the console. ● Understanding return types and void methods. value or expression that represents the value method should return. To write a method. ● List of parameters: method parameters provide an interface for providing input to method. ● Return type: data type of the value this method will return. we have to terminate it using return keyword followed by the variable. use void keyword instead of return type in definition. static ReturnType methodName(param_1. and rest of words start with upper case letters. this name must be a valid variable name (we discussed naming rules earlier).. . So far. those procedures are called methods. and as we will be calling our methods from the main method. for example. Method could take zero to infinity parameters. and it is clear this makes our work easier. those parameters are variables specified by data type and name. 12.. ● Differentiating between passing by value and passing by reference. we will use static in method definition. there are some common procedures we occasionally use. ● Method name: the name we will use to call our method. these methods are previously written by developers of Java. so we can directly call and use them. } Using static keyword is not part of the format and there are more options for definition. we shall define our methods as static. but right now.

int b){ int c = a + b. The advantage of returning the value is that gives programmer more options to do with the result Java Lab Manual by Yasser Jaffal (2008) 61 . y). similar to parameter copying.println(c). } static int sum(int a.out. return c.println(z). all we have to do is to specify method name and pass the parameters.out. so we call it and assign the return value to a new variable z. } } This time we specified integer as return type of the method. System. ● Method calling is simple and straight forward.2 Writing and Calling Methods The following example shows how to add two numbers using method calling. but is still in the block of the class. Technique 1: method takes parameters and prints the sum: class Addition{ public static void main(String[] args){ int x = 5. int b){ int c = a + b. Technique 2: method returns integer that contains the sum of two numbers. sum(x. so we define additional methods out of the block of main method. ● When method is called. similarly. class Addition{ public static void main(String[] args){ int x = 5.12. so it does not contain return statement. int y = 7. it contains the sum of x and y. int z = sum(x. y). } static void sum(int a. int y = 7. ● The method we have written is void. the value of x is copied into matching method parameter which is a. } } From the previous code you can notice the following: ● No method is defined in the body of another one. the value of c returned from the method is copied in z. the value of y is copied into b. System. so when c is calculated.

println("Welcome " + name). this eases code writing by handling the exception so we no more need to declare our methods to throw it. System. sum(1. int age = readInt("Enter your age:"). BufferedReader in = new BufferedReader( new InputStreamReader(System. 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. }catch(Exception e){} return "". } } 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.readLine().instead of just printing it out.print(message). 6)). consider the situation in which we need to use our method to calculate the sum of four values instead of two. The second method we used is called readNumber.//z = 12 In the above example. we will try to simplify the process of reading input by putting all of its steps in a single method with single call. Lets have a look at more complex methods. We use try and catch instead of throwing the exception. passes it to readString and get the value returned from it. and more useful ones. class ReadingSimplifier{ public static void main(String[] args){ String name = readString("Enter your name:").in)).io.out. try{ String input = in. In the next example.out.*. it takes a string to display for the user. return input.parseInt(input). } static String readString(String message){ System. this string is the message that will be displayed for the user as input prompt.println("Your birth year is " + (2007 – age)). return Integer. first time with 2 and 3 so it returns 5. System. } static int readInt(String message){ String input = readString(message). import java. Java Lab Manual by Yasser Jaffal (2008) 62 .out. 3). readString also returns a string that represents the value entered by user. then converts the returned value to integer and returns it. second time with 1 and 6 so it returns 7. sum is called 3 times. it can be reached using second technique through calling the method more than one time. int z = sum(sum(2.

in which values are copied from the parameters to the local values of the method. A common example of objects passed by reference is passing an array object.out. the output is 1.3 Passing by Value and Passing by Reference When methods are called. there are two different ways to pass parameters to method body. Consider the following code. } static void add(int i){ i++. add(a).println(x). but x itself had never affected. the common way is pass by value. because the value of x was copied into i. For example. } Java Lab Manual by Yasser Jaffal (2008) 63 . that is. any change we make on the array x inside add method is reflected on array a.out. 1}. then the value of i was incremented.4 Recursion We can write a method that calls itself. static int factorial(int n){ //Base case if(n == 0 || n == 1){ return 1. consider the following code. a recursive method calls itself with different parameters to do certain job. the object itself is passed to the method. System. consider the following method that calculates the factorial of a given integer n. System. add(x). Because arrays are passes by reference. all objects in Java are passed by reference. 12. rather we passed its value. the output you will see is 0. } static void add(int[] x){ x[0] += x[1]. because we did not pass x. } If you compile and run the code above. //main { int[] a = {0. //main { int x = 0.12. these methods are called recursive methods. } If you compile and run the above code.println(a[0]). On the other hand. because a and x are two references to the same object.

For example. the execution of the method will flow like this: 1. You will be given a lab on recursion on separate sheet and you have to solve it. we build recursive methods using a base case and a recursive call. Write a void method called reverse that takes a string as parameter and prints it in reverse order and inverted letter case. The result of multiplication (6) is returned to the previous call and multiplied by 4 8. Write a method named average that takes array of doubles as parameter then returns the average of the values inside the array. the output should be "AVAj". both numbers have the factorial 1. Java Lab Manual by Yasser Jaffal (2008) 64 . 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. so we return n multiplied by the factorial of n – 1. 2. so return 1 (base case) 5. so return 4 * (4 – 1)! (recursive call) 2. (n = 3) Is 3 = 0 or 3 = 1? No. Hint: use integer values of characters to determine upper and lower cases. The result of multiplication (2) is returned to the previous call and multiplied by 3 7. if we tried to get the factorial of 4. The recursive call is executed if the base case is not reached yet (i. then returns an integer representing number of occurrences of the character in the string. 1 is returned to the previous call and multiplied by 2 6. Write a method named countChar that takes two parameters: a string and a character. in case of factorial.//Recursive call return n * factorial(n – 1). there are more recursive calls until job is done).e. (n = 2) Is 2 = 0 or 2 = 1? No. so return 3 * (3 – 1)! (recursive call) 3. In the above code. } As you can see. for example if the input is "Java". (n = 1) Is 1 = 0 or 1 = 1? Yes. for example. Write a method named maxPosition that takes an array of integers as array and returns the index of the maximum element in the array. so return 2 * (2 – 1)! (recursive call) 4. the base case is when n is equal to 0 or 1. The result of multiplication (24) is returned by the method as final result. 5. 3. (n = 4) Is 4 = 0 or 4 = 1? No. we build our recursive call using the mathematical fact which states that n! = n (n – 1)!. the base case is the condition at which we stop the recursion. Exercises 1.

2 Writing Classes in Java So far. By the same way. Car A: Color: red. objects like these: 1. ● Shift down. ● Steer right. their rule was only to include the main method that we use to run the program. Manufacturer: Nissan. after creating this class. ● Start engine. 3. and each object represents different car.Session 13 Object-Oriented Programming: Classes and Members Objectives ● Understanding the concept of Object-Oriented programming. ● Color. we can represent any real-life object or any other object at any field. year: 1998. Java Lab Manual by Yasser Jaffal (2008) 65 . you have been writing a lot of classes. ● Stop engine. Car B: Color: black. this representation includes both attributes and behavior. so we may have. ● Steer left. 2. that is. these classes does not necessarily have main method and hence are not executable. class Circle{ //Radius is enough to determine all circle attributes public double radius. Number of wheels: 6. ● Transmission (Automatic. We define this set of attributes and behavior in a class called Car. we have to specify its attributes and behavior as the following: Attributes: ● Engine No. Behavior: ● Move forward. ● Shift up. ● Stop moving. ● Introducing classes and objects and differences between them. Transmission: Normal. We will start now to write classes that represent real-life objects. for example. like circles and triangles in representation of geometrical shapes. if we want to represent a car in Java. ● Chassis No.1 What is Object-Oriented Programming? Object-Oriented programming is based on representing real life objects using software. the class defines common properties among all cars. for example. we can define several objects of this class. A.Start engine. a class that represents circle shape. we will leave the car example to something more simple. Man. ● Model name. 13. For simplicity. ● Move backwards.Move forward and so on. ● Manufacturer. ● Understanding class members and their properties. A. Normal) ● Number of wheels. ● Understanding polymorphism and method / constructor overloading. 13. but these were far from the idea of representing real-life objects. ● Manufacturing year.

when declaring a Circle object. because all circle measurements are based on the radius. As we declared radius to be public.//Constructor public Circle(double r){ radius = r. As shown above. When we call a member from the object. constructors are used to determine the initial values necessary to build objects and are used after new keyword in declaration. we call it constructor. } public double getCircumference(){ return 2 * Math.getArea()). Java creates a default constructor that takes no parameters. when we declare an object from the class Circle. System. we need to specify the radius of that circle. You can also notice a method that holds the same name of the class and does not has a return value. Circle c1 = new Circle(10).getDiameter()).' to access the members then specify member name. } public double getDiameter(){ return radius * 2. for example.out. so we write a constructor that takes radius as double.println("c1 Area is " + c1. Circle c1 = new Circle(10). this keyword means that the member is accessible from outside the class. the default constructor is no more available. we can access all public members.PI * radius. Circle c2 = new Circle(12).println("c2 Diameter is " + c2. If we don't write a constructor for our class. we use dot '. 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. we can access it just like any other members to change the radius after declaration. declaring objects is straight forward. System. } } The above class contained members declared using public keyword. } public double getArea(){ return (radius * radius) * Math. but once we write a constructor. actually. } //Methods public double getRadius(){ return radius. we use something similar to variable declaration. that is.out. even if we declare the object outside Circle class. To declare a Circle object. Java Lab Manual by Yasser Jaffal (2008) 66 .PI.

//Changes the value by mutator method System.getArea()). set methods are called mutators. thats why we were declaring methods using static keyword. For now.out. } } class B{ public static void main(String[] args){ A a = new A().value).out. //Error.println("c1 Area is " + c1. On the variable level.println(a.radius = 15. the static variable is shared among all objects of the class. these properties are enough for us.out. This is clear when declaring main method.getArea()). //prints 33 Java Lab Manual by Yasser Jaffal (2008) 67 . ● static: by static. public int getValue(){ return value.getValue()). The following example clearly explains the difference between public and private members: class A{ private int value = 10. } public void setValue(int newValue){ value = newValue. we can use accessors and mutators methods o access the value stored in class A as the following: class B{ public static void main(String[] args){ A a = new A(). because main is static. It is important to know that static members cannot by called from non-static members and vice versa.out.println("c1 Area is now " + c1. c1. we mean set of access rules that controls how these members are accessed and called from the class or an object of that class. value is private } } Trying to access private member from outside the class reports compile-time error.System. In the above example. private states that the member is accessible only from within the same class (a method or constructor inside the class). Here is a list of access rules and their use: ● public: states that the member is accessible from outside the class (from another class). because when we run our class we do not declare an object from it. System. we have introduced one of these properties in Circle class which is public. we have to declare any method we wish to call from main as static also. ● private: in the contrary of public.3 Different Properties of Class Members By properties of members. It is a common practice in Object-Oriented that we declare members that store values as private and create set and get methods to access them.println(a. we specify that a certain member can be called without declaring an object (by calling class name followed by dot then member name). a.setValue(33). and get methods are called accessors. System. 13.

println("a =" + s2. b =" + s2. b =" + s2.println("s1 values:").out. System.setA(5). } } class Main{ public static void main(String[] args){ StaticTest s1 = new StaticTest().getA() + ".println("\ns1 values:"). System.getB()). System.setB(3).println("s2 values:").} } The following example shows the difference between static and non-static variables: class StaticTest{ private static int a. System. s1. System. } //Mutators public static void setA(int newA){ a = newA. public StaticTest(){ a = 0. } public int getB(){ return b.out.out. b = 0. } } Compiling and running the above code shows the following output: s1 values: a =0. b =0 s2 values: a =0. b =0 Java Lab Manual by Yasser Jaffal (2008) 68 .out.getB()).out. System. System.getA() + ". private int b.getB()). } public void setB(int newB){ b = newB.out.println("a =" + s1. System. b =" + s2. StaticTest s2 = new StaticTest().out.getA() + ".println("s2 values:").println("a =" + s1. } //Accessors public static int getA(){ return a.getA() + ".println("a =" + s2.out. b =" + s2.getB()). s1.

Rectangle a = new Rectangle().s1 values: a =5. when we call a constructor after new keyword. changing the value of b in object s1 did not affect the value of b in s2. we have three constructors having the same name.getA()).println(s1. To see how parameters can help in overloading. } } As the above example illustrates. for example.//Second constructor Java Lab Manual by Yasser Jaffal (2008) 69 . System. because there are more than one way to discriminate between methods. public Rectangle(double h. which is not the situation with a. println method will print 13 two times. width = w. 13. you can notice that getA and setA methods are declared static. } public Rectangle(double d){ height = width = d.4 Methods and Constructors Overloading Overloading means to have more than one constructor or more than one method having the same name. b =3 s2 values: a =5. including name and number and type of parameters.setA(13).getA() + " " + s2. back to StaticTest class definition. variable a and methods related to it could be called from the class name directly as shown below: StaticTest. consider the following constructors. thats because static members are shred among all objects as stated. depending on parameters we specify a matching constructor is selected. class Rectangle{ private double height.out. double w){ height = h.//Third constructor Rectangle b = new Rectangle(5). Remember to declare static methods when dealing with static variables. width. } public Rectangle(){ height = width = 1. b =0 So what can be concluded from the output? The value of b is different for each object. In the above code. because changing the value of a in s1 had its effect in a when called from s2.

2 = manager Java Lab Manual by Yasser Jaffal (2008) 70 . Exercises 1. Order of parameters. Types of parameters. } } To better understand classes and objects.//First constructor It is important to realize that discriminating between constructors and methods holding the same name are: 1. Number of parameters.//Employee name ○ private int type.//Height ○ private double base. 2. the name of this object is out. non-static method called println that has several overloads.//Employee id ○ private String name. 4). there is a public. Inside PrintWriter class.//Sets base length ○ public double getBase(). System is a name of a class. Write a class that represents triangle named Triangle. the class should contain the following members: ○ private int id. Write a class Employee that represents an employee of some organization.//Constructor ○ public void setHeight(double x). double b).//Gets base length ○ public double getArea(). public void setValue(int t){ value = t.//Returns the area of the triangle 2.println("Hello World"). } public void setValue(int s){ value = s. So it is important to know that parameter name has nothing to do with overloading. the class must have the following members: ○ private double height.//1 = employee. inside System class. class A{ private int value.Rectangle c = new Rectangle(3. 3. //This code generates error message. lets analyze a well-known statement we've been using repeatedly: System. there is a public and static member (object) of class PrintWriter.out. the following example shows this.//Gets height ○ public void setBase(double x).//Base length ○ public Triangle(double h.//Sets height ○ public double getHeight().

so what you have to do is to pass parameters to this just like the way you pass them to any constructor. we can use this keyword.//Base salary public Employee(int _id. we use this to specify which one in in the scope of whole class. it has to be a global member.//id accessor public String getName()..//name accessor public double getSalary(). Lab Extras When we wish to specify a member from the class. public Vector(double length.length = length. String _name). add 10% to base salary public void setBaseSalary(double bs). //if manager. Another use of this keyword is to call a constructor from within another constructor. This technique is common when writing default constructor that does not require user to specify parameters. this refers to the current object of the class. this.//id mutator public void setName(int x). public Square(int sideLength){ this. double angle){ this.//name mutator public int getID(). to discriminate between local and global variables in a class that have the same name. we are returning back to the scope of the class. when we call this.sideLength = sideLength.○ ○ ○ ○ ○ ○ ○ ○ private double baseSalary. } public void setSideLength(int sideLength){ //global local this. private double angle. one is global for the whole class and it is where we store the value. } public Vector(){ /* Calling the previous constructor. } } As you can see. For example. and other is local for the constructor (or method). we have two variables called sideLength. class Vector{ private double length.//Constructor public void setID(int x).sideLength = sideLength. class Square{ private int sideLength. Java Lab Manual by Yasser Jaffal (2008) 71 .angle = angle. this itself represents the call. so if we are to specify any member after this.//sets base salary.

0). when using this to call another constructor. these statements should be specified after this call. in other words. } } If you need to specify additional statements in the constructor from which you are calling another constructor.passing 1 as length and 0 as angle */ this(1. it should be in the first statement. Java Lab Manual by Yasser Jaffal (2008) 72 .

String input = in.io. . exception is a special type of classes that could be thrown to indicate a runtime error and provide additional data about that error. this exception is thrown as it Java Lab Manual by Yasser Jaffal (2008) 73 . } } If we wish to write a method that simplifies reading from user. we used to declare main method from which we call readLine() using throws IOException. Recalling reading from user using BufferedReader class. import java. 14. this because readLine() is declared to throw that exception. BufferedReader in = new BufferedReader( new InputStreamReader(System. ● Understanding and writing custom exceptions. ● Using try-catch to handle exceptions.print(message).*.readLine(). any other method calls it should deal with this exception by throwing it (if it appears) or handle it. you may want to declare it to throw IOException.Session 14 Exceptions and Error Handling Objectives: ● Understanding exception-throwing methods. if an exception occurs in readLine() method. If a method is declared to throw an exception.1 Exception-Throwing Methods Runtime errors appear in Java as exceptions. class ReadFromUser{ public static void main(String[] args) throws IOException{ String in = read("Enter your name: ").in)). return input. } public static String read(String message) throws IOException{ System.*.out.io. class ReadFromUser{ public static void main(String[] args) throws IOException{ . } } In the previous code. . import java.

int x = Integer. String input. BufferedReader in = new BufferedReader( new InputStreamReader(System.readLine(). BufferedReader in = new BufferedReader( new InputStreamReader(System. 14. we can place readLine() method which throws IOException in a try-catch block as the following.3 Writing Custom Exceptions In some cases while developing our own applications. }catch(IOException e){ System. the exception is throws to JVM which prints it out on the screen so the user can know there was error. finally. try{ input = in. because this last one is also declared to throw that exception.is to read method. which originally called it. }catch(NumberFormatException err){ System. } When we are expecting more than one exception.println("Error occurred"). } 14.println("Error reading input"). }catch(IOException e){ System. we can use several catch blocks. String input. try{ input = in. we need to specify custom types of Java Lab Manual by Yasser Jaffal (2008) 74 . it also throws it as it is to main method.out. For example.out.in)). try{ //Statement(s) that may throw exceptions }catch(Exception e){ //Statement(s) to handle exception. when reading a string using BufferedReader and converting it to integer. } For example.2 try-catch Exception Handling Another technique for handling runtime errors is to use try-catch block to handle different types of exceptions and take appropriate action instead of throwing them to the user. which originally called it. The format of try-catch block is the following. each one for different type of exceptions.readLine().println("This is not a valid number").in)). you can expect two different exceptions: IOException and NumberFormatException which occurs when the provided string cannot be converted to integer.parseInt(input).out.

} public String toString(){ return message. try{ verfyID(id).*. declare an object of it and throw that object using throw keyword. the program reads student id.showInputDialog("Enter student ID"). class StudentsData{ public static void main(String[] args){ String id. } public String toString(){ return message.message = message. } Java Lab Manual by Yasser Jaffal (2008) 75 . public MyCustomException(String message){ this.showMessageDialog(null. this id should be of length 7 and consists only of digits.exceptions to handle custom errors that may occur during program execution.swing. } } Import javax. e. It is optional to declare the method containing throw statement with throws keyword. otherwise it throws an exception. class MyCustomException extends Exception{ private String message. } catch(InvalidIDException e){ JoptionPane. } } To use your custom exception. In the following example. we will define it as using extends Exception in class declaration. since inheritance is beyond the scope of this course. id = JOptionPane.toString()). name = JOptionPane. public InvalidIDException(String message){ this. name.message = message.showInputDialog("Enter student name"). class InvalidIDException extends Exception{ private String message. A custom exception is a class that inherits Exception class or any of its subclasses.

} } } Exercises 1. packaging means putting two or more classes in the same package by stating package name before declaring class (and also exceptions). another class named Main to run a program that manages student information. Lab Extras In order to access the exception from the class it uses. that class is automatically declared as a part of that package. If minimum value is greater than or equal to maximum value. When two classes are in the same package. Figure 14. for example. } catch(Exception err){ throw new InvalidIDException("ID can contain only digits"). In NetBeans IDE. if we have a class named Student that represents a student. it is possible to access any one of them from the other. } try{ Long. 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. by adding new class to any package of your project. For example. 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.length() != 7){ throw new InvalidIDException("Check ID length"). 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. there is no need to manually write the above statement. there is an important aspect one should be aware of which is packaging. Write a program that count how many prime numbers between minimum and maximum values provided by user.parseLong(id). Java Lab Manual by Yasser Jaffal (2008) 76 .1 shows packages and classes in NetBeans IDE project explorer. and a third class called StudentDataException that represent any errors in student information.} public static void verifyID(String id) throws InvalidIDException{ if(id.

' then desired class name.1 by calling it in the following statement: linkedlist.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 '.Figure 14. For example.Main Java Lab Manual by Yasser Jaffal (2008) 77 . we can access Main class show in Figure 14.

Sign up to vote on this title
UsefulNot useful