Java Lab Manual

thrillukrainianΛογισμικό & κατασκευή λογ/κού

7 Ιουν 2012 (πριν από 4 χρόνια και 10 μήνες)

613 εμφανίσεις

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
Session 1
HTML and Webdisk (Revision)
Objectives:

Creating web pages with rich contents.

Uploading web pages to Webdisk.

Accessing web pages from the Internet.

Adding content to an uploaded web page.
1.1 Creating Web Pages using HTML
As you have learned in CS101, we use HTML language to write web pages. Pages written with

HTML could contain text, tables, images and other media. What you are asked to do today is to

create a web page and uploading it to your Webdisk, this task is achieved by following the

instructions below. First of all, you have to create you personal web folder (if you haven't do so

yet). To create the web folder, follow the following steps:
1.
Run
Internet Explorer.
2.
Go to web page:
http://mail.alquds.edu
3.
Enter your student profile login information to access your mailbox.
4.
From the tool bar, click
Webdisk
icon.
5.
Under
operation
field, write

public_html
and click on
MkDir
button, by doing this,

you are creating a folder named
public_html
, this is the folder in which you will put

your web pages.
6.
Click on
public_html
to open it. It is now the current working directory.
7.
Inside
public_html
, create another folder called
lab1
.
After preparing your Webdisk, you are ready to create a web page and upload it, to create a simple

HTML page, follow the following steps:
1.
Start the notepad from
Start
-->
All Programs
-->
Accessories
-->
Notepad
(or simply type

notepad in the run dialog
Start
-->
Run
)
2.
Enter the following text:
<html>
<body>
<h1> This is a Major Heading </h1>
<ul>
<li> List item one
<li> List item two
</ul>
</body>
</html>
3.
Save your file as index.html
4.
Back to Webdisk, under upload field, browse for your file (index.html) and click on
Upload

to upload your file to the server, make sure to upload it inside lab1 folder.
5.
Using browser, confirm page at
http://mail.alquds.edu/~s999/lab1



(where s999 should be

replaced by your student profile login id).
Java Lab Manual by Yasser Jaffal (2008)

4
1.2 Adding Content to Web Page
To add an image to your web page, use the following code:
<img src="
image_name
"></img>
Also, 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.
<table border=1>
<tr>
<td> Row 1 Column 1 </td>
<td> Row 1 Column 2 </td>
</td>
<tr>
<td> Row 2 Column 1 </td>
<td> Row 2 Column 2 </td>
</tr>
</table>
The table that resulted from the above code is shown in figure 1.1 below.
Figure 1.1: HTML Table
To link two pages together, we user the Hyperlink, to create a Hyperlink to another HTML page,

use the following syntax:
<a href="
target_page
">
Display Text
</a>
Exercises
1.
Create a page named index.html and upload it to “lab1” folder in your public_html

directory.
2.
Modify index.html by adding
a.
A table,
b.
A Hyperlink to university's homepage (
http://www.alquds.edu
), and
c.
At least one image.
Java Lab Manual by Yasser Jaffal (2008)

5
Session 2
Introduction to Java
Objectives:

Introduce programming languages.

Introduce Java programming language.

Show how to set up your system environment for Java development.

Write, compile and run your first Java application "Hello World".
2.1 Programming Languages
By
programming language
, we mean a set of vocabulary, grammar and libraries that

construct a language we can use to write computer programs.
A programming language consists of the following:

Vocabulary: set of meaningful
keywords
that have specific meaning in the programming

language (also called
reserved words
).

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
.

Software Development Kit (SDK) that contains the following:

Libraries: also known as Application Programming Interface (API), these files are

previously written classes and methods that contain some common functionality.

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.

Interpreter: some programming languages does not compile the source code file into

directly executable form (native code), but they instead compile it into partially

compiled file that could be executed by a program called
interpreter
.
2.2 Java Programming Language
Java programming language is an
interpreted
programming language, that is, when the

source code is compiled into binary file, it needs an interpreter called Java Virtual Machine (JVM)

to run it.
Java compiler is called
javac.exe
, and interpreter is called
java.exe
. Figure 2.1 shows a Java

technology overview.
Figure 2.1: Java technology
2.3 Setting Up Your Machine for Java Development
To be able to write, compile and execute Java applications, you need a set of tools called

Java Software Development Kit (JSDK)
.
This SDK could be obtained from Java official site at

Java Lab Manual by Yasser Jaffal (2008)

6
http://java.sun.com
.
After downloading the installation file (about 60 MB) you are ready to start the installation process.

Follow the following procedure to prepare your machine.
Step 1
: Double click on
jdk-1_5_0_06-windows-i586-p.exe

icon, the setup wizard appears as in

figure 2.2.
Figure 1.2: First step of JDK setup wizard
Select
I accept the terms in the license agreement
and click on
Next
. Custom setup dialog appears as

in figure 2.3.
Figure 2.3: Setup options
It is advisable that you change the installation path by clicking on
Change
button and selecting the

path
"
C:\jdk
"
as installation directory. After you have done changing the path, click on
Next
to start

the installation and wait until its done. When installation is complete, click on
Finish
to terminate

installation wizard.
Java Lab Manual by Yasser Jaffal (2008)

7
Step 2
: You need now to define some environment variables to be able to use the tools you've just

installed. To define an environment variable, right-click on
My Computer
icon on the desktop or

start menu, then select
Properties
from the pop-up menu. The
System Properties
dialog appears,

from the top of the dialog box select
Advanced
tab as shown in figure 2.4.
From
Advanced
tab, click on
Environment Variables
button, Environment Variables dialog appears

as shown in figure 2.5.
2.4: Windows advanced settings
To add new environment variable, click on
New
button in
User Variables
field, note that you may

not modify system variables unless you have administrator privileges. Once you click on
New

button, variable addition dialog appears as in figure 2.6.
In
Variable name
field enter the name of your variable, in
Variable value
field enter the value of the

variable then click on
OK.
You need to add two variables to use with JDSK:

PATH
: points to
bin
directory in JSDK home directory (e. g.
c:\jdk\bin
)

CLASSPATH
: points to the folder in which you will create you Java programs (e. g.

c:\Documents
and Settings\Student\Desktop\java
).
Your computer is ready now to be used for Java development.
Java Lab Manual by Yasser Jaffal (2008)

