Java Programming - People at Creighton University

advertisement
Java Programming
Report by
Rohit Moza
Spring 2002
Dr Prem Nair
Table of Content
INTRODUCTION _______________________________________ 2
1. A FIRST PROGRAM – HELLO JAVA _____________________ 3
2. METHODS, CLASSES AND OBJECTS __________________ 19
3. ADVANCED OBJECT CONCEPTS______________________ 29
4. INPUT SELECTION AND REPETITION __________________ 38
5. ARRAYS, VECTORS AND STRINGS ____________________ 49
6. FILE INPUT AND OUTPUT ____________________________ 54
7. APPLETS __________________________________________ 65
8. EXCEPTION HANDLING ______________________________ 73
REFERENCES ________________________________________ 80
Page 1
Java Programming - Spring 2002
Introduction
The Java programming language was developed at Sun Microsystems under the
guidance of Net luminaries James Gosling and Bill Joy. It is an object-oriented language
that is used both for general-purpose business programs and interactive World Wide
Web - based Internet programs. The Java programming language is designed to be
machine-independent and safe enough to traverse networks while powerful enough to
replace native executable code. This language is also simpler to use then many other
object-oriented languages.
The Java programming language is both a compiled and an interpreted language. Java
source code is converted into simple binary instructions, similar to ordinary
microprocessor machine code. So the Java source is compiled into Java Virtual Machine
code called bytecode, also called J-code .The compiled byte code is then interpreted on
the machine where the program is executed. A compiled program will run on any
machine that has a Java programming language interpreter.
Java is modeled after C++. It is similar to C++ but only at a superficial level. Although the
basic syntax of Java looks a lot like C or C++ it, in fact, has more in common with
languages like Smalltalk and Lisp.
Page 2
Java Programming - Spring 2002
1. A First Program – Hello Java
Creating a Program
The following is a simple program to print “Hello Java” on the screen.
public class HelloJava
{
public static void main(String[ ]
args)
{
System.out.println(“Hello Java”);
//prints Hello Java
}
}
Example 1.1: A first Java program
This example public class HelloJava defines a class named HelloJava.
Classes are the fundamental building blocks of most object-oriented languages.
Everything that you use within a Java program must be part of a class. A Java class can
be defined using any name or identifier subject to the following requirements:

A class name must begin with a letter, an underscore, or a dollar sign.

A class name can contain letters digits underscores or dollar signs.

A class name cannot be a Java reserved word keyword. For example Boolean,
double, float, future, void, private, public, class, etc.