8
Figure 2.5: Environment Variables
Figure 2.6: Adding new environment variable dialog box
2.4 Writing, Compiling and Running Your First Java Application
To write a Java program, open the command prompt by selecting
run
from start menu and

entering the command
cmd

in the dialog box, the command prompt console appears, show in

figure 2.7. Change to the directory you have selected as Java directory (for example

c:\Documents and Settings\Student\Desktop\java
) by using
cd
command.
Figure 2.7: Command prompt
To write a new Java program using the notepad, enter the command
notepad
filename
. For

instance, we will write a class named
HelloWorld
, so we will use the command
notepad

HelloWorld.java

(Figure 2.8). Note that we use a
.java
extension for all Java source files, and we

always use upper case characters in the beginning of a class name. After starting the notepad, it will

Java Lab Manual by Yasser Jaffal (2008)

9
ask you whether you wish to create a new file with the name specified, confirm file creation. It is

important to keep in mind that file name and class name must be the same, otherwise the compiler

will generate an error message and the file will not compile.
Figure 2.8: notepad command with parameters
In the notepad, write the following code (always keep in mind that Java is case-sensitive language,

for example if you typed
Class
instead of
class
the compiler will report a syntax error)
//HelloWorld.java
/* This is my first java program.
*/
class HelloWorld{
public static void main(String[] args){
System.out.println("Hello World!");
System.out.println("How r u 2day?");
}//end of main method
}//end of class
When you are done with code writing, save the file and exit notepad.
Your source code file is now ready for compilation, to compile a Java source code file, use the

command
javac
filename
. In our example,
javac HelloWorld.java
. If everything is alright, the

compiler will terminate without any messages and go back to command prompt as shown in figure

2.9. After compilation, if you run
dir
command, you will notice that the compiler generated a new

file called
HelloWorld.class
, this is the binary file JVM will execute. To run you application, use

the command
java
ClassName
, for our program, we will use
java HelloWorld
, if everything is

alright, you shall see the program output on the screen.
Notice that some lines in the program begin with //, these are called
comments
,

compiler does not

read comments, so whatever your write in them it will not affect the functionality of your program,

the notations /* and */ declare the beginning and ending of a block of comments, so we call them

multi-line comments
.
Figure 2.9: successful compilation
Java Lab Manual by Yasser Jaffal (2008)

10
Exercises
1.
Change the
HelloWorld.java
program so that it displays
Hola Mundo!
instead

of
Hello World!
2.
Try printing the following strings, what do they do?
1.
"Hello \t World"
2.
"Hello \n World"
3.
Try to use
print
method instead of
println.
4.
Consider the following
Useless
class. Compile and run it, what does it do?
public class Useless{
public static void main(String[] args){
System.out.println(java.util.Locale.getDefault()); }}
Lab Extras
Batch files are common in executing a series of shell commands, for example,

you can write a batch file to create and delete folder instantly, by writing the

appropriate commands in the notepad and saving the file with .bat extension. The file

will look like the following:
MD MyFolder
RD MyFolder
Note that we put each command in separate line. You can create a Java program that

runs everywhere by putting it together with a batch file that does the following steps:
1.
Adds the current folder to CLASSPATH by using the command
SET CLASSPATH=.
2.
Compiles the
.java
file.
3.
Executes the program.
Try to write a batch file that holds your name and runs a Java program that types your

name on the command line. Add
PAUSE
command at the end of the batch file in order

to freeze the screen after program execution to be able to see the results.
Java Lab Manual by Yasser Jaffal (2008)

11
Session 3
Working with NetBeans IDE
Objectives:

Showing how IDE software facilitates the process of programming.

Introduce the basics of NetBeans IDE.

Introducing debugging and its importance.

Introducing error types in Java and understanding error messages

Discriminating between run-time (semantic) errors and compile-time (syntax) errors.
3.1 IDE Software
IDE stands for Integrated Development Environment, IDE is a software that helps us

to write, compile, run and debug programs. IDE programs vary and each one of them usually

targeted to certain programming language, the following table shows well-known IDE

programs:
Programming

Languages
IDE
Java

NetBeans

Forte for Java

Borland JBuilder
C/C++

Microsoft Visual Studio

Borland C++
PHP/JSP/ASP

Macromedia Dreamweaver
ASP.NET

Microsoft Visual Studio .NET

Sharp Develop
We can notice from table above that we have various brands of IDEs, since we are interested

in Java programming language in this course, we will focus on its IDEs. NetBeans is the best

offered IDE for us as Java learners, because it is free compared to JBuilder, more advanced

and stable compared to Forte. So lets start having a look at NetBeans.
3.2 NetBeans IDE
Figure 3.1 shows the main screen of NetBeans IDE (version 5.0). You can download

NetBeans from
http://java.sun.com
, Once you have JDK 1.5 installed, NetBeans installation is

a straight-forward process.
To use NetBeans for writing and running your Java programs, Follow these steps:
1.
Create a new project by going to
File > New Project
, or by clicking on
New Project

button
on the toolbar; all programs written using NetBeans must be included in

projects to be able to be compiled and run. Project creation is a simple process consists

of two steps. First step is defining
project category
and
type
. In our case, we leave

the default settings, that is,
General
category and
Java Application
type. Second step

is specifying
project name
and
main class
.
Java Lab Manual by Yasser Jaffal (2008)

12
Figure 3.1: NetBeans IDE main screen
2.
After creating a project, you are ready to start coding, on the
project explorer
you

will see a tree that has the project name you specified as root. Project is split into four

folders:
Source packages
,
Test packages
,
Libraries
and
Test libraries
.
Source

packages
is the folder containing the source code files (.java files) and hence it is the

folder we are interested in. Source code is usually split into packages, so we can group

classes of related functionality together. Once you create a project, a default package

that holds project name is created.
3.
In the
code editor
, you will see the created
Main
class, with its
main
method already

coded, so you need just to start programming.
4.
In the
main
method, try to write some statements you've learned from session 1, after

you are done, you may compile and run the program by selecting
Run > Run main

project
, pressing F6 key on the keyboard, or clicking
Run

button
on the toolbar
5.
The
output window
appears at the bottom of the IDE and shows the outputs of

compilation and running processes.
Java Lab Manual by Yasser Jaffal (2008)

13
3.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. NetBeans allows you to debug

your program and trace any run time errors that may exist. Debugging in NetBeans IDE

means that you define one or more
break points
in your code, break point is a sign you may

put on any line of your program to have the debugger stop at it, when the execution of the

program reaches a break point, it hangs allowing you to review the values of variables at that

moment. To add a break point, click on the left of the line you want to insert the break point

in. Figure 3.2 shows a break point added in some lines.
Figure 3.2: Break points
To show how debugging works, make a small test by following the procedure below:
1.
Write the
HelloWorld
program from session 1.
2.
Add a break point in the second line (
System.out.println("How r u

2day?");
).
3.
Debug the program by pressing F5 key on the keyboard or by clicking on
Debug

button
on the toolbar.
4.
Observe the output of the program, what do you notice?
5.
Notice that when debugger reaches a break point, it turns to green, this means that this

is the next statement will be executed, as we put a break point on the second line, the

statement is not executed until we select to
continue
, this can be done by pressing Ctrl
+F5 or by clicking on C
ontinue button
on the toolbar.
6.
To stop debugging, press Sift+F5 on the keyboard, or click on
Stop button
on the

toolbar.
3.4 Error Types in Java
In Java (and other programming languages) there are two major types of errors:

Compile-Time errors (Syntax errors).
Java Lab Manual by Yasser Jaffal (2008)

14

Run-Time errors, these errors fall into two categories: exceptions and semantic errors.
Compile time errors are those the compiler detects while translating your program from Java

language to machine language, the most common reason for these errors is there is something

in your code does not follow Java syntax (that's why we call them syntax errors). The

following examples show some of these errors:
1.
System.out.println("Hellow")
2.
system.out.println("Hello");
3.
System.out.println("Hello);
4.
class Hello World{
5.
Class HelloWorld{
6.
public Static void main(string[] args){
OK, let's start with statement 1, what is wrong with it? Clearly Hello don't have "w" at the end

of it! However, this is not the error we are looking for, we are looking for violation of Java

language rules not English language rules. As we know, each statement in Java should be

terminated with semicolon "
;
" which is absent in our case. The message the compiler will

generate in this case is "
';' expected
", error message also includes the line in which

error exists as shown in figure 3.3.
Figure 3.3: Compile-Time error message.
In statement 2, you can notice that
system
is written in lower case, as we've learned before,

Java is case sensitive, and as
System
is a class in Java, it starts with upper case letter. The

message you will see in this case is "
Cannot find symbol
". This message means the

keyword or member name you are calling is not recognized as valid one. The most common

reason for this error is a spelling mistake.
In statement 3 , the error message is "
unclosed string literal
", because the

opening double quotation (
"
) does not have a matching closing one.
In statement 4, the error is that the given class name is not valid, as class name cannot have

spaces according to naming conventions in Java (as we shall see in next session). The error

message in this case is "
'{' expected
", the compiler assumes that class name finishes

when it finds space, after the space it is expecting the opening bracket "
{
".
In statement 5, the message generated is "
class or interface expected
", it is clear

that
class
keyword must start with lower case letter as all keywords in Java do so.
In statement 6, the message generated is "
<identifier> expected
", because
Static

is not a valid keyword. Notice that in this statements we have another error which is

"
cannot find symbol
" because
string
is written mistakenly in lower case, but it will

not be detected until first error is fixed because it appears first.
Run-Time errors appear when program run, the compiler cannot detect them because there are

no errors or rules violations. First category of run-time errors is
exceptions
, exception is a non

expected error happens while executing a code, an example of exceptions is

Java Lab Manual by Yasser Jaffal (2008)

15
ArithmeticException
which occurs when you try to divide by zero. The second

category are
semantic
errors, those are not actual errors detected by compiler, nor exceptions

occur at runtime, but they are unexpected results or outputs of your program, for example, if

your program is supposed to calculate the sum of three numbers, and we give it 1, 2 and 3 as

inputs, its output should be 6, otherwise we have a semantic error.
NetBeans can detect syntax errors while you type your program, so you can find them before

compiling you program. The statement containing an error is underlined by red line, and you

can see the error message by positioning the mouse pointer over the line as shown in figure

3.4. We will have a closer look at run-time errors and how to deal with them in the coming

sessions.
Figure 3.4: Error detection in NetBeans
Exercises
1.
Create a project using NetBeans called MyFirstProject, and type a program to print

your name and student ID each in separate line using only one
println
statement.
2.
What is the error message expected from each of the following statements? (Also

show if there is more than one error, and mention which one is detected first)
1.
System.out.println(Hello World!);
2.
System.out.pint("How are you?");
3.
public static void main(String[] args);{
4.
class My Class{
5.
public static void main(String() args){
6.
System.out.Print ln("Hi man!");
7.
System.out.print('What's up');
8.
System.out.println("I wonder where is the error?\m");
Lab Extras
You can add a new class to your default package and make it the default class to be

run instead of
Main
class. To do this, right-click package in the
project explorer
, open
Add

menu and select
Java Class
from the list. Enter new class name and click
OK
to see your

newly added class. Note that the Main class is still open and you can navigate between two

class using tabs above
source editor
.
To make your new class the default one (that is, it will run when you run the project), right-
click the project icon (Java cup) in the
project explorer
and select
Properties
from the menu.

This will open up
Project Properties
dialog. From the tree on the left, select
Run
category,

and type your class name in place of Main in
Main Class
text field. Be ware not to delete

package name mistakenly.
Now type a main method in your new class and put some code in it, run the project and you

will see the result. You may also run a non-default class by right-clicking it in the project

explorer and selecting run or using Shift + F6 keys while opening its code in the editor.
Java Lab Manual by Yasser Jaffal (2008)

16
Session 4
Variables, Data Types and Operations
Objectives:

Identifying variables and data types in Java.

Discriminating between primitive data types and classes (user-defined data types).

Applying operations to variables.

Converting between data types.

Understanding literal values and expressions.
4.1 Variables and Data Types
Variables are reserved areas in computer memory, holding unique name and expecting

some data format to store called
data type
. 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. Primitive data types are declared using special keywords. Table 4.1

shows primitive data types in Java.
Table 4.1: Primitive data types in Java
To declare a variable, use a statement with the following format:

datatype variableName;
Data type is one of primitive data types shown in table 4.1, variable name is a valid Java

Java Lab Manual by Yasser Jaffal (2008)

17
variable name, the name is valid if it:

Is not a reserved word.

Is not the name of a previously defined variable, even of different type (unique).

Starts with a letter ('
A
' to '
Z
' or '
a
' to '
z
'), a dollar sign '$' or an underscore '
_
'.

Contains only letters, dollar signs '$', underscores '_' and numbers.

Has no spaces.
In addition to previous conditions, we have some optional conventions but they are highly

recommended to follow them in order to stay up with the global standards of Java. One of

these conventions is to start class name (and each fragment in the name if it has more than

one) with an upper-case letter like
ClassName
and
MyFirstJavaClass
. We will be

talking about conventions as they appear. Here are some examples of declaring data types:
int anInt;
double d;
float average;
boolean done;
long x1, x2, x3;
As you can see, the first part is a primitive data type from table 4.1, and the second type is a

valid name. You can notice from the last statement that we can define several variables of the

same type by using commas '
,
' between names on the following format:
datatype var_1, var_2, ..., var_n;
A notable naming conventions in Java is the one we've used in the first statement, a variable

name should start with a small letter, and each following fragment with a capital letter like

variableName
and
averageOfMarks
.
So whats next? We have to assign some values in the variables we have just declared. Value

and variable must be of the same type, for example, you cannot store
7.34
in a variable of

type
int
(unless you convert). Table 4.2 shows examples of values and their appropriate

data types.
Table 4.2: Examples of values and data types
Java Lab Manual by Yasser Jaffal (2008)

18
As you can see, numerical values with decimal point are treated as
double
by default, if you

want to assign them to a
float
variable, you have to
explicitly
define it as
float
using
F

after the value. The value 26.77e3 is equal to 26.77 * 10
3
.
To assign a value to a declared variable, we use
assignment
operation denoted by equality

sign '=' in the following format
variable = value;
for example, to assign a value
10
to some integer
x
int x;
x = 10;
Assignment can be done in the same statement in which we declare the variable
float average = 81.5f;
boolean b = false;
System.out.println(average);//prints "81.5"
System.out.println(b);//prints "false"
4.2 Operations on Variables
As we have seen, most primitive data types are numerical, so we can perform binary

operations on them (addition, subtraction, multiplication and division), those arithmetic

operations are called
binary operations
because they are used with exactly two operands.

Table 4.3 shows arithmetic operators.
Operation
Operator
Usage
Assignment
=
var1 = var2
Addition
+
var1 + var2
Subtraction
-
var1 – var2
Multiplication
*
var1 * var2
Division
/
var1 / var2
Modulus (division remainder)
%
var1 % var
Table 4.3: Arithmetic operations
We have seen assignment before, and we know that is stores the value of right operand on the

variable on the left operand. Addition, subtraction, multiplication and division operations

generate
expressions
, an expression is a series of calculations that produces a single value.

Here are some examples of expression:
int a, b, c, d, e = 3; //variables definition
a = b = 5; //multiple assignment
c = 6;
d = c % a;//d = 1
Java Lab Manual by Yasser Jaffal (2008)

19
e = e + (a + b * c – d);//expression evaluation (e = 37)
System.out.println("The value of e is " + e);
Comments on the previous code:

It is valid to define multiple variables in the same statements and assign values to

them (statement 1).

You can assign single value to multiple variables in the same statement (statement 2).

We can use brackets '(' and ')' to specify which expressions must be evaluated first

(precedence overriding).

By default, multiplication has the highest precedence, followed by division then

addition and subtraction (in statement 5,
b * c
is calculated first).

Mod operator calculates the remainder when dividing first operator on the second.

We can
concatenate
a string with an integer by using "+" operator (last statement).
We have some shortcuts with binary operations, for example, expression
a = a + b
, could

be written in the form
a += b
, this way is valid for other operations as table 4.4 illustrates.
Expression
Shortcut
a = a + b
a += b
a = a - b
a -= b
a = a * b
a *= b
a = a / b
a /= b
a = a % b
a %= b
a = a + 1
a++, ++a
a = a – 1
a--, --a
Table 4.4: shortcuts of expressions
The difference between
a++
and
++a
is the value of the expression itself; at the end, both of

them increment the value of
a
by one, but the value of
a++
when evaluated is the original

value of a, and the value of
++a
is the incremented value. The following example shows the

difference.
int a, b, c;
a = b = c = 1;
a = ++b + c;
System.out.println("a = " + a + ", b = " + b + ", c = " + c);
b = a++ - 1;
System.out.println("a = " + a + ", b = " + b + ", c = " + c);
c = a + a++ + --b + b;
System.out.println("a = " + a + ", b = " + b + ", c = " + c);
If you compile and run the above program, you should see the following output:
a = 3, b = 2, c = 1
a = 4, b = 2, c = 1
a = 5, b = 1, c = 10
Java Lab Manual by Yasser Jaffal (2008)

20
To clearly understand how it works, let's monitor the value of
b
before, during and after the

execution of the statement
a = ++b + c;
. Before the execution, it is clear that b = 1, once the

statement
++b
executed, the value of
b
is incremented by 1, then the rest of expression is evaluated

using the new value of
b
. This happened because we used pre-increment. If we use post-increment,

the value of
b
will also be incremented, but when
b++
itself is evaluated, it gives the old value of
b

before increment, so post increment does not affect the expression in which it is, but the following

expressions.
Boolean variables have different set of unary and binary operations according to the special data

type they store, which is logical. Table
4
.5 shows primary boolean operations.
Operation
Operator
Usage
Logical AND
&&
op1 && op2
Logical AND
&
op1 & op2
Logical OR
||
op1 || op2
Logical OR
|
op1 | op2
Logical NOT
!
!op1
Table
4
.5: logical operations
Discussing the difference between
&&
and
&
, and
|
and
||
, when we use
&&
or
||
,

op2
is not

evaluated when the value of the whole expression could be determined by the value of
op1
and the

operation. For example,
true || false
expression does not evaluate the second operand,

because the logical OR between
true
and any other boolean expression is always
true
, similarly,

false && true
does not evaluate the second operand because logical AND between
false

and any other boolean expression is always
false
.
In addition to these operations, there are also comparison operations which we apply to numerical

variables to get boolean results, table
4
.6 shows comparison operations.
Operation
Operator
Usage
Equals
==
op1 == op2
Greater than
>
op1 > op2
Greater or equals
>=
op1 >= op2
Less than
<
op1 < op2
Less or equals
<=
op1 <= op2
Does not equal
!=
op1 != op2
Table
4
.6: Comparison operations
The following example evaluates some boolean expressions and prints their results.
boolean b1, b2, b3;
b1 = true || false;
b2 = b1 && (5 > 3);
b3 = b2 && (13 == 6);
System.out.println(
"
b1=
"
+ b1 +
"
, b2=
"
+ b2 +
"
, b3=
"
+ b3);
Java Lab Manual by Yasser Jaffal (2008)

21
If you compile and run the above code you should get the following output:
b1=true, b2=true, b3=false
Once again, we have used concatenation to convert the whole output to string, the next section

focuses more on conversion.
4.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, conversion is different from another operation called
casting
,

the following discussion shows the difference between them.
int i; float f; double d;

i = 1;
f = 4.4f;
d = 5.5;
d = i;
i = (int)f;
f = (float)d;

System.out.println("i = " + i + " f = " + f + " d = " + d);
The above code does the following:

Converts the value of
i
to
double
and stores it in
d
. This conversion is done automatically

by the compiler, because
double
data type is normally wider than
int
, there is absolutely

no risk storing
int
in
double
.

In the following two statements, notice that we but a large value into a smaller data type, in

this case, a possible loss of data occurs in which we have to be aware of. Because that,

compiler (by default) refuses to store
float
value in
int
, or
double
in
float
. Because

of that, 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. One of them is a well known method that converts a String to integer which is

Integer.parseInt()
method, the following example shows how to use it.
String s = "115";
int x = Integer.parseInt(s);
x++;
System.out.println(x); //prints 116
Similarly, we can also use
Double.parseDouble()
,
Float.parseFloat()
and

Long.parseLong()
.
A common method among all objects in Java is
toString()
method which converts the object to

a s
tring,
toString()
method will be covered in more details later.
Types of conversion mentioned above are called
explicit
conversion, because we request that

Java Lab Manual by Yasser Jaffal (2008)

22
conversion explicitly, another type of conversion is called
implicit
conversion (promotion), because

it is done automatically without requiring the programmer to request that conversion, for example,

concatenating an integer or a character with a String converts them automatically to a string.
int x = 10;
String s = "x equals " + x;
In the above code, the value of
x
which is 10 is converted from integer to string and concatenated

with the previous string
"x equals "
.
Promotion also occurs when an expression of values from different types is evaluated. In general,

promotion converts all operands to the largest data type among them. The following code shows an

example.
int x = 10;
double d = 12.5;
float f = 1.5f;
double result = (d/f) + x;
System.out.println("The result is " + result);
If you run the above code, you will see the output “The result is 18.33333333”. The expression was

evaluated as the following:
1.
The value of
f
is converted to
double
and
d/f
is evaluated, clearly, the result is of type

double
.
2.
The value of
x
is converted to
double
and added to the previous expression.
3.
The whole expression is evaluated to type
double
And stored in
result
.
4.4 Literal Values and Expressions
It is important to realize that a value of any type can be expressed in different ways, and all

of them are equivalent. The following example shows how to express integer value of 8 in different

ways.
int x = 8;
//literal value
int y = 5 + 3;
//Constant expression
int z = Integer.parseInt("8");
//Method return type
int w = (x + y) / 2;
//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. For example,

assigning
8
directly to an integer,
'a'
directly to a character or
"Hello"
directly to a

string.
Expression:
expressions are evaluated in runtime to generate a single value, for example,

the expression
1 + 3 – 5
evaluate at runtime and generate a final value of
-1
.
Methods:
Some methods returns a value of certain type, one of them is the previously

discussed
parseInteger()

method which returns an integer generated from some string.
Java Lab Manual by Yasser Jaffal (2008)

23
Exercises
1.
Assuming that
a = 3, b = 5, c = 1, x = 2, y = -2,
and
z = 6
and

following precedence rules. Evaluate each expression of the following
independently
and

mention any changes in the variable values after expression is evaluated (all variables are

integers):

(a / c) + z / a

c++ + b / x – y

x + ++x * x--

--a * ++a – (z++ * z++)

(true && (5 > 7)) || ((3 <= 10) && !false))

(3 < 6) || (c++ == x)
2.
Write a program that evaluates all the expressions in exercise 1 and prints the result on the

screen.
3.
Write a program that calculates
a + b + c + d
and prints the result on the screen

where:

a, b, c
and
d
are integers.

a
is assigned a literal value of 3.

b
is assigned a value of 6 using an arithmetic expression of 3 literal values.

c
is assigned a value of 2 generated from an expression of
a
and
b
.

d
is assigned a value of 4 converted from a string using
parseInt()
method.

The result is printed directly without defining a new variable to store the result.
Lab Extras
Some variables are declared using
final
keyword,
final
means that the value remains

constant at the time of execution and it is assigned during compile time. The value of a final

variable cannot be modified once it is assigned. The final keyword is used before specifying data

type in variable declaration.
final int MAX_VALUE = 100;
It is important to realize that you can assign a value to a final variable only once. You can only

assign the value in the same statement in which you define the variable, so the following statements

are invalid.
final int MAX_VALUE;
MAX_VALUE = 100;
//Error
As you can see, the naming convention of final variables is to use upper letters and underscores "_".
Java Lab Manual by Yasser Jaffal (2008)

24
Session 5
Working with Java Applets
Objectives:

Writing and compiling Applets.

Embedding Applets into web pages.
5.1 Idea of Applets
So far, we can claim that our Java applications are
console

applications
, because the run mainly on

console (command prompt in Windows, shell in Unix).
Applets are something different, from the context in which they run. In general, Applets are Java

programs that are written with
*.java
file extension and compiled using
javac
command, but

they are different from another perspective:

You cannot run Applets using
java
command.

Applets have no
main(String[] args)
method, instead, there is a method called

init()
.

To run an Applet, you have to embed it in a HTML page using special tag.

Applets are graphical, not command-line applications.
5.2 Writing and Compiling Applets
Applets are written in ordinary Java source files that has the name of the class inside it. The

following code shows a simple example (read comments carefully).
//These two classes are necessary, so we
//need to import them from the libraries
import java.awt.Graphics;
import java.applet.Applet;
//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,25);
}
//We use this code to draw on the applet
public void paint(Graphics g){
//Drawing text on the specified point
g.drawString("Hello world!", 50, 25);
}
}
Java Lab Manual by Yasser Jaffal (2008)

25
There are some important notes about writing Applet code:

We use
import
keyword to get classes from libraries into our source files.

Class should be declared using
public
keyword, this enables access to it from web

browsers.

To let Java deal with this class as Applet, add
extends Applet
to class declaration.

Applets have two important methods:

init()
method: This method is like
main(String[] args)
method in Java

applications, the Applet starts execution from this method.

paint(Graphics g)
method: This method is dedicated for painting on the Applet,

the variable
g
(called
object
) has a lot of drawing methods like
drawString()
,

drawLine()
,
drawOval()
and so on. We will discuss them in details later.
After writing the class, we compile it as usually with
javac
command. To run the applet, we need

to put it inside HTML page. The following section discusses this task.
5.3 Embedding Applets into HTML
After compiling the code in section 5.2, you get a file called
HelloApplet.class
. To run this

file, create an HTML page (in the same folder) and add the following HTML code in it.
<html>
<body>

<applet code="HelloApplet" width=400 height=200></applet>
</body>
</html>
The highlighted part is the most important tag in out page,
<applet>
tag tells the browser where

to add the Applet,
code
property specifies the name of the class from which the Applet should be

loaded. Saying it again, the name of the
class
, not the name of the
file
, so don't add the extension

.class to the name.
When you open the web page, and everything is alright, you'll get the result shown in figure 5.1

below.
Figure 5.1: Hello World Applet
Java Lab Manual by Yasser Jaffal (2008)

26
Notice that our Applet does nothing except drawing the text “Hello World” at the point (50, 25) of

the frame. To see exactly where this point is located, we have to understand the coordinations of the

Applet. Have a look at figure 5.2 below.
Figure 5.2: Coordinations of Applet
As you can see, the upper-left corner has the coordinates (0, 0). The value of x increases from left to

right, and the value of y increases from up to down. So to locate the point (50, 25), start from the

upper-left corner and take 50 pixels to right then 25 pixels downward. To get the width of the whole

Applet, call
getWidth()
method, to get the height of the whole Applet, call
getHeight()

method.
Exercises
1.
Write the HelloApplet class and compile it.
2.
Create a web page to run HelloApplet.
3.
Create a new folder in your public_html folder on Webdisk named lab2 and upload

HelloApplet.class and the web page into it.
4.
Run your Applet from the web.
Java Lab Manual by Yasser Jaffal (2008)

27
(0, 0)
x+
y+
(getWidth(),
getHeight())
(50, 25)
Session 6
Conditional Statements and User Input
Objectives

Introducing the logic of
if
and
if-else
statements.

Reading user input.

Making decisions based on user input.

Using
switch-case
statement to make decisions based on some value.
6.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. The statements in by which we make this decision are called
conditional

statements
.
Choices are made by one or more conditions being satisfied or not, we express those conditions by

boolean expressions, that is, if the result of the boolean condition is true then the condition is met

and the appropriate action(s) is made.
We use
if
statement to determine whither the condition is me or not. The format of
if
statement is

as follows:
if(
condition
){
//statement(s) to be executed if the condition is true
}
For example, we can check whether some value is positive or negative:
int x = 5;
if(x > 0){
System.out.println("x is positive");
}
else{
System.out.println("x is negative");
}
Notice that we use
else
block to enclose statements that we want to perform if the condition is

NOT met. The problem of the above statement is that
0
is considered negative. To solve this

problem, we can use
>=
operator instead of
>
, but if we wish to detect 0 itself, we can use
nested

if
statement inside the block of
else
as follows:
int x = 5;
if(x > 0){
System.out.println("x is positive");
}
else{
if(x == 0){
System.out.println("x is zero");
}
Java Lab Manual by Yasser Jaffal (2008)

28
else{
System.out.println("x is negative");
}
}
Using technique like on in the above example may make the code more complex and harder to

understand, instead, we can use
else-if
statement, by which we can check unlimited number of

condition, and making decision for each one separately. The format of if-else statement is the

following:
int x = 5;
if(x > 0){
System.out.println("x is positive");
}
else if(x < 0){
System.out.println("x is negative");
}
else if(x == 0){
System.out.println("x is zero");
}
Using else before each if statement means that if one of the conditions is met no other condition will

be checked.
6.2 Reading User Input
You can read input from the user using
BufferedReader
class in this way:
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String input = in.readLine();
Before using
BufferedReader
, be sure to
import
the library which contain this class, this library

is called
java.io
, in order to import it, we use
import
statement as follows.
import java.io.*;
By using character
*
here we identify that we import all classes in this library. import statements

are used before class definition.
To use
BufferedReader
class, you need to deal with the exception it throws through

readLine()
method which is
IOException
, for instance, we will do this by changing the

definition of
main()
method to throw that exception.
public static void main(String[] args) throws IOException{
Butting it all together, a simple program that reads user name and prints it on screen.
Java Lab Manual by Yasser Jaffal (2008)

29
import java.io.*;
class ReadFromUser{
public static void main(String[] args)
throws IOException{
String userName;
BufferedReader in;
in = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter your name: ");
userName = in.readLine();
System.out.println("Welcome " + userName);
}
}
The above code asks the user to enter his name, reads the input using
readLine()
method which

returns a String value that represents user input from keyboard, then concatenates it with

"Welcome" and prints it on the screen.
6.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. For instance, we will write a program that uses if-else to determine that the

number provided by user is positive, negative or zero, as well as determining whether the number is

odd or even.
import java.io.*;
class Numbers{
public static void main(String[] args)
throws IOException{
BufferedReader in;
in = new BufferedReader(
new InputStreamReader(System.in));
int x;
String userInput;
System.out.print("Enter a number: ");
userInput = in.readLine();
x = Integer.parseInt(userInput);
if(x == 0){
System.out.println("zero");
}
//x is positive
else if(x > 0){
Java Lab Manual by Yasser Jaffal (2008)

30
//x is even
if(x % 2 == 0){
System.out.println("positive and even");
}
//x is odd
else{
System.out.println("positive and odd");
}
}
//x is negative
else{
//x is even
if(x % 2 == 0){
System.out.println("negative and even");
}
//x is odd
else{
System.out.println("negative and odd");
}
}
}//end of main()
}//end of class
As you can see, we converted the String we read from user to integer because it is easier to

compare, another reason may lead us to this conversion, is that
switch-case
statement accepts

only integers and numerical values or characters, and it cannot accept strings. The following section

covers
switch-case
statement.
6.4
switch-case
Statement
This statement is a special type of decision making techniques, it makes choice among

several options based on a numerical value. The format of
switch-case
statement is the

following:
switch(
variable
){
case
value_1
:
//Statement(s) to be executed if
//variable = value_1
break;
case
value_2
:
//Statement(s) to be executed if
//variable = value_2
break;
.
.
.
case
value_n
:
Java Lab Manual by Yasser Jaffal (2008)

31
//Statement(s) to be executed if
//variable = value_n
break;
}
As you can see, we put some variable in
switch
then follow it by several
case
blocks. Execution

goes through cases one by one comparing each one with the value of the variable specified in

switch
statement, then executes it and all cases that follows, unless we use
break
keyword to

avoid the execution from expanding to unwanted statements. The following example shows how to

use
switch-case
statement.
import java.io.*;
class SwitchCaseDemo{
public static void main(String[] args)
throws IOException{
BufferedReader in;
in = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("1. Print your name");
System.out.println("2. Print your age");
System.out.println("3. Exit");
int choice;
choice = Integer.parseInt(in.readLine());
switch(choice){
case 1:
System.out.print("Enter your name: ");
String name = in.readLine();
System.out.println("Welcome " + name");
break;
case 2:
System.out.print("Enter your age: ");
String age = in.readLine();
System.out.println("You are " + age);
break;
case 3:
System.exit(0);
}//End switch
}//End main
}//End class
The following code shows how cases are executed, the following program enters all cases.
Java Lab Manual by Yasser Jaffal (2008)

32
int x = 1;
switch(x){
case 1: System.out.println("x = 1");
case 2: System.out.println("x = 2");
case 3: System.out.println("x = 3");
}
You can notice that the value of
x
meets the first case only, but all three cases are executed, this

states that
switch-case
statement does not automatically exit after one a case value is met. So

the output of the previous code is the following:
x = 1
x = 2
x = 3
To prevent such behavior, use
break
statement after the end of each case, which exits the whole

switch
block.
A special case that is executed without checking the value of the variable is called default case, we

use
default
keyword instead of
case
keyword to specify the default case. Because we usually

use
break
after each case, default block is executed when the value of the variable did not match

any of specified cases value. To see how this works, add a default case to our previous

SwitchCaseDemo
class (shown in boldface) and try to enter any value other than 1, 2 and 3.
switch(choice){
case 1:
System.out.print("Enter your name: ");
String name = in.readLine();
System.out.println("Welcome " + name");
break;
case 2:
System.out.print("Enter your age: ");
String age = in.readLine();
System.out.println("You are " + age);
break;
case 3:
System.exit(0);
default:
//User did not enter 1, 2 or 3
System.out.println("Invalid choice");
}//End switch
Java Lab Manual by Yasser Jaffal (2008)

33
Exercises
1.
Write a program that specifies whether a given number (x) falls in one of the following

categories (give x a value from the code, don't read from user):

0 to 9

10 to 19

20 to 29

None of the categories
For example, if x = 5, program should print
"0 to 10"
, and if x = 44 it should print

"None".
Hint: use
if
statements with boolean expressions combined using
&&
.
2.
Write a program that reads two integers and prints their sum like the code below (text shown

in boldface is supposed to be user input).
Enter the first number:
3
Enter the second number:
4
2.
The sum is 7
3.
Write a program that asks the user to enter two numerical values (integers) and then select

an operation (addition, subtraction, multiplication and division) then prints the result based

on operation selected. The code below shows examples of the output (text shown in

boldface is supposed to be user input).
Enter first number:
4
Enter second number:
2
1. Addition (+).
2. Subtraction (-).
3. Multiplication (*).
4. Division (/).
Enter operation number:
3
The result is 8
Lab Extras
There is an easier way to read from user, which depends on showing a dialog box for the

user and let him enter his input in a text box inside that dialog. To use this input dialog we import

the library called
javax.swing
, this library contains classes that deal with GUI. What we

interested in among the classes of this library is a class called
JOptionPane
and a method inside

it called
showInputDialog()
. The following example shows how to use this technique to read

from user.
import javax.swing.*;
class EasyRead{
Java Lab Manual by Yasser Jaffal (2008)

34
public static void main(String[] args){
String userInput;
userInput = JoptionPane.showInputDialog("your name: ");
System.out.println("Hello " + userInput + " !");
}
}
You can notice here that we do not declare any objects and no exceptions to throw. An easy and

straight forward method. The output of the above code is a dialog box like the image 7.1.
If user clicks OK the input is read and returned as String, if he click Cancel dialog box closes

without returning any input entered.
Image 6.1: Input Dialog
Java Lab Manual by Yasser Jaffal (2008)

35
Session 7
Decision-Tree Applet
Objectives:

Adding user controls to Applets.

Handling events of user controls.

Reading and writing values to user controls.

Including external packages.
7.1 Adding User Controls to Applets
So far, we have been creating Applets that do nothing but drawing text on the screen. Well, applets

can do more. The main objective of Applets is to provide a dynamic user interface on the web, so it

is reasonable to start learning how to add user controls (buttons, text fields, ..., etc) to the Applet.
Adding user controls is a simple yet relatively long process, to summarize, it involves the following

steps:
1.
Importing the library in which they are located (
java.awt
).
2.
Declaring user controls variables (or objects).
3.
Initializing the controls.
4.
Adding the controls to the Applet.
5.
Handling controls events.
For now, lets focus on the first four steps and leave step 5 to the next section. Lets now discuss

these steps in details. Importing the library is achieved by using
import
statement followed by

library name and class name. To import all classes in a library, we use *. The following code shows

the necessary
import
statement.
import java.awt.*;
The second step is to declare the controls variables. These controls have data types just like

primitive data types discussed in session 3 but their initialization is slightly different. For example,

if we want to add a button and a text field to our Applet, we use code like the following.
Button b;
TextField t;
Notice that these types start with upper-case letter, unlike primitive data types. It is important to

realize that you need to declare these variables outside
init()
, in other words, they should be

declared directly inside the class body.
Up to now, we have just
declared
these controls, this means that we have reserved the variables

names for them, but they does not actually exist. The initialization step is the one which makes

them really exist. It is advisable that you initialize these controls at the beginning of
init()

method.
Java Lab Manual by Yasser Jaffal (2008)

36
public void init(){
b = new Button("Click Me!");
t = new TextField("Type in me!");
}
As the above code shows, we use the
new
keyword to initialize the controls. The statement that

follows
new
keyword is a call to the
constructor
, which is a special type of methods written

specifically to initialize objects. Don't bother yourself with it now.
The string we pass to
Button
constructor is the text we want to appear on it. Similarly, the text we

pass to
TextField
constructor is the default text that will appear in it.
We have now declared and initialized controls, the step left is to add these controls to the Applet.

Although these controls are declared inside Applet's class, they are not graphically added hence not

yet visible to the user. To make them visible, we add them to the Applet using
add()
method.

Code below shows a full example.
//Step 1: import
import java.awt.*;
import java.applet.Applet;
public class SimpleApplet extends Applet{
//Step 2: declare controls
Button b1, b2;
TextField tf;
public void init(){
//Step 3: initialize controls
b1 = new Button(
"Button 1");
b2 = new Button("Button 2");
tf = new TextField("Type something");
//Step 4: add controls (adding order affects appearance)
add(b1);
add(tf);
add(b2);
}
}
If you compile and run the above Applet, you'll get something like this (figure 7.1).
Figure 7.1: Simple Applet
Java Lab Manual by Yasser Jaffal (2008)

37
7.2 Handling Events of User Controls
The last thing remained in this session is to add some functionality to these controls, at the end,

there is no point in adding buttons that do nothing and text fields we are not able to read/write to.
First step of adding this functionality is to import the necessary library, which is

java.awt.event
.
import java.awt.event.*;
Next, we need to alter the definition of our class, in addition to being Applet, our class should now

serve as
ActionListener
, that is, being able to handle actions raised by controls (mainly

buttons). So the definition of the class will be the following.
public class MyApp extends Applet
implements ActionListener
Notice the addition (
implements ActionListener
) at the end of the class definition. This

addition requires you to write a new method called
actionPerformed()
.
public void actionPerformed(ActionEvent e){
}
One thing left, letting the current Applet be the event handler for buttons we have added, this is

achieve by calling
addActionListener()
from button's object.
//Assume that Button b is already defined...
b.addActionListener(this);
Your Applet is ready now for event handling, but how? When user clicks on a button, the method

actionPerformed()
is executed. The following code shows how can you decide which button

was clicked (modified version of
SimpleApplet
). Modifications are shown in boldface.
//Step 1: import
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class SimpleApplet extends Applet
implements

ActionListener
{
//Step 2: declare controls
Button b1, b2;
TextField tf;
public void init(){
//Step 3: initialize controls
b1 = new Button(
"Button 1");
b2 = new Button("Button 2");
tf = new TextField("Type something");
//Step 4: add controls (adding order affects appearance)
add(b1);
add(tf);
Java Lab Manual by Yasser Jaffal (2008)

38
add(b2);

//Step 5: add action listener

b1.addActionListener(this);
b2.addActionListener(this);
}
//This method will run when buttons are clicked.

public void actionPerformed(ActionEvent e){
Object cause = e.getSource();
if(cause == b1){
tf.setText("Button 1 Was Clicked");
}
else if(cause == b2){
tf.setText("Button 2 Was Clicked");
}
}
}
Code inside
actionPerformed()
method needs some explanation, we call
e.getSource()

to know which button was clicked, then store it in
cause
. Then we compare
cause
which all

buttons we have to find out which button was clicked in order to perform the appropriate action.
To change the value displayed in the text field, call
setText()
method and pass a
String

representing text you want to appear in it. To read the text typed in the text field call its

getText()
method.
String valueOfTextField = tf.getString();
You can also use a control name
Label
to add text labels to the Applet.
Label l = new Label("Some text");
add(l);
7.3 Applets with NetBeans
NetBeans facilitates developing Java Applets by using
applet viewer
tool, this tool can run your

Applet without the need of creating HTML page.
To do the exercises at the end of this session, you need to add an external library that is not present

in JDK, this library is called
ModelAwb.jar
and can be downloaded from the following link

http://mail.alquds.edu/~f3576/102/resources/ModelAwb.jar
.
After downloading the file, you have to add it to your NetBeans project, to do this, follow the

following steps:
1.
Expand your project tree from project explorer (on the left).
2.
Right-click libraries node and select “Add JAR/Folder”
3.
Browse for
ModelAwb.jar
file, select it and click “Open”.
4.
You can now use the statement
import awb.*;
Java Lab Manual by Yasser Jaffal (2008)

39
Exercises
1.
Write a calculator Applet that has two int fields (Use
awb.IntField
class), named

register
and
accumulator
, and four buttons named
setReg, setAccum, add

and
power
. The behavior of these buttons should be as the following:
Button
Job
Set Reg
Sets register int field to 0
Set Accum
Sets accumulator int field to 0
Add
Sums the values in register and

accumulator and leaves the result in

accumulator
Power
Raises accumulator value to the power

of the value of register leaving the result

in accumulator
Your Applet should look like figure 7.2.
Figure 7.2: Exercise 1
Lab Extras
You can specify the width of text field by providing the number of columns in the constructor. For

example, the following code creates a text field with 20 columns width.
TextField t = new TextField(20);
TextArea a = new TextArea(20, 20; //Text field with multiple lines
Java Lab Manual by Yasser Jaffal (2008)

40
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
int x = 0;
while(x != 0){
System.out.println(x);
}
//do-while
int x = 0;
do{
System.out.println(x);
}while(x != 0);
Output:
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.