A class cannot be named as true, false or null.
Page 3
Java Programming - Spring 2002
As a standard rule class names in Java begin with an upper case letter and employ
other upper case letters for easy readability.
In the line public class HelloJava the reserved word public is an access
modifier. Public access is the most liberal type of access.
A class can contain many methods. The example 1.1 above contains a special method
called main() that all Java applications must include. The main() method is an entry
point of an application. This method is run when the application first starts.
public static void main(String[ ] args) is the method header for the
main() method. The keyword public is an access modifier, as above. Static is the
reserved keyword that indicates that every member created for the HelloJava class
will have an identical, unchanging main() method. The keyword void indicates that the
main() method does not return any value when it is called. (String[] args)
represent an argument passed to the main() method. String represents a Java
class that can be used to represent character strings. args is an identifier that is used
to hold any Strings that might be sent to the main method. The identifier can also be
named any other legal Java identifier. Although in the example the main() method
does not actually use the args identifier, it must be placed within the main() method’s
parentheses.
In this example the next statement System.out.println(“Hello Java”);
performs the task to give us the output “Hello Java”. Here the method is
println() to which “Hello Java” is being passed. The println() method
prints a line of output on the screen and places the cursor on the following line. In the
statement System is a class that defines the attributes of a collection of similar
“system” objects. out is a system object that represents the screen. “Hello
Java” is a literal string of characters that will appear on the screen exactly as it is. Any
literal string in Java should be placed between double quotation marks “ ”.
Page 4
Java Programming - Spring 2002
//prints Hello Java is a program comment. In Java comments can be of three
types. Line comments that start with two forward slashes (//), Block comments that start
with a forward slash and an asterisk (/*) and end with an asterisk and a forward slash
(*/), and javadoc comments that begin with a forward slash and two asterisks (/**) and
end with an asterisk and a forward slash (*/).
How to run a Java program
1.
Write your program in any text editor, such as Notepad or WordPad.
2.
Save the program as classname.java (the program in example 1.1 would be
saved as HelloJava.java) The file extension should be .java so that the
compiler will recognize the program. You must remember that Java is case
sensitive and so the class name should exactly match the saved file name. The
file should be saved in the bin folder of jdk directory.
3.
To compile and run the program go to MS-DOS. Change directory to jdk bin
folder by using the command cd c:\jdk1.3\bin and press the enter key
(assuming you are using jdk 1.3).
4.
Now compile the program by typing javac filename.java and press the
enter key (the program in example 1.1 would be compiled by typing javac
HelloJava.java)
5.
To interpret and execute the class type the command java filename. (In the
program in example 1.1 we would type java HelloJava ).
6.
Your output should look like Figure 1.1
Page 5
Java Programming - Spring 2002
Output for Example 1.1
Using Data
Variables and Constants
Data can be categorized as variable or constant. Constant data cannot be changed
after a program is compiled. For example, if you include the statement
System.out.println(200); in your program, the number 200 is a constant and
every time the program is executed the value 200 will print.
Variable data however may change, for example, if you create a variable named
employeeSalary and include the statement
System.out.println(employeeSalary); in your program, the output may vary
every time the program is executed depending on what value is stored in the
employeeSalary each time the program is run.
Data Types
Java provides eight types of data: boolean, byte, char, double, float, int,
long, short. These are called primitive types because they are not complex.
Page 6
Java Programming - Spring 2002
A variable cannot be any Java reserved keyword and must always start with a letter. All
variables must be declared appropriately by including the following:

Data type – to identify what types of data will be stored by the variable

Identifier – name of the variable

Assigned value – needed only if the variables needs an initial value

Semicolon – to end the declaration.
An example of variable declaration is int employeeSalary = 200;
Here int is the variable type, employeeSalary is the variable name, the ‘=’ sign is
the assignment operator, and 200 is the initial value assigned to the variable.
An assignment made when the variable is declared is called initialization (as in the
example above). However if the assignment is made later in the program it is called
assignment. An assignment to assign a new value may be done with the statement
employeeSalary = 300;
Variables can be declared one at a time with separate statements, or multiple variable of
the same type can be declared in a single statement separating the declaration with a
comma. For example:
int employeeSalary = 200;
int employeeHours = 30;
int employeeSalary = 200, employeeHours = 30 ;
Variables of different types should be declared in separate statements, for example,
int employeeSalary, employeeHours ;
float totalSalary;
Page 7
Java Programming - Spring 2002
int
int in Java is the variable type to store integers. It has a size of 4 bytes. Byte, short and
long are variations of the integer type. Byte and small are used to hold small values and
long is used to hold large value.
The following figure shows the minimum and maximum value limits on integer values
according to their types.
Type
Minimum
Maximum
Bit Size
Byte
-128
128
1
Short
-32768
32768
2
Int
-2147483648
2147483648
4
Long
-9223372036854775808
9223372036854775808
8
Figure 1.1
If the value assigned is too large for the variable data type, you will get an error message
from the compiler and the program will not execute. If the variable data types is larger
than needed you will waste memory.
public class showVariables
{
public static void main(String[] args)
{
int anInt = 55;
System.out.print("The int is ");
System.out.println(anInt);
Page 8
Java Programming - Spring 2002
}
}
Example 1.2: Declaring a variable
Output for Example 1.2
public class showVariables1
{
public static void main(String[ ] args)
{
int anInt = 315;
long aLong = 12345678987456L;
short aShort = 23;
System.out.print(“The int is ”);
System.out.println(anInt);
System.out.print(“The long is ”);
System.out.println(aLong);
System.out.print(“The short is ”);
System.out.println(aShort);
Page 9
Java Programming - Spring 2002
}
}
Example 1.3: Declaring multiple variables
Output for Example 1.3
public class showVariables2
{
public static void main(String[] args)
{
int anInt = 315;
long aLong = 12345678987456L;
short aShort = 23;
System.out.println(“The int is ” + anInt);
System.out.println(“The long is ” + aLong);
System.out.println(“The short is ” + aShort);
}
}
Example 1.4: Change the two print statements into one
Page 10
Java Programming - Spring 2002
Output for Example 1.4
Arithmetic Statements
In the Java programming language there are five main arithmetic operators for integers,
as shown below.
Operator
Description
Example
+
Addition
3+2, the answer is 5
-
Subtraction
3-2, the answer is 1
*
Multiplication
3*2, the answer is 6
/
Division
3/2, the answer is 1
%
Modulus (remainder)
3%2, the answer is 1
Figure 1.2
In division, any fractional part of the result is lost. For example, 7/2 is equal to 3,
instead of 3.5.
Page 11
Java Programming - Spring 2002
In modulus, the result is the value of the remainder after division takes place. For
example, 7%2 is equal to 1, because 2 goes into 7 three times with a remainder of 1.
Modulus can be used only with integers unlike the other four operators that can also be
used with floating-point data. The example 1.5 below shows arithmetic statements.
public class showVariables3
{
public static void main(String[ ] args)
{
int value1 = 40, value2 = 10, sum, difference, product,
quotient,
modulus;
sum = value1 + value2;
difference = value1 – value2;
product =
value1 * value2;
quotient = value1 /
value2;
modulus = value1 % value2;
System.out.println(“Sum is
” + sum);
System.out.println(“Difference is
System.out.println(“Product is
System.out.println(“Quotient is
System.out.println(“Modulus is
” + difference);
” + product);
” + quotient);
” + modulus);
}
}
Example 1.5: Program wit arithmetic statements
Page 12
Java Programming - Spring 2002
Output for Example 1.5
Operator Precedence
Multiplication, division, and modulus always take place before addition or subtraction in
any expression.
2 + 3 * 4
= 14, here the multiplication 3 * 4 takes place before the addition of 2.
Operator precedence can be overridden by putting the operation to perform first in
parentheses.
(2 + 3)
* 4 = 20, here the addition within the parentheses takes place first, and
then the multiplication by 4.
boolean
A Boolean data type can hold only one of two values, either true or false. For example,
boolean greaterNumber = false;
boolean smallerNumber = true;
In the Java programming language there are five comparison operators for integers, as
shown below.
Page 13
Java Programming - Spring 2002
Operator
Description
Example
<
Less than
1<2
>
Greater than
2>1
==
Equal to
2 == 2
<=
Less than or equal to
2 <= 2
>=
Greater than or equal to
2>=1
!=
Not equal to
2 != 1
Figure 1.3
Comparison operators that have two symbols (==, <=, >=, ! = ) should not have any
white space placed between the two symbols.
Values can be assigned based on the results of comparisons to boolean variables for
example.
boolean highSalary = (hourRate > 30);
In the above statement, the variable hourRate is compared to a constant value of 30.
If the variable hourRate is greater than 30, then the expression evaluates to true. If
the variable hourRate is less than 30, then the expression evaluates to false.
Floating-point Data types
Page 14
Java Programming - Spring 2002
In the Java programming language there are two floating-point data types: float and
double.
Type
Minimum
Maximum
Size (Bytes)
Float
-3.4 * 1038
3.4 * 1038
4
Double
-1.7 * 10308
1.7 * 10308
8
Figure 1.4
A float data type can hold values up to 6 or 7 significant digits of accuracy. For
example, a float with the value 0.123456789 will display as 0.123456.
A double data type can hold values up to 14 or 15 significant digits of accuracy. For
example, a double with the value 0.12345678901234567890 will display as
0.123456789012345.
A floating number constant such as 15.45 is a double by default. You can also store a
value explicitly as a float or a double. For a float, you can type either a lower
case or an upper case F after the number. For example, 15.45F. For a double, you
can type either a lower case or an upper case D after the number. For example, 15.45D.
All arithmetic operation can be performed with floating point numbers, except for
modulus operations.
Page 15
Java Programming - Spring 2002
public class showVariables4
{
public static void main(String[] args)
{
double numOne = 31.5, numTwo = 2.5, result;
result = numOne + numTwo;
System.out.println(“The sum is
” + result);
result = numOne * numTwo;
System.out.println(“The product is
” + result);
}
}
Example 1.6: Floating point data types
Output for Example 1.6
char
char data type is used to hold characters. The character value(s) is placed within single
quotation marks, for example:
char firstLetter = ‘R’;
char firstNum = ‘9’;
char firstSign = ‘%’;
Page 16
Java Programming - Spring 2002
A variable of type char can hold only one character. A data structure called a string
is used to store a string of characters, such as your name. However, string constants
are placed between double quotation marks. For example,
string myName = “John”;
In a char variable you can store any character using an escape sequence, which
always begins with a back slash (\). Some common escape sequences used in the Java
programming language are shown below.
Escape Sequence
Description
\b
Backspace
\t
Tab
\n
New line or line feed
\f
Form feed
\r
Carriage return
\”
Double quotation mark
\’
Single quotation mark
\\
Back slash
Figure 1.5
Page 17
Java Programming - Spring 2002
public class EscapeChar
{
public static void main(String[] args)
{
System.out.println(“\nThis is one line.\n This is
another.”);
System.out.println(“This shows\thow\ttabs\twork.”);
}
}
Example 1.7: Escape sequence
Output for Example 1.7
Page 18
Java Programming - Spring 2002
2. Methods, Classes and Objects
Methods
A class can contain an unlimited number of methods. A method is a series of statements
that carry out a task. A method must include the following:
-
A declaration (or header or definition)
-
An opening curly bracket
-
A body
-
A closing curly bracket
A method declaration must contain the following:
-
Optional access modifiers
-
The return type for the method
-
The method name
-
An opening parenthesis
-
An optional list of method arguments, separated by commas
-
A closing parenthesis
The following example 2.1 is a program using a method.
Page 19
Java Programming - Spring 2002
public class UseMethod
{
public static void main(String[] args)
{
LineNumbers ( );
System.out.println(“This is the last line.”);
}
public static void LineNumbers ( )
{
System.out.println(“This is the first line”);
System.out.println(“This is the second line”);
}
}
Example 2.1: UseMethod class calling LineNumber ( ) method
Output for example 2.1
In the above example, when the compiler reads the statement LineNumbers (), in
the main () method, it will call the method public static void
LineNumbers () and print its output.
The advantage of method(s) is that they are reusable, that is, you can use the method in
any program that needs it. For example, if you want to use the method
Page 20
Java Programming - Spring 2002
LineNumbers() in another program, you simply have to include the statement
LineNumbers() in the program. If you want to use the method in a different class you
need to write it as UseMethod.LineNumbers (); or the compiler will not
recognize it. This statement will tell the compiler that the method LineNumbers () is
in another class called UseMethod, as shown in the example below.
public class UseMethod2
{
public static void main(String[] args)
{
UseMethod.LineNumbers ( );
System.out.println(“This is the last line.”);
}
}
Example 2.2: UseMethod2 class calling LineNumber ( ) method from the class UseMethod.
Output for Example 2.2
Two different classes can have methods of the same name. Such a method in the
second class would be entirely distinct from the method with the same name in the first
class.
Page 21
Java Programming - Spring 2002
Methods and Arguments
Arguments are communications you send to a method. A method may require a single
argument or multiple arguments.
The method declaration for a method that can receive an argument needs to have the
type of argument and a local name for the argument included within the method
declaration parentheses.
public void salaryCalculation(double hoursWorked)
{
double totalSalary;
totalSalary = hoursWorked * 8.65;
System.out.println (“The total salary is ” + totalSalary);
}
Example 2.3: The salaryCalculation() method receiving an argument
In example 2.3, the argument is double hoursWorked within the parentheses and it
indicates that the salaryCalculation() method will receive a value of type double
and this value will be known as hoursWorked within the method. Thus, the variable
hoursWorked is a local variable to the salaryCalculation() method. The
salaryCalculation() method is a void method because it does not return any
value to any class that uses it.
A method, within a program, can be called by using either a constant value or a variable
as an argument. For example:
salaryCalculation (167);
salaryCalculation (monthly Salary);
Page 22
Java Programming - Spring 2002
Further, a method can be called any number of times in a program. Example 2.4 shows
a program that uses the same method twice.
public class UseMethodTwice
{
public static void main(String[] args)
{
double johnSalary = 100;
System.out.println("Salary Calculation");
salaryCalculation(500);
salaryCalculation(johnSalary);
}
public static void salaryCalculation(double hoursWorked)
{
double totalSalary;
totalSalary = hoursWorked * 8.65;
System.out.println ("The total salary is " +
totalSalary);
}
}
Example 2.4: The UseMethodTwice class using the method salaryCalculation ( ) twice.
Output for Example 2.4
Page 23
Java Programming - Spring 2002
If a method requires multiple arguments, you can pass the arguments to the method by
listing them, separated by commas, within the call to the method. The declaration for the
method must list the type for each argument separately, even if the arguments have the
same type. It is important to pass the argument to the method in the right order. Passing
two arguments of the same type (e.g. two doubles) to a method in the wrong order will
result in a logical error. Passing arguments of different types (e.g. a double and a float)
in reverse order will result in a syntax order. Example 2.5 shows the
salaryCalculation() method receiving two arguments
public void salaryCalculationWithBonus
(double hoursWorked, double bonusAmount)
{
double totalSalary;
totalSalary = (hoursWorked * 8.65) + bonusAmount;
System.out.println (“The total salary is ” + totalSalary);
}
Example 2.5: The salaryCalculation() method receiving two arguments
Returning Values in Methods
The return type of methods can be of any type, such as, int, double, float, char,
boolean, etc. A method can also return a class type or a method can simply return
nothing, which means the return type is void.
A method can return a value. For this you need to include the return type in the method
header and a return statement at the end of the method. See example 2.6 below.
Page 24
Java Programming - Spring 2002
public static double salaryCalculation (double hoursWorked)
{
double totalSalary;
totalSalary = hoursWorked * 8.65;
return totalSalary;
}
Example 2.6: The salaryCalculation ( ) method returning a value.
The value returned by a method can be assigned to a variable. For example:
johnsCalculatedSalary = salaryCalculation (johnsHours);
Here the returned value is a double, therefore, it should be assigned to a double
variable.
The returned value can also be displayed directly without being assigned to a variable.
For example:
System.out.println(“John’s salary is ” + salaryCalculation
(johnsHours));
Classes and Objects
Everything around us is an object – people, plants, animals, cars, etc. Every object is a
member of a more general class. So, a person is a member of a class that contains
people, and a plant is a member of a class that contains all plants. An object is an
Page 25
Java Programming - Spring 2002
instance of a class and, as such, a person is an instance of the people class and a plant
is an instance of the plants class.
All objects have attribute - size, shape, color, etc. All objects also exhibit behavior, such
as, ball rolls, baby cries, etc. Different objects can have similar attributes and exhibit
similar behavior. For example, cars, trains and planes have many common
characteristics.
An advantage of a class is its reusability. Objects inherit attributes from classes. A class
of cars would have the same characteristics. So objects have predictable attributes
because they are members of a certain class.
An objects behavior is defined by its methods. Every object that is an instance of a class
is assumed to possess same methods. For example, all cars may have the method
mileageDriven (). Methods require arguments. For example, mileageDriven
(45000).
Creating a Class
A class has three parts
-
An optional access modifier
-
The keyword class
-
Any legal identifier you chose for the name of your class
Following are the access modifiers you can use in Java class: public, private,
protected, friendly, private protected, static and final. Public
class is the most liberal form of access. public access means that if you make a class
and on a later stage you want to develop some more specific classes, than you don’t
have to start from scratch. Each new class can become an extension of the original
class inheriting its data and methods.
Page 26
Java Programming - Spring 2002
private class provides the highest level of security. private access means that no
other classes can access the field values, and only the method of the same class are
allowed to set, get or use the private variables. private access is also called
information hiding and also is an important component of object oriented programs. A
private class’s data can only be changed by class’s own methods.
If you don’t specify any access modifier access becomes friendly, which is a more
liberal form of private access.
Following is the example of how classes are used:
public class Salary
{
private int empHours;
private String firstName;
private String lastName;
private float ratePerHour;
public int getHoursWorked()
{
return empHours;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public float getRate()
Page 27
Java Programming - Spring 2002
{
return ratePerHour;
}
public void setEmpHours(int h)
{
empHours = h;
}
public void setFirstName(String first)
{
firstName = first;
}
public void setLastName(String last)
{
lastName = last;
}
public void setHoursWorked (float hrs)
{
ratePerHour = hrs;
}
}
Example 2.7 : A program using classes
Page 28
Java Programming - Spring 2002
3. Advanced Object Concepts
Class features
Block and scope
The code between the curly bracket within any class or method is known as block. See
example 3.1.
public static void methodWithTwoBlocks
{
// this is block first
int number = 2;
System.out.println(“Number is : ” + number);
{
//this is second block
System.out.println(“Number is accessible here too
: ” + number);
int anotherNumber = 33;
}
//end of block two
}// end of first block
Example 3.1: Block
Page 29
Java Programming - Spring 2002
A block can exist entirely within another block, or entirely outside and separate from
another block. Blocks can never overlap.
If you declare a variable in one program you cannot use it in another, similarly when you
declare a variable in a block you cannot refer that variable outside that block. The
portion of a program where a variable can be referenced is the variable’s scope. A
variable comes into scope when it is declared and goes out of scope at the end of the
block in which it is declared. In the example below the variable number can be
accessed in both the blocks as the second block is within the first one. But if you try to
access the variable anotherNumber from the first block it would not be able to access
it, as anotherNumber is declared in the second block.
public static void methodWithTwoBlocks
{
// this is block first
int number = 2;
System.out.println(“Number is : ” + number);
{
//this is second block
System.out.println(“Number is accessible here too : ” +
number);
// valid statement as the scope of
the
variable goes out with the end of the block
int anotherNumber = 33;
System.out.println(“another Number is : ” +
anotherNumber);
}
//end of block two
Page 30
Java Programming - Spring 2002
System.out.println(“another Number is : ” +
anotherNumber);
// invalid statement as the scope of variable
is only in second block
}
// end of first block
Example 3.2: Two Blocks
The variables in a method can have the same name as long as they are not declared in
the overlapping block and each variable has it’s own declaration. For example:
public static void methodWithTwoBlocks
{
{
// first block
int number = 1;
System.out.println(“Number is : ” + number);
}
{
// second block
int number = 2;
System.out.println(“Number is : ” + number);
}
{
// third block
Page 31
Java Programming - Spring 2002
int number = 3;
System.out.println(“Number is : ” + number);
}
}
Example 3.3: Two blocks with same variable names
You cannot declare the same variable more than once in nested blocks.
public static void methodWithTwoBlocks
{
// first block
int number = 1;
System.out.println(“Number is : ” + number);
int number = 2;
{
// invalid statement
1
// second block
int AnotherNumber = 2;
int number = 2;
//
valid statement
// invalid statement
2
System.out.println(“Number is : ” + number);
}
}
Example 3.4: Two nested blocks with same variable names
Page 32
Java Programming - Spring 2002
The above example would cause an error as the variable number has been declared
twice in the same block. Also, the declaration of variable number in the second block is
invalid, as the scope of first variable number has not ended.
If you declare a variable within a class, and use the same variable name within a method
of the class, then the variable used inside the method takes precedence, or overrides,
the first variable. For example:
public static void methodWithTwoBlocks
{
private int number = 100;
public void
inMethod()
{
int
number = 200;
//
overrides the previous
value
System.out.println(“inside method value = ” +
number)
}
System.out.println(“outside method value = ” + number)
}
Example 3.5: Two blocks - Variable in method overrides first variable
Method Overloading
Method overloading is the ability to define multiple methods with same name in a class.
The compiler picks the correct method based on the arguments passed to the method.
Page 33
Java Programming - Spring 2002
Method overloading is a powerful and useful feature. The idea is to create methods that
act in same way on different types of arguments. This creates an illusion that a single
method can operate on any type of arguments. The following example overloads the
method multiply to take two arguments (int, int), ( int, double), (double
double) or (double , int).
public class overload
{
public static void main(String[] args)
{
int
numberOne = 4;
double numberTwo = 20.0;
multiply(numberOne,numberTwo);
}
public static void multiply( int numberOne, int
numberTwo)
{
int result;
result = numberOne * numberTwo;
System.out.println("The result is :
" + result);
}
public static void multiply( double numberOne, double
numberTwo)
// for both decimal values
{
double result;
result = numberOne * numberTwo;
System.out.println("The result is :
" + result);
Page 34
Java Programming - Spring 2002
}
public static void multiply( double numberOne, int
numberTwo)
// for both decimal values and integer values
{
double result;
result = numberOne * numberTwo;
System.out.println("The result is :
" + result);
}
public static void multiply( int numberOne, double
numberTwo)
// for both integer values and decimal values
{
double result;
result = numberOne * numberTwo;
System.out.println("The result is :
" + result);
}
}
Example 3.6: Overloading methods
Output for Example 3.6
Page 35
Java Programming - Spring 2002
Constructors
A constructor is a special method that establishes an object for use when a new class
instance is created. Like other methods, constructors can accept arguments and can be
overloaded. However, constructors have no return type and always have the same name
as the class.
In Java, constructors are provided automatically when a class is created. Constructors
can also be written by the programmer to ensure initialization of fields within a class to a
default value. In example 3.7 below, the constructor method assigns the value 100 to
each worker’s workerNum any time a worker object is created using a statement such
as Worker tempWorker = new worker();. Even if no other data-assigning
methods are used, you are ensured that the tempWorker, like all workers, will have a
workerNum of 100.
public class Worker
{
private int workerNum;
private double salary;
Worker()
//
CONSTRUCTOR METHOD
{
workerNum = 100;
}
// Other methods go here
}
Example 3.7: Constructor method
Page 36
Java Programming - Spring 2002
Alternatively, you might choose to create employees with an initial workerNum that
differs for each worker. To accomplish this within a constructor, you need to pass the
worker number to the constructor. The example below shows a worker constructor that
receives an argument. With this constructor, an argument is passed in using a statement
such as Worker tempWorker = new worker(200);. When the constructor
executes, the integer within the method call is passed to the Worker() and assigned
to the workerNum.
Worker(int num)
{
workerNum = num;
}
Example 3.8: Worker constructor method with an argument
Page 37
Java Programming - Spring 2002
4. Input selection and repetition
Until now most of the programs we have seen have been hard coded value, that is,
values were put into the program. But it would be far more useful if we were able to
provide values to the program at run time, that is, while the program is executing. These
types of programs where the user can input values are more interactive. The simplest
form of providing run time input is keyboard. We have already used class system
and its object out (System.out) for data output, for inputting value we have a similar
object in (System.in). The in object has access to method called read() which
retrieves data from the keyboard.
public class InputDemo
{
public static void main (String[] args) throws Exception
{
char alpha;
System.out.println(“ENTER AN ALPHABET ”);
alpha = (char)System.in.read();
System.out.println(“Your input was ” + alpha);
}
}
Example 4.1: Program taking input and writing it to screen
Page 38
Java Programming - Spring 2002
Output for Example 4.1
The code in the above example 4.1 simply asks the user for an input and then outputs
the same. The line, public static void main (String[] args) throws
Exception, has the phrase throws Exception. The phrase throws
Exception is used because it throws or passes the errors, made by the user while
inputting data (e.g. wrong type of data) to the operating system. A program that reads
from the keyboard will not compile without this phrase.
Repetition or Looping
The for loop
The syntax of the for loop is as follows:
for (<initialization>; <condition>; <increment>){ <statement>}
Here, <initialization> is a list of expressions that is evaluated exactly once before the
loop is executed. The <condition> is evaluated at the start of the loop and is executed
before the subordinate <statement>. The loop terminates when the <condition>
evaluates to false. If the <condition> is true then the <statement> is executed.
Example 4.2 has the loop to print the phrase “Hello Java” 5 times.
Page 39
Java Programming - Spring 2002
public class HelloJava1
{
public static void main(String[ ]
args)
{
for (int x = 1; x<=5; x=x+1){
System.out.println(“Hello Java”);
}
}
}
Example 4.2: for loop
Output for Example 4.2
The if statement
In the if statement the expression is evaluated first. The statement ends if the
expression is evaluated as true. Whether the expression is evaluated as true or false,
execution continues with the next independent statement. In this case, the if statement
accomplishes nothing. The syntax for an if statement is as follows:
Page 40
Java Programming - Spring 2002
if (<expression>) statement;
if(response == ‘y’)
System.out.println("The value of some variable is " +
variable);
response
Example 4.3: An if statement
In example 4.3 if the response variable holds the value ’y’ , then the Boolean value of the
expression (response == ‘y’ ) is true and the subsequent print statement will
execute. If the value of the expression (response == ‘y’ ) is false, then the print
statement will not execute.
The if else statement
The if else statement is like the if statement. The only difference is that in an if
else statement if the boolean value of the expression is false it will execute some other
statement. The if else statement provides a mechanism to perform one action if the
expression is evaluated as true and a different action if the expression is evaluated as
false. The syntax for if else statement is as follows:
if(<expression>)<statement>; else <statement>;
Page 41
Java Programming - Spring 2002
if(response == ‘y’)
System.out.println("Your response was yes");
response
else
System.out.println("Your response was not yes");
Example 4.4: An if else statement
In the above example 4.4 if the user inputs ‘y’ the expression (response == ‘y’)
will evaluate to true and the statement "Your response was yes" will be printed,
otherwise the expression will evaluate to false and the else part of the if else
statement will be executed and "Your response was not yes" will be printed.
The while loop
The syntax of while loop is as follows:
while(<expression >)<statement>;
In the while loop, if the expression is false, the loop stops executing, but if the
expression is true the while loop then executes. Once the statement is executed the
program sends the value of the expression. The program returns the value to evaluate
the expression. This process continues until the expression is no longer met. It is also
possible that the expression is always true. In this case, the loop never terminates. Such
a loop is called an infinite loop. Below is the example of a while loop which prints the
number from 5 to 1.
counter = 5;
Page 42
Java Programming - Spring 2002
while (counter > 0)
{
System.out.println(counter );
counter-- ;
}
Example 4.5: while loop
The do while loop
The do while loop checks the bottom of the loop after one repetition is done. The
syntax of the do while loop is as follows:
do { <statement>} while(<expression>);
In this type of loop, the statement is first executed then the expression is evaluated.
The do while loop, like the while loop, continues to execute the statements as long
as the expression evaluates to true. The only difference is that in the do while loop
the statement is executed at least once even if the condition is never true
counter = 0;
do
{
System.out.println(counter );
Counter++ ;
}
Page 43
Java Programming - Spring 2002
while ( counter < 11);
Example 4.6: do while loop
In the above example, the do statement will keep on looping until the while condition
evaluates to true. The output of the above example will be integers from 1 till 10. At 11
the condition will be true as counter will be equal to 11.
do
{
System.out.println("Press x to exit");
res
System.in.read();
response= (char)System.in.read();
}
while(response =='x');
Example 4.7: do while loop
In the above example 4.7, the program will keep on prompting the user with the
statement "Press x to exit". When the user inputs ‘x’ the loop will stop. The do
while loop is convenient when you want to perform some task at least one time.
Nested looping
Page 44
Java Programming - Spring 2002
A loop can also be put inside another. This is known as nesting of loops. For example,
you can put a while loop inside another while loop, or a for loop within another
for loop or any other combination. If, for example, you want to find all the numbers that
divide evenly into 50, you can write a for loop that sets a variable to 1 and increments it
to 50, next you can write an if loop inside the for loop to do the rest of the calculation.
int num, x;
for(x=1; x<=50; ++x)
{
System.out.print(x+" is evenly divisible by ");
for ( num=1; num<x; ++num)
if(x%num ==0)
System.out.print(num+" ");
System.out.println();
}
Example 4.8: Nested loop
In the above example, the outer loop keeps the count of numbers from 1 till 50, where
as, the inner loop performs all the calculations on each of the numbers.
The switch statement
Page 45
Java Programming - Spring 2002
Sometimes a code can contain nested if statements so that different if has different
statement to execute. For example, the following example checks the number (1-12) and
gives the month.
int monthnum;
char month;
if(monthnum ==12)
{
month = ‘December’;
}
else
{
if(monthnum ==11)
{
month = ‘November’;
}
else
{
if(monthnum ==10)
{
month = ‘October’;
}
else
{
if(monthnum==9)
{
month = ‘September’;
}
Page 46
Java Programming - Spring 2002
}
}
}
system.out.println(“The month is ” + month);
Example 4.9: switch statement
This is a very lengthy and tedious way of writing code. This is where a switch
statement comes in handy. The syntax of switch statement is as follows:
switch (<value>)
{ case<constant 1>: <statement 1>break;
case <constant 2>: <statement 2> break;
case <constant 3>: <statement 3> break;
……………… default: <default statement> break; }
When the switch statement is encountered, the value is used to determine which
statement within the switch is to be executed. If, for example, the value equals to the
constant value of constant 3 then the statement 3 will be executed, then it exits. If no
case is matched then the default case is selected and the default statement is
executed. The switch statement for the above example will be as shown in example
4.9 below.
switch (monthnum)
Page 47
Java Programming - Spring 2002
{
case 12:
system.out.println(“ December”);
case 11:
system.out.println(“ November”);
case 10:
system.out.println(“ October”);
case 9:
system.out.println(“ September”);
default:
system.out.println(“ try again”);
Example 4.9: switch statement
Page 48
Java Programming - Spring 2002
5. Arrays, Vectors and Strings
Arrays
An array is a place to hold a list – a list of numbers, such as scores; a list of strings such
as people’s name; or a list of objects, such as frogs. An array is indicated by []. For
example, array for list of months will be monthName[].
Steps for creating and filling an array are:
1.
Declare the array for example.
String[] monthName;
2.
Create the array using the reserved word new:
monthName = new String[12];
This code tells how many elements the array called monthName will hold.
3.
Filling the array with values.
monthName[0] = “January”;
monthName[1] = “February”;
monthName[2] = “March”;
monthName[3] = “April”; ….monthName[11] = “December”;
4.
Access the value, for example, printing the names of the month.
System.out.println(monthName[0]);
Page 49
Java Programming - Spring 2002
This line of code will print “January”.
int daysInMonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
String monthName[] = {“January”, “February”, “March”,
“April”, “May”, “June”, “July”, “August”, “September”,
“October”, “November”, “December” };
int i, shortest;
System.out.println(“The longest months are :” );
for ( i = 0; i < 12; i++)
{
if (daysInMonth[i] == 31)
System.out.println(monthName[i]);
}
Example 5.1: Array
In the above code we declared two arrays. The first one is for the days in a month and
the second one is for the names of the month. The code first checks out the first array
value one by one from 0 till 11: (daysInMonth[i] == 31). Then it matches all
the 31 values (position) with the same position of the second array to print out the
names of the month.
Page 50
Java Programming - Spring 2002
Vectors
Arrays cannot be used for very big lists, as they use up a lot of memory. We can use a
vector to solve this problem. A vector is a like variable length array that can grow
randomly large. Initially vector is constructed with no cells.
Here is the code for beginning a list, of say, a list of names:
vector names = new Vector();
Here is the code to add objects to the list:
names.addElement(“Tom”);
names.addElement(“Johnny”);
System.out.println(names);
The last line of code prints the contents of the vector.
Here is the code to fetch a value from a vector:
System.out.print(names.elementAt(1));
Each of the elements of vector has an index just like arrays, which begins from 0. It is
also possible to get the size of the array by using size method for example
names.size();. The size method returns the number of elements that are logically
part of the vector.
Page 51
Java Programming - Spring 2002
In vectors when we are reordering the current list of elements, for example, to make the
list in alphabetical order, it is necessary to remove names from the list and then reinsert
them back to another position.
Following is the code for removing an element from the list:
names.removeElementAt(1);
For reinserting we use:
names.insertElementAt(temp,0);
Strings
A string is a sequence of characters. Strings constants are indicated by a sequence of
characters between double quotation marks (“ “). Following are the examples of string :
String name = “Kate Mathew”;
String blankSpace = “” ;
String together = “to” + “get” + “her”;
The last example showed the operation of concatenation, (‘+’). In fact, any value of any
type can be concatenated with string. For breaking up a string we use charAt. This
method allows the programmer to retrieve a single character from a string for charAt
to do its work. It must be provided by position or index. The index of the first character in
a string is always 0 and it increases as we move up.
Page 52
Java Programming - Spring 2002
Comparing a string
Since a string variable holds memory addresses, we cannot make a simple comparison
to determine whether two string objects are similar or not. For example, if you declare
two strings as String aString = “rainbow”; and String
anotherStirng = “rainbow”;, Java will evaluate a comparison such as if
(aString == anotherString) as true. This is comparing the memory address
rather than comparing their values. For comparing values string class provides us with
number of useful methods. The equal() method evaluates two strings to check if they
are equivalent. It returns true if the value are identical. For example,
if(aString.equals(anotherString)) System.out.println(“The
names are same”);.
The equalsIgnoreCase() method is very similar to the equals() method. The
only difference is that it ignores the case while comparing the strings. Thus, if String
aString = “rainbow”; and String anotherStirng = “Rainbow”; the
equals() method will return false and equalsIgnoreCase() method will return
true.
Page 53
Java Programming - Spring 2002
6. File Input and Output
File Class
Files are stored by computers on their permanent storage devices and have a specific
name and time of creation. Files can be of different types depending on their contents:
data files, program files, etc. File class provides information on files, such as, its
existence, size and modification date.
In order to use the File class the statement import java.io.* needs to be used in
the program. Some File class methods are listed below.
Method
Purpose
boolean exists()
If file exists returns true
boolean canRead()
If file is readable returns true
boolean canWrite()
If file is writeable returns true
String getName()
Return’s the file’s name
String getPath()
Return’s the file’s path
long length()
Return’s the file’s size
Figure 6.1: File Class methods
Page 54
Java Programming - Spring 2002
Classes can be written, for example, to examine a file or to check whether a file exists or
not. This is demonstrated in the examples below.
Example 6.1 is a program to check the status of a file. The file in the program is a disk
file that is named info.txt.
The content of this file is: abcdefghijklmnop
import java.io.*;
public class LookupFile
{
public static void main(String[] args)
{
File f = new File("info.txt");
if(f.exists())
{
System.out.println(f.getName() + " does
exist");
System.out.println("The file length is " +
f.length() + " bytes long");
if(f.canRead())
System.out.println(" can be read");
if(f.canWrite())
System.out.println(" can be written");
}
else
System.out.println("File does not exist!");
}
}
Page 55
Java Programming - Spring 2002
Example 6.1: File class program to check a file status
Output for Example 6.1 – when the file exists
Save the above file as LookupFile.java and compile it. In the text editor, open a
new file and type “abcdefghijklmnop” and save the file as info.txt. Run the program
using the command java LookupFile and the output will be as shown above.
Output for Example 6.1 – when the file does not exist
If the file info.txt is removed from the directory and you run the program again, the output
of the program will be “File does not exist” as shown above.
To check the status of files that are stored in other directories (not the current directory
from which you are working) a File constructor with two String arguments is used. Here
the first String argument will represent the filename path and the second will represent
the name of the file. So, for example, for a file in the assignment folder within the Java
folder, you would use File myFile = new File(“\\java\\work”,
“info.txt”)
Page 56
Java Programming - Spring 2002
Example 6.2 below compares two data files for size and time stamp. Create a second
data file by typing “abcdef” in a new file in the text editor and saving it as info1.txt in
the same folder where info.txt is stored.
import java.io.*;
public class LookupTwoFiles
{
public static void main(String[ ] args)
{
File f1 = new
File("info.txt");
File f2 = new File("info1.txt");
if(f1.exists() && f2.exists())
{
System.out.println("The more recent file is
");
if(f1.lastModified() > f2.lastModified())
System.out.println(f1.getName());
else
System.out.println(f2.getName());
System.out.println("The longer file is ");
if (f1.length() > f2.length())
System.out.println(f1.getName());
else
System.out.println(f2.getName());
}
}
}
Example 6.2: Comparing two files
Page 57
Java Programming - Spring 2002
Save the above example as LookupTwoFiles.java and compile and run the program.
The output will be as shown below.
Output for Example 6.2
Data File Organization and Streams
Data stored in variables is stored in the Random Access Memory (RAM) of the
computer. This data is temporary in nature and is lost when the variable no longer
exists. To retain data for longer periods, it need to be stored in secondary storage
devices (e.g. floppy disks, zip disks, compact discs).
When data is stored it is broken down into characters that are made up of bits (zeros
and ones). A group of characters make up a field. A group of fields form a record.
Classes in Java e.g. Student class, represent a record. The variables in this class would
represent data fields. A group of related records make up a file. A Student Enrollment
file would contain one record for each student enrolled.
Every program must open and close a data file. Note: Failure to close an output file
may result in the data not being accessible. Failure to close an input file may not have
serious consequences but would use up memory space.
Page 58
Java Programming - Spring 2002
In Java files are viewed as a series of bytes instead of records. The movement of bytes
during an input and output operation in a program is like a stream. This stream of bytes
is an object and has data and methods that allow you to perform actions.
Input stream
Program
Output stream
Figure 6.1
A stream flows in one direction only. A program may open more then one stream
depending on the number of tasks.
Streams
There are a lot of InputStream and OutputStream classes that can be combined in many
ways. However, there are just a few common ways they are used.
FileInputStream and FileOutputStream are used to read from and write to disk files.
PrintStream is an extensively used object type for handling output to standard output
devices (e.g. monitor). As you have seen in most previous examples the System class
declares an object of type PrintStream. This object is System.out and is commonly
used with the println() method.
The object System.in is a BufferedInputStream object. This object captures
keyboard input and stores it temporarily (until user presses Enter key), thus, allows for
increased speed of deletion or replacement of characters.
Example 6.3 is a program that reads from the keyboard and writes to the screen.
Page 59
Java Programming - Spring 2002
import java.io.*;
public class ReadCatchScreen
{
public static void main(String[ ] args)
throws IOException
{
InputStream istream;
OutputStream ostream;
int c;
istream = System.in;
ostream = System.out;
try
{
while ( (c = istream.read()) != -1)
{
ostream.write(c);
}
}
catch (IOException e)
{
System.out.println(“Error: “ + e.getMessage());
}
finally
{
istream.close();
ostream.close();
Page 60
Java Programming - Spring 2002
}
}
}
Example 6.3: A program that reads from the keyboard and writes to the screen
Use CTRL + Z to end the program in example 6.3.
Writing to a File
You can also assign a file (e.g. disk) to the InputStream and OutStream. To change a
program’s output device you simply need to assign a new object to the OutputStream. A
File object can be associated with the OutputStream in two ways. The first way is by
passing the filename to the constructor of the FileOutputStream class. The second way
is by creating a File object passing the filename to the File constructor and then passing
the File object to the constructor of the FileOutputStream class.
import java.io.*;
public class ReadCatchFile
{
public static void main(String[ ] args)
throws IOException
{
InputStream istream;
OutputStream ostream;
File outFile = new File(“datafile.dat”);
int c;
istream = System.in;
Page 61
Java Programming - Spring 2002
ostream = new FileOutputStream(outFile);
try
{
while ( (c = istream.read()) != -1)
{
ostream.write(c);
}
}
catch (IOException e)
{
System.out.println(“Error: “ + e.getMessage());
}
finally
{
istream.close();
ostream.close();
}
}
}
Example 6.4: A program that writes to a file
Use CTRL + Z to end the program in example 6.4.
Output for Example 6.4
Page 62
Java Programming - Spring 2002
In the example above the keyboard input was the letter “f” and this is written to the new
file.
Reading from a File
This process is similar to writing to a file. See example 6.5 below.
import java.io.*;
public class ReadFileWriteScreen
{
public static void main(String[ ] args)
throws IOException
{
InputStream istream;
OutputStream ostream;
File inFile = new File(“datafile.dat”);
int c;
istream = new FileInputStream(inFile);
ostream = System.out;
try
{
while ( (c = istream.read()) != -1)
{
ostream.write(c);
}
}
Page 63
Java Programming - Spring 2002
catch (IOException e)
{
System.out.println(“Error: “ + e.getMessage());
}
finally
{
istream.close();
ostream.close();
}
}
}
Example 6.5: A program that reads from a file
Output for Example 6.5
The contents of the new file (“f”) in Example 6.4 are read from the file and written to the
screen. See output above.
Page 64
Java Programming - Spring 2002
7. Applets
Applets are small programs that run inside a web browser. An applet is a borderless
rectangle that occupies part of a web page. By default, the applet’s background color is
the same as that of the web page.
Java has a package called applet, which in turn contains a class called Applet. Before
we can subclass the Applet class, we should import either the Applet class explicitly or
the entire applet package:
import java.applet.Applet
or
import java.applet.*
import java.applet.*;
import java.awt.*;
public class FirstApplet extends Applet
{
Label first = new Label(“My first applet”);
public void init()
{
add(first);
}
}
Example 7.1: A first applet
Page 65
Java Programming - Spring 2002
To run the above applet we must place it in a web a page and view it in a Java enabled
web browser. To place an applet inside a web page we must put a special tag inside the
HTML source for that web page to tell page how to run the applet. Below is how an
applet tag would look like for the above applet:
<html>
<applet
code = "inout.class"
width = 200
height = 200>
</applet>
</html>
Example 7.2: HTML tag to place the applet in a web page
In the example 7.2, the code value gives the name of the class file where the applet
resides. The width and height specify the initial size of the applet (in pixel). The output is
shown below.
Page 66
Java Programming - Spring 2002
Output for Example 7.2
Java also provides us with different methods to change the font, font style, etc. to make
applets to look better. To change the font of the text “My first applet” in example 7.2, you
have to create a new font object as follows:
Font headlineFont = new Font(“Helvetica”, Font.Bold,36);
Below is how the code would look like with the change:
import java.applet.*;
import java.awt.*;
public class FirstApplet extends Applet
Page 67
Java Programming - Spring 2002
{
Label first = new Label(“My first applet with new
font”);
Font headlineFont = new Font(“Helvetica”,
Font.BOLD,36);
public void init()
{
first.setFont(headlineFont);
add(first);
}
}
Example 7.3: Changing font and font style to improve the applet
The output of the applet, in example 7.3, with the changed font size and font style is
shown below.
Page 68
Java Programming - Spring 2002
Output for Example 7.3
In addition to labels, Java also provides other features like buttons and text fields in
applets. For example, to provide a TextFeld for a user to advice on our font, we can
code TextField advice = new TextField(15); to provide a textField that is
empty and displays 15 characters. There are several ways in which a text field can be
constructed. Some of them are as follows:
public TextField() creates text field with unspecified length.
public TextField(int width) where width specifies the width for the field.
public TextField(String someText) provides text field with some initial
text.
public TextField(int width, String someText) specifies both width
and initial text
After providing the text field the user should also be provided with the option to submit.
This can be done by providing a button. A button is quite simple to make. You just have
Page 69
Java Programming - Spring 2002
to call the Button constructor with the label you want on the button. For example,
makeButton = new Button(“Submit”);.
import java.applet.*;
import java.awt.*;
public class FirstApplet extends Applet
{
Label first = new Label(“My first applet with new
font”);
Font headlineFont = new Font(“Helvetica”,
Font.BOLD,36);
Button adviceMe = new Button(“Submit”);
TextField advice = new TextField(“ ”, 15);
public void init()
{
first.setFont(headlineFont);
add(first);
add(advice);
add(adviceMe);
advice.requestFocus();
}
}
Example 7.4: Applet with submit
The output of example 7.4 is shown below.
Page 70
Java Programming - Spring 2002
Output from Example 7.4
Capturing an event
The applet above does not do anything even if we press the submit button. Here is when
we add code to determine what would happen when the user presses the submit button.
This is known as event capturing and is done by telling the applet to expect the Action
events with the AddActionListener() method. The action listener interface
contains the actionPerformed(ActionEvent e) method specification. So when
the button is clicked by the user the actionPerformed() method is executed. The
body of this method contains the statement or the calculations the user would like to
print or any other action the user would like to perform. For example 7.4 this method can
be as follows:
Page 71
Java Programming - Spring 2002
public void actionPerformed(ActionEvent
thisEvent)
{
String text = answer.getText();
Label check = new Label("");
check.setText("You submitted: "+ text);
add(check);
invalidate();
validate();
}
Example 7.5: Capturing and event
In example 7.5, the method public void actionPerformed(ActionEvent
thisEvent) is performing three functions:
1.
String text = answer.getText(); This takes the string entered by
the user in the text field and assigns it to the variable text.
2.
Label check = new Label(""); check.setText("You
submitted: "+ text); This creates an empty label on the screen and
then prints “You submitted: ” and the users response which is in the variable
text.
3.
invalidate(); This method is the most important function. It tells the
applet that it is out of date and that it needs to update itself. The second
method validate(); redraws the window with the changes on it.
Page 72
Java Programming - Spring 2002
8. Exception Handling
Exceptions
The object oriented technique to manage exceptions (unexpected or error conditions)
comprises of a group of methods called exception handling. As in other classes in
Java, exceptions are objects and their class name is Exception. There are two basic
classes of errors:

Error class – These are more serious types of errors from which the program can
usually not recover.

Exception class – these are less serious but more unusual errors, which the
program can recover from. E.g. performing certain illegal arithmetic operations.
The error messages for each type of error differ.
In Java, you “try” a procedure that might not complete correctly. A method that detects
an error condition or Exception “throws an Exception,” and the block of code that
processes the error “catches the Exception”.
Try Block and Catch Block
A try block consists of the following:

The word try

An opening curly bracket

Statements that might cause exceptions

A closing curly bracket
Page 73
Java Programming - Spring 2002
A catch block follows a try block immediately and consists of the following:

The word catch

An opening parenthesis

An exception type

A name for an instance of the exception type

A closing parenthesis

An opening curly bracket

Action statement to deal with the error problem

A closing curly bracket
In the method header the keyword throws must be used, followed by an exception
type when a method throws an exception that will be caught.
public class oneMethod throws oneException
{
try
{
// Statements that might cause an Exception
}
catch(oneException theExceptionInstance)
{
// What to do about it
}
// Statements here execute even if there was no Exception
}
Example 8.1: Try block – catch block
Page 74
Java Programming - Spring 2002
In the example above, oneException stands for the Exception class and its
subclasses. The try block is executed first. During the execution of the try block, if an
exception occurs, then the catch block is executed or else it is skipped over.
GetMessage() Method Exception
Instead of writing your own message in the catch block, the getMessage() method can
be used. This method allows you to inherit Java messages from the throwable class.
Example 8.2 shows how the getMessage() method can be used.
public class checkMath
{
public static void main(String [ ] args) throws ArithmeticException
{ int num = 7, denom = 0, result;
try
{
result = num / denom;
}
catch(ArithmeticException error)
{
System.out.println(“The official message is ” + error.getMessage());
}
}
}
Example 8.2: getMessage() method
Page 75
Java Programming - Spring 2002
Output for Example 8.2
In addition to printing an error message in the catch block, you can also add code to
correct the error. For example, in example 8.2 the following statements can be added in
the catch block to divide the arithmetic by one.
result = num / 1;
System.out.println(“Result is ” + result);
Multiple Exceptions
Multiple statements can be added to the try block and you can catch as many
Exceptions as you want. As soon as an error is generated in a try block statement, the
remaining statements in the try block are skipped and the logic transfers to the catch
block. The catch blocks are examined in sequence and when a match is found it is
executed, skipping any remaining catch blocks. Example 8.3 illustrates throwing and
catching multiple exceptions.
Public class MultipleErrors
{
public static void main(String[ ] args)
throws ArithmeticExceptions, IndexOutOfBoundsException
{
int num = 7, den = 0, answer;
Page 76
Java Programming - Spring 2002
int[ ] array = {20,30,40};
try
{
answer = num / den;
answer = array[num];
// First try
//Second try
}
catch(ArithmeticException error)
{
System.out.println(“This is an Arithmetic error!”);
}
catch(IndexOutOfBoundsException error)
{
System.out.println(“This is an Index error!”);
}
}
}
Example 8.3: Two catch blocks
In example 8.3, an Exception occurs in the first statement in the try block because the
denom is zero. So the second statement in the try block is skipped and the logic is
transferred to the first catch block. Since this is an ArithmeticException it will match the
“Arithmetic Error” in the first catch block and print that error. The second catch block is
skipped. See output below.
Output for Example 8.3
Page 77
Java Programming - Spring 2002
If the first try statement succeeds then the program proceeds to the second try
statement and so on. Similarly, if the first catch block does not match the Exception the
program proceeds to the next catch block and so on, until a match is found.
finally Block
The finally block is used to perform actions (e.g. clean-up tasks) at the end of the try
block sequence. The finally block code executes irrespective of whether Exceptions are
identified in the try block.
public class oneMethod throws oneException
{
try
{
// Statements that might cause an Exception
}
catch(oneException theExceptionInstance)
{
// What to do about it
}
finally
{
// Statements here execute even if there was no Exception
}
}
Example 8.4: try block, catch block, finally block
Two primary reasons why finally may be required are:
Page 78
Java Programming - Spring 2002

An unplanned Exception may occur

The try or catch block may contain a System.exit(); statement
An example of a case where a finally block would be used is when a program opens and
reads a file. The finally statement would ensure “If the file is open, close it”.
Page 79
Java Programming - Spring 2002
References
Farrell, Joyce; Java Programming: Comprehensive
www.sun.com
Bailey A. Duane, Bailey W. Duane; Java Elements – Principals of Programming in Java
Eckel, Bruce; Thinking in Java
Page 80
Java Programming - Spring 2002
Download