Download Java Tutorial 1 - Computer Science Home

Document related concepts
no text concepts found
Transcript
Introduction to Java Programming Language
Introduction
 Java is an imperative-based object-oriented programming language introduced by Sun Microsystems
(which is now a subsidiary of Oracle) in 1995.
 Its syntax is derived from C and C++ but it has a simpler object model and fewer low low-level facilities.
 It was first created for developing software for embedded consumer electronic, such as toasters,
microwave ovens, and interactive TV systems. But today, it is mostly used to develop software for
networking, mobile devices, multimedia, games, web-based content and enterprise software.
 Java applications are typically compiled to an intermediate representation called bytecode that can run
(be interpreted) on any Java Virtual Machine (JVM) regardless of computer architecture.
 In order to speed up the execution of java bytecode, Just-in-Time compilers are provided to translate
the bytecode of a method into machine language when it is called for the first time during the execution
of the program.
 You need to install the Java Runtime Environment (JRE) on your computer in order to execute java
applications. It consists of the Java Virtual Machine (JVM), the Java core classes, and the supporting
Java class libraries also known as the Java APIs (Applications Program Interfaces).
 You need a Java development environment or an integrated development environment (IDE) in
order to create, compile, and execute Java applications.
 The latest version of the Java development environ provided by Sun Microsystems is Java SE
Development Kit 8 (JDK8) that can be downloaded from the web site java.sun.com/javase/downloads/.
 IDEs provide tools that support the software development process, including editors, and debuggers.
Popular IDEs include Eclipse (www.eclipse.org) and Netbeans (www.netbeans.org).
© 2011 Gilbert Ndjatou
Page 1
Elements of Java Programming Language
Comments
 Comments are the same as in C++.
Examples
/*-- Program to add two integer values --*/
// read the values
Identifiers
A. Rules for writing valid identifiers:
1. In Java, a letter denoted by L is defined as: ‘a’ to ‘z’, ‘A’ to ‘Z’, the underscore character ‘_’ or any
Unicode character that denotes a letter in a language.
2. A digit denoted by D is defined as ‘0’ to ‘9’ or any Unicode character that denotes a digit in a
language.
3. An identifier is defined as:
(L | $)(L | D | $)*
4. However, by convention, user-defined identifiers do not start with the dollar sign ‘$’ or the
underscore ‘_’ and the dollar sign ‘$’ is never used for user-defined identifiers.
5. C++ conventions for identifiers are also used in Java: use of the underscore character as a connector
or start the second word with an uppercase letter. Examples: gross_pay, grossPay.
6. An identifier cannot be a Java Keyword. Java keywords are provided in Appendix 1.
7. Uppercase and lowercase letters are different.
Constant Data
 There are six types of constant data in Java:

Boolean constants

character constants,

integer constants,

floating-point constants,

strings constants, and

Special constants
© 2011 Gilbert Ndjatou
Page 2
Boolean Constants
 Boolean constants are the same as in C++:

true and false.
However, 0 is not false and anything else is not true as in C++.
Character Constants
 A character constant is either a single printable Unicode character enclosed between single quotes, or an
escape sequence enclosed between single quotes.
Examples of printable characters: 'A', '$',
Examples of escape sequences: '\n',
'\t',
'8',
‘ ’ (space bar), 'z'.
‘\”’,
'\'', '\\',
'\?'.
 Escape sequences are used to represent characters that you can not type from the keyboard or characters
that have a meaning for the compiler such as single quote, double quote, . . ., etc.
 Unicode characters that you cannot type from the keyboard may be specified using a Unicode escape
sequence in the form: \uXXXX where XXXX represents the hexadecimal code of that character.
Examples
‘\u00EA’ for ê
and
‘\u00A5’
for ¥
Integer Constants
 Integer constants are the same as in C++: positive or negative whole numbers.
 An integer constant may be specified in one of the following bases:

Decimal
Example: 26

Octal (base 8)
Example: 032

Hexadecimal (base 16)
Example: 0x1A (the number 26 in hexadecimal)
(the number 26 in octal)
Floating-point constants
 Floating-point constants are the same as in C++:
 They may either be written in decimal notation or exponential notation.
 They may be specified with the ‘f’ or ‘F’ suffix for the 32-bit value or the ‘d’ or ‘D’ suffix for the 64-bit
value which is the default.
Examples
123.4
1.234e+2D
123.4f
String constants
 A string constant is a sequence of zero or more Unicode characters (including escape sequences)
enclosed between double quotes.
© 2011 Gilbert Ndjatou
Page 3
Examples
“\nJohn Doe”
“Enter a value:\t”
“T\u00EAte” (Tête)
Special Constants
 There are two special constants:

null

A class literal (constant) is formed by taking a type name and appending “.class” to it. For example,
String.class.
can be used as the value for any reference type (but not primitive type) variable.
Variables, Basic Data Types, and Type Binding
 Name of a variable: is an identifier.
 Address of a variable:
is not accessible in a program.
 In Java, the number of bytes reserved for a memory location depends on the data type of the
corresponding variable, and not on the machine on which you will be running the Java program.
 Basic data types: Java basic data types with their range of values are provided in the following table:
Data Type
Type of Data
Range of Values
boolean
Boolean value
true, false
char
A single
character
Unicode character representations: ‘\u0000’ – ‘\uffff’
2 byte
byte
integers
-27 (-128) to 27 – 1 (127)
1 bytes
short
integers
int
integers
-231 (-2,147,483,648) to 231 – 1 (2,147,483,647)
4 bytes
long
integers
-263 (-9,223,372,036,854,775,808) to 263 – 1 (9,223,372,036,854,775,807)
8 bytes
float
Floating point
decimals
Floating point
decimals
Negative range: -3.4028235E+38 to -1.4E-45
Positive range: 1.4E-45 to 3.4028235E+38
Negative range: -1.7976931348623157E+308 to -4.9E-324
Positive range: 4.9E-324 to 1.7976931348623157E+308
4 bytes
double
© 2011 Gilbert Ndjatou
-215 (-32,768)
to 215 – 1 (32,767)
Size
2 bytes
8 bytes
Page 4
 The precisions of a floating point data types are provided as follows:
Data Types
Precision
float
7 digits
double
15 digits
Type Binding:
(static type binding with explicit declarations of variables).
 In Java, a variable must be declared before it can be used.
 The declaration statement is the same as in C++.
Examples
int num,
// to hold the first value
number, // to hold the second value
sum;
// to hold their sum
Note
There is a Java class named type-wrapper class for each of the basic data types above. This class has
the same name as the basic data type, but starts with an uppercase letter: Byte, Short, Integer, Long,
Float, and Double.
Arithmetic Expressions
 The rules for writing and evaluating valid arithmetic expressions are the same as in C++. However,
unlike in C++, the order of operands evalution in Java is left-to-right.
 Java also allows mixed-mode expressions as in C++: the following table shows the Java arithmetic
operators and how the data type of the result is obtained from those of the operands.
Operation
Operator
Addition
+
Example
A+B
Promotion Rule
1.
2.
Subtraction
-
A–B
Multiplication
*
A*B
Division
Modulus
(Remainder)
/
A/B
%
A%B
Negation
-
-A
3.
© 2011 Gilbert Ndjatou
4.
5.
Operands with data type byte or
short are converted to int.
If either operand is of type double,
then the other operand is converted
to double.
Otherwise, if either operand is of
type float, then the other operand
is converted to float.
Otherwise, if either operand is of
type long, then the other operand is
converted to long.
Otherwise, both operands are
converted to int.
Page 5
Assignment Statement
 Its syntax is the same as in C++:
<variable-name> = <arithmetic-expression>;
Examples
char letter;
int num1, result;
double dnum;
letter = ‘A’;
num1 = 25;
dnum = 4.25;
result = num1 * 3;
// the new value of variable result is 75
Assignment conversion Rules
 Java allows you to make certain assignment conversions by assigning a value of one type to a variable
in another type as follows:
byte
→ short
→ int → long
→ float
→ double
Example
byte bnum = 97;
int inum = 123;
long lnum;
double dnum;
lnum = bnum;
dnum = inum;
 Conversions from one type to the right of an arrow above to another type to the left of the arrow are done
by means of casts. However, there may be a loss of information in the conversion.
Example
double dnum = 9.997;
int inum = (int) dnum;
// the value of inum is: 9
Compound Assignments and the Assignment Operator
 Compound assignments are specified in the same way as in C++ as follows:
<variable-name>
<operator>= <expression>;
Which is equivalent to the regular assignment:
<variable-name> = <variable-name> <operator> <expression>;
© 2011 Gilbert Ndjatou
Page 6
Examples
Compound Assignments
Equivalent Simple Assignments
counter += 5;
power *= value;
counter = counter + 5;
total -= value;
remain %= 8;
result /= num - 25
number *= -1;
power = power * value;
total = total - value;
remain = remain % 8;
result = result / (num - 25);
number = -number;
 In Java, the assignment is an operator with right-to-left associativity.
Example
num1 = num2 = number = 5;
// num1 = 5
num2 = 5
number = 5
Initial value of a Variable
 The initial value of a variable with a basic data type can be specified when it is declared in the same way
as in C++.
Examples
int num1 = 25,
num2,
sum = 0;
char letter , grade = 'A';
Naming Constants
 In Java, you use the keyword final in the declaration of a variable to indicate that its initial value cannot
be modified as follows:
final <data-type> <variable-name> = <arithmetic-expression>;
Example
final double PI = 3.14;
final int MAXVALUE = 150;
 final variables correspond to const variables in C++. They are in general specified in upper case.
© 2011 Gilbert Ndjatou
Page 7
Increment and Decrement Operators
 The increment and the decrement operators are the same as in C++.
Example
int inum1 = 12, inum2 = 50;
double dnum = 2.54;
inum1++;
inum2 = - - inum1 * 10 ;
++dnum;
Logical Expressions
 A logical expression (or condition) are specified and evaluated in the same way as in C++.
 A simple condition has the following syntax:
<arithmetic expression>
<relational operator>
<arithmetic expression>
Relational Operators
C/C++ Symbol
Meaning
<
is less than
>
is greater than
==
is equal to
<=
is less than or equal to
>=
is greater than or equal to
!=
is not equal to
 A compound condition is built from simple conditions and logical operators.
Logical Operators
C++ Symbol
&&
© 2011 Gilbert Ndjatou
Meaning
AND
||
OR
!
NOT
Evaluation
<condition1> && <condition2> is true if and only if
both conditions are true
<condition1> || <condition2> is true if and only if at least
one of the two conditions is true
!<condition> is true if and only if <condition> is false
Page 8
 In C++, 0 is false and anything else is true. But this is not the case in Java. So, the C++ condition
!num (which is equivalent to num = = 0) is not valid in Java.
Precedence of Java Operators
Operator
!
Unary –
*
/
%
+
<
<=
>
<=
==
!=
&&
||
Order of Evaluation
Precedence
right to left
7
left to right
6
left to right
5
left to right
4
left to right
3
left to right
left to right
2
1
Conditional Expressions
 A conditional expression has the following syntax:
<Condition > ? <expression-True> : <expression-false>
 With the meaning: if <Condition> is true, the value of the expression is the value of <expressiontrue> otherwise, it is the value of <expression-false>.
Example:
average = (count = = 0) ? 0 : sum / count;
 A conditional expression can be used in a program where any other expression can be used.
Example:
cin >> num1 >> num2;
cout << 2 + (num1 > num2 ? num1/ num2 : num2 / num1);
Note that if the inputs are 15 and 3, the output will be 7 and if they are 2 and 7 the output will be 5.
© 2011 Gilbert Ndjatou
Page 9
Class String
 The Java programming language does not have a basic data type to store and manipulate character
strings.
 However, the standard Java library contains a predefined class called String (from the package
java.lang) that may be used to create and manipulate character strings.
 A String object (as any other object in Java) is created by using the new operator and a class
constructor.
For example:
String name = new String(“John Doe”);
 But you can declare a String object that references a string constant as follows:
String <variable-name>
=
<string-constant>;
Example
String greeting = “Hello world!”;
 You can also use the assignment statement to store a character string into a String variable.
Example
String address;
address = “300 Pompton Road, Wayne, NJ 07470”;
Concatenation Operator
 In Java, the + operator can be used to join (concatenate) two strings together or a string to any other
value.
Examples
int num = 105;
String head = “Hello”;
String tail = “ world!”;
String greeting1 = head + tail;
String greeting2 = head + 2009;
String rating = “PG” + 13;
String message = “num =” + num;
// the value of variable greeting1 is: Hello world!
// the value of variable greeting2 is: Hello2009
//the value of the variable rating is: PG13
// the value of the variable message is: num = 105
 You can also use the + operator in the compound assignment.
© 2011 Gilbert Ndjatou
Page 10
Examples
String greeting = “Hello”
greeting + = “ world”;
// the value of variable greeting is: Hello
// the value of variable greeting is: Hello world!
Testing Strings for Equality
 In Java, you do not use the = = operator to test for Strings equality as in C++.
 You use instead the equals( ) or the equalsIgnoreCase( ) methods to do it as follows:
StringVar1.equals(StingVar2)
returns true if strings StingVar1 and StringVar2 are identical.
StringVar1.equalsIgnoreCase(StingVar2)
returns true if strings StingVar1 and StringVar2 are identical
except for the uppercase/lowercase letter distinction.
Examples
String greeting = “Hello”;
String message = “Thanks”;
greeting.equals(“Hello”)
returns true
greeting.equals(message)
returns false
“Thanks”.equals(message)
returns true
greeting.equals(“HELLO”)
returns false
greeting.equalsIgnoreCase(“HELLO”)
returns true
String Length
 The length( ) method returns the number of character contained in a String object.
Example
String message = “Thank you”;
int n = message.length( );
© 2011 Gilbert Ndjatou
// the value of variable n is: 9
Page 11
Converting Strings to their Numerical Values
 Strings of digits can be converted into their numerical values by using the following methods:
Byte. parseByte( s )
Short.parseShort( s )
Integer.parseInt( s )
Long.parseLong( s )
Float.parseFloat( s )
Converts string s to a byte
Converts string s to a short
Converts string s to an integer (int)
Converts string s to a long integer ( long )
Converts string s to a single precision floating point (float)
Double.parseDouble( s )
Converts string s to a double precision floating point (double)
Example
String argument1 = “123”,
argument2 = “123.45”;
int inum = Integer.parseInt( argument1 );
double dnum = Double.parseDouble( argument2 );
// inum = 123
// dnum = 123.45
Converting Numbers to Strings
 Sometimes you may want to convert a number to a string because you need to operate on its value in
string form.
 You can convert a number to a string in one of the following ways:
1. Use the String concatenation operator:
Example
int inum = 123;
double dnum = 12.5;
String st1 = “” + inum;
String st2 = “” + dnum;
2. By using the String.valueOf( ) method:
Example
int inum = 123;
double dnum = 12.5;
String st1 = String.valueOf( inum );
String st2 = String.valueOf( dnum );
3. By using the toString( ) class methods (example: String st1 = Integer.toString( 123); ).
© 2011 Gilbert Ndjatou
Page 12
Standard Input
 Input statements are not provided in the Java language.
 However, input from the standard input device may be performed in a Java program by using objects
of the class Scanner.
 The standard input device (which by default is the keyboard) is represented in a Java program by the
object System.in.
 You use objects of the class Scanner to perform standard input as follows:
1. Write the following import statement before any class of your program:
import java.util.Scanner;
2. Declare an object of the class Scanner and initialize it with the object in.System as follows:
Scanner <Object-Name> = new Scanner( System.in );
Example:
Scanner input = new Scanner( System.in );
3. Use the following instance methods to perform input:
Method
What it does
Example
next( )
nextByte( )
nextDouble( )
nextFloat( )
nextInt( )
nextLine( )
nextLong( )
nextShort( )
Input next word (sequence of characters)
Input next byte
Input next double precision value
Input next single precision value
Input next integer value
Input next line of text
Input next long integer value
Input next short integer value
String name = input.next( );
byte num = input.nextByte( );
double dnum = input.nextDouble( );
float fnum = input.nextFloat( );
int inum = input.nextInt( );
String line = input.nextLine( );
long lnum = input.nextLong( );
short snum = input.nextShort( );
 Input values are separated (by default) with white spaces: spaces, tabs, carriage returns, . . ., etc.
Example
int age, hours;
double payRate;
String firstName;
firstName = input.next( );
age = input.nextInt( );
payRate = input.nextDouble( );
hours = input.nextInt( );
Input:
© 2011 Gilbert Ndjatou
John 24 12.50 35
Page 13
Standard Output
 Output statements are not provided in the Java language.
 However, output to the standard output device (which is by default the monitor) can be performed by
using the methods println and print on object System.out.
 They have the following syntax:
System.out.println( <string> );
System.out.print( <string> );
 println outputs <string> and then moves the cursor to the next line whereas print just outputs
<string>.
Example
int num = 105;
String head = “Hello”;
String tail = “ world!”;
System.out.println( “Hello World!” );
System.out.println( head + tail );
System.out.println( head + 2009 );
System.out.println( “PG” + 13 );
System.out.println( “num - 3 =\t” + (num – 3));
Output:
Output:
Output:
Output:
Output:
Hello World!
Hello world!
Hello2009
PG13
num - 3 = 102
Formatted Output
 Formatted output to the standard output device can be performed by using the printf methods on
object System.out.
 It has the following syntax:
System.out.printf( <format-string>, <Argument-list> );
 <format-string> consists of fixed text and format specifiers.
 The fixed text in the format string is output just as it would be in a print or println method.
 Each format specifier in the <format-string> is the placeholder of the value of the corresponding
argument in the <Argument-list>.
 A format specifier may also include optional formatting information such as the number of spaces to
use to display a value (field width) or the number of digits to be displayed after the decimal point of
a floating point value.
 If the field width is larger than the data being printed, the data is right justified in the field (by
default); if you want the data to be left justified, precede the field width with the minus sign.
© 2011 Gilbert Ndjatou
Page 14
 The following table lists some format specifiers with their corresponding data formats:
Format Specifier
Data Format
Example
Output
%c
%C
%s
%S
%d
%o
%x or %X
%f
%e or %E
a single character in lowercase
a single character in uppercase
a string of characters in lowercase
a string of characters in uppercase
Decimal integer in base 10
Decimal integer in base 8
Decimal integer in base 16
Floating point in decimal format
Floating point in exponential format
Floating point in either floating
point format or exponential format
based on the magnitude of the value
System.out.printf( “%c”, ‘a’ );
System.out.printf( “%C”, ‘a’ );
System.out.printf( “%s”, “John” );
System.out.printf( “%S”, “John” );
System.out.printf( “%d”, 125 );
System.out.printf( “%o”, 125 );
System.out.printf( “%X”, 125 );
System.out.printf( “%f”, 12.5 );
System.out.printf( “%E”, 12.5 );
a
A
john
JOHN
125
175
7D
12.5
1.25E+1
System.out.printf( “%G”, 12.5 );
12.5
%g or %G
 You specify a field width between the % symbol and the format specifier.
 The number of digits to be displayed after a decimal point in a floating point value is specified in the
same way as the field width, but it must be preceded with the decimal point.
Examples
Given the following definitions of variables:
int inum = 125;
char ch = 'z';
float fnum = 42.75;
double dnum = 347.874;
a) System.out.printf("\nI have chosen the number:%4d and the value of ch is:\t%C", 47, ch);
Output
|I have chosen the number:_ _47 and the value of ch is:
Z_
b) System.out.printf("\nThe value of fnum is:%7.1f \n and that of dnum is:%.2E", fnum, dnum);
Output
|The value of fnum is: _ _ _42.8
|and that of dnum is:3.48E+2
c) System.out.printf("\n%10S\nt%-10S", “PRICE”, “PRICE”);
Output
© 2011 Gilbert Ndjatou
|_ _ _ _ _ PRICE
|PRICE_ _ _ _ _
Page 15
Creating Format Strings
 Using the String.format( ) static method, you can create a formatted string that you can reuse, as
opposed to a one-time print statement.
Example
Given the declaration of variables provided in the example above, instead of the output statement in
example a) we can write:
String st = String.format( "\nI have chosen the number:%4d and the value of ch is:\t%C", 47, ch);
System.out.println( st );
Control Structures
 Java has the same control structures as C++:
1. Two way selection:
implemented using the if-else structure as in C++.
2. One way selection:
implemented using the if structure as in C++.
3. Counter –controlled iteration:
there is no counting loops in Java. However, counting loops
are simulated by using the while-loop or the for-loop as in C++.
4. Logically controlled iteration:
implemented using the while-loop or the for-loop as in C++.
5. Multiple way selections: implemented using if-else structures or the switch structure as in C++.
Java Program
 A Java program consists of one or more source files.
 The file name of a source file must be a valid Java identifier with the filename extension .java.
Examples
Lab0.java
GradeProcessing.java
PayRollProc.java
SampleProg.java
 A Java source file consists of one or more classes.
 A class is used to encapsulate data (variables) and methods (functions) and is in general defined as
follows:
<access-specifier> class <name-of- class>
{
<definitions of variables and/or methods>
}
© 2011 Gilbert Ndjatou
Page 16
<name-of-class>
is a valid Java identifier. But by convention, its initial letter is capitalized.
<access-specifier>
is either public or is omitted.
 A class with access specifier public is visible in any other source module.
 When the access specifier is omitted, the class is visible only within its own package (named group
of related classes).
 One class in every source module must have the access specifier public. The name of this class must
be the name of that source module.
 A public class of every program must contain method main with the following syntax:
public static void main( String [ ] args )
{
<statements-of-method-main>
}
Where args is an array of Strings to be initialized with command line arguments.
Example P1
/*--------------------------------------Program1 -------------------------------------*/
public class Program1
{
public static void main( String [ ] args )
{
System.out.println( “Hello World!”);
System.out.println(“Java, here we come”);
}
}
Notes:
 The name of the source file that contains this class must be: Program1.java.
 The execution of a Java program starts with the first executable statement in method main.
 The statements of any other method are executed only if that method is called by main or a method
that is called by main.
© 2011 Gilbert Ndjatou
Page 17
Compiling and Executing a Java Program
 You compile a java source file as follows:
Javac <source-file-name> <ENTER>
Example
You compile the source file of example P1 as follows:
javac Program1.java <Enter>
 The Java compiler will create the bytecodes for this class and store it in a new file named
Program1.class (in the same directory).
 You use the Java interpreter to run a bytecode file as follows:
java <bytecode-filename> <Enter>
Example
The bytecode Program1.class of the program in example P1 is executed as follows:
java Program1 <Enter>
 Input redirection: you can ask the operating system to get the input of your program from a file instead
of the keyboard by first entering all the input data of your program in that file and then specifying that
file when you execute your program as follows:
java <bytecode-filename> < <input-data-file> <Enter>
Example
For the bytecode Program.class to get its input from the file program.dat execute it as follows:
java Program < program.dat <Enter>
 Output Redirection: you can ask the operating system to send the output of your program to file instead
of the monitor by using the output redirection as follows:
java <bytecode-filename> > <ioutput-data-file> <Enter>
Example
For the bytecode Program.class to send its output to the file program.out, execute it as follows:
java Program > program.out <Enter>
For the bytecode Program.class to get its input from the file program.dat and to send its output to
the file program.out, execute it as follows:
java Program < program.dat > program.out <Enter>
© 2011 Gilbert Ndjatou
Page 18
Lab Procedure
A. Follow this procedure if you are using one of the lab computers
1. Use Notepad to create the file SETUPJAVA.BAT with the following content:
@echo off
set PATH=C:\Program Files\Java\jdk1.8.0_25\bin;%PATH%
E:
Where:
 jdk1.8.0_25
 E:
is the version of the Java Development Kit installed on your PC
is the name of the drive with your flash drive.
2. Save the file in your flash drive.
3. Perform the following activities before you can compile and execute your Java programs:
a. Use Notepad or any other editor to type your Java program source files and save them in your
flash drive (make sure that your flash drive is in drive E and type the name of the source files
in double quotes: e.g. “Lab0.java”).
b. Click the Start button, and then click All Programs, then Accessories, and then Command
Prompt to open the Command Prompt window.
c. Type the command: DIR C:\“Program Files\Java”  to list the content of the Java
directory.
d. Make sure that the version number of the JDK is 1.8.0_25; otherwise change 1.8.0_25 in the
SETUPJAVA.BAT file to the version number of the JDK displayed on your computer.
e. At the Prompt, execute the SETUPJAVA.BAT file as follows: E:\SETUPJAVA 
© 2011 Gilbert Ndjatou
Page 19
B. Follow this procedure if you are using a laptop or a computer at home
1. First find out the version number of your Java Development Kit as follows:
a. Click the Start button, and then click All Programs, then Accessories, and then Command
Prompt to open the Command Prompt window.
b. Type the command: DIR C:\“Program Files\Java”  to list the content of the Java
directory. Your version of the JDK will be listed with its version number (for example:
jdk1.8.0_25). Note that if you have downloaded the 32-bit version of JDK, you should type
the command: DIR C:\“Program Files (x86)\Java” 
2. Update the PATH Environment variable to include the pathname:
C:\Program Files\Java\jdk1.8.0_25\bin (where 1.8.0_25 is the version number of JDK)
or C:\Program Files (x86)\Java\jdk1.8.0_25\bin (if you have a 32-bit version of JDK).
You update the PATH environment variable as follows:
a. Click Start, then Control Panel, then System and Security, then System.
b. Click Advanced System Settings, then Environment Variable.
c. Select Path in System Variables and then click Edit.
d. Use the right-arrow key to move the cursor to the end of the displayed string.
e. Type a semicolon followed by the pathname that you want to add.
f. Click OK.
3. Perform the following steps before you can compile and execute your Java programs:
a. Use Notepad or any other editor to type your Java program source files and save them in
your flash drive (make sure that your flash drive is in drive E and type the name of the source
files in double quotes: e.g. “Lab0.java”).
b. Click the Start button, and then click All Programs, then Accessories, and then Command
Prompt to open the Command Prompt window.
c. Type E: 
© 2011 Gilbert Ndjatou
to change to the drive that contains your flash drive.
Page 20
Java Methods
 Java methods have the same syntax as C++ functions; but they are defined in the class in which they
belong: there are no function prototypes in Java.
 A Java method may be specified as a class (static) method or an instance method.
 Class methods and instance methods differ in the way they are called in a Java program.
 Variables and methods defined in a Java class also have access specifiers.
 The access specifiers with their access levels are provided as follows:
Can be accessed in:
specifier
Class
Package
Subclass
Everywhere
public
Yes
Yes
Yes
Yes
protected
Yes
Yes
Yes
No
No specifier
Yes
Yes
No
No
private
Yes
No
No
No
 The general syntax of a class (static) method follows:
<Access-specifier> static <Return-type> <Function-Name>( <Parameter-List> )
{
<statements-of-function>
}
 The general syntax of an instance method follows:
<Access-specifier> <Return-type> <Function-Name>( <Parameter-List> )
{
<statements-of-function>
}
© 2011 Gilbert Ndjatou
Page 21
Where
<Access-specifier> is either private, public or is not specified
<Return-type>
<Parameter-List>
is either void or the data type of the value returned by the function
is a list of zero or more value parameters.
 Parameters are specified in the same way that they are specified in C++, except that there are no
reference parameters in Java: Java allows only value parameters.
 In addition to values in the basic data types boolean, char, byte, short, int, long, float, and double,
Java methods can return arrays, strings, and objects.
Defining and Calling a Class (static) Method
 You call a class (static) method in any other method (class or instance) in the class in which it
is defined in the same way that you call a user-defined function in C++.
Example P2
The following program reads two integer values and computes their product by calling the class method
int computeProd1(int num1, int num2).
/*-------------------------------------------------------Program2 --------------------------------------------*/
/* Read two integer values, compute their product
*/
import java.util.Scanner;
public class Program2
{
public static void main( String [ ] args )
{
Scanner input = new Scanner( System.in );
int first,
second;
// for standard input
// to hold the first value
// to hold the second
/*-------------------------------read the two values -------------------------------*/
first = input.nextInt( );
second = input.nextInt( );
/*---------------------------Compute and print their product--------------------------------*/
int product = computeProd1( first, second );
System.out.println( “Their product is:\t” + product );
}
© 2011 Gilbert Ndjatou
Page 22
/*---------------------------------------Class Method computeProd( )--------------------------------------*/
/* compute the product of two integer values and returns it
*/
static int computeProd1( int num1, int num2)
{
return( num1 * num2);
}
}
Defining and Calling an Instance Method
 You call an instance method in a class (static) method as follows:

First define and initialize a reference variable with the location of an object of the class of the
instance method.

Follow that variable with the dot (.) which is followed by the method name to call it.
 You define and initialize a reference variable with the location of an object in one of the following
ways:
a.
<Class-name> <variable-name> = new <Class-name>( );
b.
<Class-name> <variable-name> ;
<variable-name> = new <Class-name>( );
Example P3
The following program reads two integer values and computes their product by calling the instance
method int computeProd2(int num1, int num2).
/*-------------------------------------------------------Program3 --------------------------------------------*/
/* Read two integer values, compute their product
*/
import java.util.Scanner;
public class Program3
{
public static void main( String [ ] args )
{
Scanner input = new Scanner( System.in );
int first,
second;
// for standard input
// to hold the first value
// to hold the second
/*-------------------------------read the two values -------------------------------*/
first = input.nextInt( );
second = input.nextInt( );
© 2011 Gilbert Ndjatou
Page 23
/*---------------------------Compute and print their product--------------------------------*/
Program3 objRef = new Program3( );
int product = objRef.computeProd2( first, second );
System.out.println( “Their product is:\t” + product );
}
/*---------------------------------------Instance Method computeProd( )--------------------------------------*/
/* compute the product of two integer values and returns it
*/
int computeProd2( int num1, int num2)
{
return( num1 * num2);
}
}
 You call an instance method in another instance method from the same class in the same way
that you call a user-defined function in C++.
Example P4
The following program reads two integer values and computes their average by calling the instance
method int computeAvg(int num1, int num2) which also calls the instance method int computeSum(int
num1, int num2).
/*-------------------------------------------------------Program4 --------------------------------------------*/
/* Read two integer values, compute their product
*/
import java.util.Scanner;
public class Program4
{
public static void main( String [ ] args )
{
Scanner input = new Scanner( System.in );
int first,
second;
// for standard input
// to hold the first value
// to hold the second
/*-------------------------------read the two values -------------------------------*/
first = input.nextInt( );
second = input.nextInt( );
/*---------------------------Compute and print their product--------------------------------*/
Program4 objRef = new Program4( );
int average = objRef.computeAvg( first, second );
System.out.println( “Their average is:\t” + average );
}
© 2011 Gilbert Ndjatou
Page 24
/*---------------------------------------Instance Method computeAvg( )--------------------------------------*/
/* compute the product of two integer values and returns it
*/
int computeAvg( int num1, int num2)
{
int total = computeSum( num1, num2);
return( total / 2);
}
/*---------------------------------------Instance Method computeSum( )--------------------------------------*/
/* compute the product of two integer values and returns it
*/
int computeSum( int num1, int num2)
{
return( num1 + num2 );
}
}
 You can call a class (static) method in an instance method.
Example P5
The following program reads two integer values and computes their average by calling the instance
method int computeAvg(int num1, int num2) which also calls the class method int computeSum(int num1,
int num2).
/*-------------------------------------------------------Program5 --------------------------------------------*/
/* Read two integer values, compute their product
*/
import java.util.Scanner;
public class Program5
{
public static void main( String [ ] args )
{
Scanner input = new Scanner( System.in );
int first,
second;
// for standard input
// to hold the first value
// to hold the second
/*-------------------------------read the two values -------------------------------*/
first = input.nextInt( );
second = input.nextInt( );
/*---------------------------Compute and print their product--------------------------------*/
Program5 objRef = new Program5( );
int average = objRef.computeAvg( first, second );
System.out.println( “Their average is:\t” + average );
}
© 2011 Gilbert Ndjatou
Page 25
/*---------------------------------------Instance Method computeAvg( )--------------------------------------*/
/* compute the product of two integer values and returns it
*/
int computeAvg( int num1, int num2)
{
int total = computeSum( num1, num2);
return( total / 2);
}
/*---------------------------------------Class Method computeSum( )--------------------------------------*/
/* compute the product of two integer values and returns it
*/
static int computeSum( int num1, int num2)
{
return( num1 + num2 );
}
}
Class variables
 A class variable (static field) is any variable declared with the static modifier. It is the same as a
static member variable in C++.
 It is used as a C++ global variable and is accessed by both instance and class methods.
 It is in general defined as follows:
<Access-specifier> static <Data-type> <Variable-Name>;
Where
<Access-specifier> is either private, public or is not specified
 A class variable may also have an initial value or be a final variable.
Example P6
The following program reads two integer values and computes the quotient and the remainder in the
division of the first value by the second by calling the class method void computeQuotRem(int num1, int
num2).
Note that since arguments are not passed by reference in Java, two class variables are needed to get the
quotient and the remainder from function computeQuotRem( ).
© 2011 Gilbert Ndjatou
Page 26
/*-------------------------------------------------------Program6 --------------------------------------------*/
/* Read two integer values and compute the quotient and the remainder in the division
of the first value by the second
*/
import java.util.Scanner;
public class Program6
{
static int quotient;
static int remain;
// to hold the quotient
// to hold the remainder
public static void main( String [ ] args )
{
Scanner input = new Scanner( System.in );
int first,
second;
// for standard input
// to hold the first value
// to hold the second
/*-------------------------------read the two values -------------------------------*/
first = input.nextInt( );
second = input.nextInt( );
/*-------------------Compute and print the quotient and the remainder-------------------*/
if( second == 0 )
System.out.println( “Division by zero is not allowed!”);
else
{
computeQuotRem( first, second );
System.out.println(“The quotient is:\t” + quotient );
System.out.println(“The remainder is:\t” + remain );
}
}
/*--------------------------------------Class Metod computeQuotRem( )--------------------------------------*/
/* compute the quotient and the remainder in the division of the first argument by the second
*/
static void computeQuotRem( int num1, int num2)
{
quotient = num1 / num2;
remain = num1 % num2;
}
}
Method (Name) Overloading
 Two or more Java methods may have the same name, as long as there is a way to distinguish them
based on their parameters: this feature is known as method name overloading.
 The compiler determines the right version of the method to call from a set of overloaded methods by
inspecting the arguments specified in the function call.
 The program in example P7 illustrates the use of method name overloading in a source module.
© 2011 Gilbert Ndjatou
Page 27
Example P7
Method Name Overloading
/*----------------------------------------------------Porgram7 ------------------------------------------------------*/
/* Compute the average of two integer values, the average of three integer values
and the average of two double precision floating-point values.
import java.util.Scanner;
public class Program7
{
int main()
{
int result1,
result2;
double result3;
// the average of two integer values
// the average of three integer values
//the average of two floating-point values
result1 = ComputeAverage(4, 5);
// calling first method
result2 = ComputeAverage(5, 4, 6); // calling second method
result3 = ComputeAverage(4.0, 5.0);
// calling third method
System.out.println( “result1=\t” + result1 );
System.out.println( “result2=\t” + result2 );
System.out.println( “result3=\t” + result3 );
return 0;
}
static int ComputeAverage(int value1, int value2)
{
return (value1 + value2) / 2;
}
static int ComputeAverage(int value1, int value2, int value3)
{
return (value1 + value2 + value3) / 3;
}
static double ComputeAverage(double value1, double value2)
{
return (value1 + value2) / 2;
}
}
OUTPUT
result1=
result2=
result3=
4
5
4.5
© 2011 Gilbert Ndjatou
Page 28
*/
One-Dimensional Arrays
 In Java, a one-dimensional array variable is a reference variable: it is an explicit/implicit heap
dynamic variable.
 A one-dimensional array variable is declared as follows:
<data-type> [ ] <array-name> ;
Where <data-type> is either a basic data type or a class name.
Examples
int [ ] studentIdList;
double [ ] studentScoreList;
char [ ] letterGrades;
String [ ] names;
 You allocate and bind memory locations to a one-dimensional array variable by using the new
operator as follows:
<variable-name> = new <data-type> [ <size-of-array> ];
Examples
studentIdList = new int [ 10 ];
// allocate an array of 10 integer elements
studentScoreList = new double[20];
// allocate an array of 20 double precision elements
names = new String [ 50 ];
// allocate an array of 50 String elements
 You can also allocate and bind memory locations to a one-dimensional array variable in a declaration
statement as follows:
<data-type> [ ] <variable-name> = new <data-type> [ <size-of-array> ];
Example
int [ ] studentIdList = new int [ 10 ];
// allocate an array of 10 integer elements
 A one-dimensional array can also be initialized when it is declared as follows:
<data-type> [ ] <variable-name> = { <list-of-values> };
© 2011 Gilbert Ndjatou
Page 29
Example
int [ ] firstPrimes = { 2, 3, 5, 7, 11, 13, 17, 19 };
String [ ] firstNames = { “John”, “Mark”, “Paterson”, Joe”, “Peter”, “Pat”, “Allan” };
 The size (number of elements) of an array is accessed by using the length member variable.
Example
int size1 = firstPrimes.length;
// size1 is set to 8
int size2 = firstNames.length;
// size2 is set to 7
Accessing and Processing the Elements of a one-Dimensional Array
 The elements of a one-dimensional array are accessed and processed in Java in the same way that
they are accessed and processed in C++.
Example
/*----- code segment to compute the sum of the elements of the array first Primes---*/
int total = 0;
for ( int i = 0; i < firstPrimes.length; i ++ )
total + = firstPrimes [ i ];
Copying Arrays
 The method arraycopy of the class System is provided in the standard Java library to copy the
elements of a one-dimensional array into another one of the same data type. It is specified as
followed:
System.arraycopy ( <array-from>, <from-index>, <array-to>, <to-index>, <count> );
Where
<array-from>
is the array to copy from
<from-index>
is the starting index to copy from
<array-to>
is the array to copy to
<to-index>
is the starting index to copy to
<count>
is the number of element to copy
© 2011 Gilbert Ndjatou
Page 30
Example
char [ ] copyFrom = { ‘d’, ‘e’, ‘c’, ‘a’, ‘f’, ‘f’, ‘e’, ‘i’, ‘n’, ‘a’, ‘t’, ‘e’, ‘d’ };
char [ ] copyTo = new char [ 7 ];
System.arraycopy( copyFrom, 2, copyTo, 0, 7 );
// set array copyTo as follows: copyTo[0] = ‘c’, copyTo[1] = ‘a’, copyTo[2] = ‘f’,
// copyTp[3] = f’, copyTo[4] = ‘e’, copyTo[5] = ‘i’, and copyTo[6] = ‘n’
 An array variable behaves like a C++ pointer variable. So, if you assign one array variable to another
one using the assignment operator, both variables will refer to the array allocated for the assigned
variable.
Example
char [ ] copyFrom = { ‘d’, ‘e’, ‘c’, ‘a’, ‘f’, ‘f’, ‘e’, ‘i’, ‘n’, ‘a’, ‘t’, ‘e’, ‘d’ };
char [ ] copyTo;
copyTo = copyFrom;
// The above array now has two names: copyTo and copyFrom
// copyTo[i] and copyFrom[i] are interchangeable in any expression.
The statement:
copyTo[i] = ‘a’;
has the same effect as
copyFrom[i] = ‘a’;
We have the following memory representation after the assignment operation is performed:
copyFrom
d
e
c
a
f
f
e
i
n
a
t
e
d
copyTo
Enhanced for Statement
 The enhanced for statement iterates through the elements of an array (one-by-one starting with the
first element) without using a counter.
 It syntax is as follows:
for( <data-type> <parameter> : <array-name> )
<Statement>
Where:
<array-name> is the name of the array
<data-type>
is a data type that is consistent with the data type of the elements in the array.
<parameter>
represents successive elements of the array, starting with the first.
© 2011 Gilbert Ndjatou
Page 31
Examples
/*----- code segment to compute the sum of the elements of the array firstPrimes ---*/
int total = 0;
for ( int element : firstPrimes )
total + = element;
System.out.println(“The sum of the first Primes is:\t” + total );
/*----- code segment to print the names in the array firstNames ---*/
for ( String element : firstNames )
System.out.println( element );
 The enhanced for statement can only be used to access the values of the elements on an array: it
cannot be used to modify the values of the elements of an array. The following code segment will
generate an error:
/*----- invalid code segment to read values into an array ---*/
int [ ] list = new int [ 10 ];
for ( int element : list )
element = input.nextInt( );
Arrays as Parameters or Returned Values of Methods
 In Java, a one-dimensional array is passed and processed in a method in the same way that a onedimensional array is passed and processed in a function in C++, except that you do not have to pass
the size of the array. Also, the argument that corresponds to a one-dimensional array in a method
call is the name of an array as in a function call in C++.
 In Java, a method can return a one-dimensional array variable which is not the case for a function in
C++.
Example
/*------------------------------- Method arraySum --------------------------------------*/
/* receives as argument an array of integer values and computes and returns
the sum of its members
*/
static int arraySum( int [ ] list )
{
int total = 0;
for ( int i = 0; i < list.length; i ++ )
total + = list[i];
return ( total );
}
© 2011 Gilbert Ndjatou
Page 32
/*-------------------------------------- Method array5Incr --------------------------------------*/
/* receives as argument an array of integer values and adds 5 to each of its members */
static void array5Incr( int [ ] list )
{
for ( int i = 0; i < list.length; i ++ )
list[i] + = 5;
}
/*------------------------------------------- Method addAarrays ----------------------------------------------*/
/* receives as arguments two arrays of integer values with the same size, adds their corresponding
elements, and stores the result in the corresponding element of a third array that it then returns */
static int [ ] addArrays( int [ ] list1, int[ ] list2 )
{
int size = list1.length;
int [ ] temp = new int [size];
for ( int i = 0; i < size; i ++ )
temp[i] = list1[i] + list2[i];
return ( temp );
}
 Some examples of method calls of these methods follow:
int [ ] valuesList1 = { 21, 25, 32, 45, 15, 8, 13, 35, 1, 17 },
valuesList2 = { 12, 52, 23, 54, 51, 8, 31, 53, 1, 71 },
valuesList3;
int sum;
// to hold the sum of the values in array valuesList1
/*--------------- compute and print the sum of the elements of array valuesList1 ----------*/
sum = arraySum( valuesList1 );
System.out.println( “The sum of the elements is:\t” + sum );
/*-------------------------- Add 5 to each element of array valuesList2 -----------------------*/
Array5Incr( valuesList2 );
/*-Add corresponding elements of arrays valuesList1 and valuesList2 and store the result in the corresponding
element of array valuesList3 ----------------------------------------------------------------------------------------------*/
valuesList3 = addArrays( valuesList1, valuesList2 );
© 2011 Gilbert Ndjatou
Page 33
Two-Dimensional Arrays
 Similarly to one-dimensional arrays, a two-dimensional array variable is a reference variable: it is
an explicit/implicit heap dynamic variable.
 It is declared as follows:
<data-type> [ ][ ] <array-name> ;
Where <data-type> is either a basic data type or a class name.
Examples
int [ ][ ] studentScores;
double [ ][ ] totalSales;
char [ ][ ] document;
String [ ][ ] namesTable;
 You allocate memory locations for a two-dimensional array variable by using the new operator as
follows:
<variable-name> = new <data-type> [ <rows> ][ <columns> ];
Examples
studentScores = new int [10][ 5 ]; // allocate an integer array of 10 rows and 5 columns
totalSales = new double [ 15][10]; // allocate a double precision array of 15 rows and 10 columns
document = new char [25][80];
// allocate an character array of 25 rows and 80 columns
namesTable = new String [10 ][5];
 You can also allocate memory locations for a two-dimensional array variable in a declaration
statement as follows:
<data-type> [ ][ ] <variable-name> = new <data-type> [ <rows> ][ <columns> ];
Example
int [ ][ ] studentScores = new int [10][ 5 ];
© 2011 Gilbert Ndjatou
// allocate an integer array of 10 rows and 5 columns
Page 34
 A two-dimensional array can also be initialized when it is declared as follows:
<data-type> [ ][ ] <variable-name> = { { <list-of-values-for-each-row> } };
Example
int [ ][ ] labScores = { { 8, 9, 7, 8, 10 },
{ 9, 8, 8, 8, 7 },
{ 8, 7, 9, 9, 10 }
};
String [ ][ ] students = {
{“John”, “Mark”, “Paterson” },
{ “Joe”, “Peter”, “Pat” },
{ “Dave”, “Bonnie”, “Pat” },
{ “Allan”, “Amy”, “Ellen” }
};
 When you create a two-dimensional array, the number of elements in a row does not have to be the
same for all the rows.
Example
int [ ] [ ] pascalTriangle5 = { { 1 },
{ 1, 1 },
{ 1, 2, 1 },
{ 1, 3, 3, 1},
{ 1, 4, 6, 4, 1 },
{ 1, 5, 10, 10, 5, 1} };
Note that each row i (0 <= i <= 5) of the above pascalTriangle5 array has i +1 columns.
 As in C++, a two-dimensional array in Java is in fact a one-dimensional array of one-dimensional
arrays that are its rows.
 When you allocate memory locations for a two-dimensional array, extra memory locations are
allocated for the one-dimensional array whose elements reference the rows of the two-dimensional
array.
© 2011 Gilbert Ndjatou
Page 35
Example
The allocation of the memory locations for the array: int [ ][ ] table = new int [ 5 ][ 4 ]; follows:
table
table [0]
table [1]
table [2]
table [3]
table [4]
table[0] is a one-dimensional array with four elements:
table[0][0], table[0][1], table[0][2], and table[0][3].
table[1] is a one-dimensional array with four elements:
table[1][0], table[1][1], table[1][2], and table[1][3].
table[2] is a one-dimensional array with four elements:
table[2][0], table[2][1], table[2][2], and table[2][3].
table[3] is a one-dimensional array with four elements:
table[3][0], table[3][1], table[3][2], and table[3][3].
Table[4] is a one-dimensional array with four elements:
table[4][0], table[4][1], table[4][2], and table[4][3].
Accessing and Processing the Elements of a two-Dimensional Array
 You access and process the elements of a two-dimensional array in Java in the same way that the
elements of a two-dimensional array are accessed and processed in C++.
Example
Given the following two-dimensional array that holds 5 lab scores of 7 students:
int [ ][ ] labScores = { { 8,
{ 9,
{ 8,
{ 9,
{ 8,
{ 9,
{ 9,
};
© 2011 Gilbert Ndjatou
9, 7, 8, 10 },
8, 8, 8, 7 },
7, 9, 9, 10 }
10, 6, 8, 8 },
8, 8, 7, 9 },
9, 9, 9, 9 },
8, 8, 8, 9 }
Page 36
The following code segment computes the average lab score of each student and the next one computes
the average lab score of each lab:
/*---------- code segment to compute the average lab score of each student -----*/
int total;
for ( int st = 0; st < labScores.length; st ++ )
{
total = 0;
for( int lct = 0; lct < labScores[ st ].length; lct ++ )
total + = labScores[st] [lct];
System.out.println( “Average score of student:\t” + (st +1) + “ is:\t” + (total / lct) );
}
/*---------- code segment to compute the average lab score of each lab assignment -----*/
int total;
for ( int lct = 0; lct < 5; st ++ )
{
total = 0;
for( int st = 0; st < 7; st ++ )
total + = labScores[st] [lct];
System.out.println( “Average score of lab:\t” + (lct +1) + “ is:\t” + (total / 7) );
}
The code segment to compute the average lab score of each student can be rewritten using the enhanced
for statement as follows:
/*---------- code segment to compute the average lab score of each student -----*/
int total,
student = 1;
for ( int [ ] scoreList : labScores )
// process the array row-by-row
{
total = 0;
for( int score : scoreList )
// add all the test scores of the current student
total + = score;
System.out.println( “Average score of student:\t” + ( student ) +“ is:\t” + (total / scoreList.length ) );
student ++ ;
}
 A two-dimensional array variable can be assigned to another two-dimensional array variable with the
same data type. But as with one-dimensional array variables, both variables will refer to the same
array.
© 2011 Gilbert Ndjatou
Page 37
Two-Dimensional Arrays and Methods
 In Java, a two-dimensional array is passed and processed in a method in the same way that a twodimensional array is passed and processed in a function in C++, except that you do not have to
specify the number of columns in the array with the parameter and you do not have to pass the
number of rows as a parameter.
 Note that if the two-dimensional array is processed row by row, you do not need to pass the number
of columns in each row to the method.
 The argument that corresponds to a two-dimensional array in a method call is the name of a twodimensional array as in a function call in C++.
 In Java, a method can return a two-dimensional array variable which is not the case for a function in
C++.
Example
The method that follows receives a two-dimensional array as parameter, and then computes and prints
the sum of each of its rows. Note that all rows do not need to have the same number of columns.
static void computeRowSum( int [ ][ ] table )
{
int sum;
for( int row = 0 ; row < table.length ; row ++ )
{
int col;
for( sum=0, col = 0 ; col < table[row].length ; col ++ )
sum += table[row][col];
System.out.println( sum );
}
}
This method is called in method main as follows:
public static void main( String [ ] args )
{
int [ ][ ] valuesTable = { {1, 2, 3}, {2, 3, 4}, {3, 4, 5}, {4, 5, 6}, {5,6,7} };
computeTable( valuesTable );
}
© 2011 Gilbert Ndjatou
Page 38
Executing a Program with a Command Line Arguments
 The general syntax of the command to execute a Java program is as follows:
java <bytecode-file-name> arg0
arg1 arg2 . . . argn
<Enter>
Where arg0, arg1, . . . argn are the command line arguments.
 the parameters of method main are set as follows:
args[0]
is set to arg0,
args[1] is set to arg1,
. . .
Args[n] is set to argn
Example P8
using a command line arguments
Given the following command line to execute program Program8:
java Program8 Banana 25 3.74
We have the following settings of the array args:
args[0]
Banana
args[1]
25
args[2]
3.74
/*----------------------------------------------- Program8 ----------------------------------------------*/
/* Using command line arguments
*/
public class Program8
{
public static void main( String [ ] args )
{
int quantity;
// to hold the quantity of the product
double uprice;
// to hold its unit price
/*---- stop the execution if the user did not type three arguments in the command line---*/
if( args.length != 3 )
{
System.out.println( “This program is terminated!”);
System.out.println(“Because you did not enter the proper number of arguments”);
return;
}
© 2011 Gilbert Ndjatou
Page 39
/*----------convert strings for the quantity and the unit price to their values ------------------*/
quantity = Integer.parseInt( args[1] );
uprice = Double.parseDouble( args[2] );
/*------------------Compute and print the price of the product -----------------------------------*/
System.out.println( “The price of the” + args[0] +” is:\t” + ( quantity * uprice ));
}
}
© 2011 Gilbert Ndjatou
Page 40
Source Modules with Two or More Classes
 A Java program source module may contain two or more classes.
 In a source module with two or more classes, a class (static) variable or a class (static) method
defined in one class can be specified in another class by preceding its name with the name of the
class in which it is defined followed by a period.
 When a source file contains two or more classes, the Java compiler creates a bytecode file for each of
the classes in that source file: the bytecode file of a class has the same name as that class with the
filename extension .class.
 You execute a program by executing the bytecode file of the class that contains the method main.
Example P9
Program with two classes (each one with class methods) in a source file
/*------------------------------------------------------- Program9 -----------------------------------------------------------*/
/* Read two integer values, compute their product, and the quotient and the remainder in the division
of the first value by the second
*/
import java.util.Scanner;
public class Program9
{
static int quotient;
static int remain;
// to hold the quotient
// to hold the remainder
public static void main( String [ ] args )
{
Scanner input = new Scanner( System.in );
int first,
second;
// for standard input
// to hold the first value
// to hold the second
/*-------------------------------read the two values -------------------------------*/
first = input.nextInt( );
second = input.nextInt( );
/*---------------------------Compute and print their product--------------------------------*/
System.out.println(“Their product is:\t” + Program9Methods.computeProd( first, second ) );
/*-------------------Compute and print the quotient and the remainder-------------------*/
if( second == 0 )
System.out.println( “Division by zero is not allowed!”);
else
{
Program9 Methods.computeQuotRem( first, second );
System.out.println(“The quotient is:\t” + quotient );
System.out.println(“The remainder is:\t” + remain );
}
}
}
/*---- end of class Program9------*/
© 2011 Gilbert Ndjatou
Page 41
class Program9Methods
{
/*---------------------------------------Method computeProd( )--------------------------------------*/
/* compute the product of two integer values and returns it
*/
static int computeProd( int num1, int num2)
{
return num1 * num2;
}
/*---------------------------------------Method computeQuotRem( )--------------------------------------*/
/* compute the quotient and the remainder in the division of the first argument by the second
*/
static void computeQuotRem( int num1, int num2)
{
Program9.quotient = num1 / num2;
Program9.remain = num1 % num2;
}
}
 You call an instance method in a class (static) method or an instance method from another
class as follows:

First define and initialize a reference variable with an object of the class that contains the
instance method.

Follow that variable by a dot (.) which is followed by the name of that method to call it.
Example P10
Program with two classes (one with instance methods) in a source file
/*------------------------------------------ Program10.java file ---------------------------------------------------*/
/* Read two integer values, compute their product, and the quotient and the remainder in the division
of the first value by the second
*/
import java.util.Scanner;
public class Program10
{
static int quotient;
static int remain;
// to hold the quotient
// to hold the remainder
public static void main( String [ ] args )
{
Scanner input = new Scanner( System.in );
int first,
second;
© 2011 Gilbert Ndjatou
// for standard input
// to hold the first value
// to hold the second
Page 42
/*-------------------------------read the two values -------------------------------*/
first = input.nextInt( );
second = input.nextInt( );
Program10Methods objectRef = new Program10Methods ( );
/*---------------------------Compute and print their product--------------------------------*/
System.out.println(“Their product is:\t” + objectRef.computeProd( first, second ) );
}
/*-------------------Compute and print the quotient and the remainder-------------------*/
if( second == 0 )
System.out.println( “Division by zero is not allowed!”);
else
{
objectRef.computeQuotRem( first, second );
System.out.println(“The quotient is:\t” + quotient );
System.out.println(“The remainder is:\t” + remain );
}
}
/*---- end of class Program10------*/
/*-------------------------------------- class Program10Methods ------- ------------------------------------------*/
/* Contains the instance methods called in method main in class Program10
*/
class Program10Methods
{
/*---------------------------------------Method computeProd( )--------------------------------------*/
/* compute the product of two integer values and returns it
*/
int computeProd( int num1, int num2)
{
return num1 * num2;
}
}
/*---------------------------------------Method computeQuotRem( )--------------------------------------*/
/* compute the quotient and the remainder in the division of the first argument by the second
*/
int computeQuotRem( int num1, int num2)
{
Program10.quotient = num1 / num2;
Program10.remain = num1 % num2;
}
/*---- end of class Program10Methods------*/
© 2011 Gilbert Ndjatou
Page 43
Programs with two or more Source Files
 A Java program may consists of two or more source files.
 The bytecode file of each class of the program is created by compiling each source file.
 However, a source file that contains a class that is referenced in another one that is already compiled
will also be compiled automatically.
 For example, the source file Program11Methods.java of Example P11 below will be automatically
compiled after you issue the command to compile the source file Program11.java.
Example P11
Program with two or more source files
/*------------------------------------------ Program11.java file ---------------------------------------------------*/
/* Read two integer values, compute their product, and the quotient and the remainder in the division
of the first value by the second
*/
import java.util.Scanner;
public class Program11
{
static int quotient;
static int remain;
// to hold the quotient
// to hold the remainder
public static void main( String [ ] args )
{
Scanner input = new Scanner( System.in );
int first,
second;
// for standard input
// to hold the first value
// to hold the second
/*-------------------------------read the two values -------------------------------*/
first = input.nextInt( );
second = input.nextInt( );
/*---------------------------Compute and print their product--------------------------------*/
System.out.println(“Their product is:\t” + Program11Methods.computeProd( first, second ) );
/*-------------------Compute and print the quotient and the remainder-------------------*/
if( second == 0 )
System.out.println( “Division by zero is not allowed!”);
else
{
Program11Methods.computeQuotRem( first, second );
System.out.println(“The quotient is:\t” + quotient );
System.out.println(“The remainder is:\t” + remain );
}
}
}
/*---- end of class Program11------*/
© 2011 Gilbert Ndjatou
Page 44
/*-------------------------------------- Program11Methods.java file ------------------------------------------*/
/* Contains the class methods called in the source file Program11
*/
public class Program11Methods
{
/*---------------------------------------Method computeProd( )--------------------------------------*/
/* compute the product of two integer values and returns it
*/
static int computeProd( int num1, int num2)
{
return num1 * num2;
}
/*---------------------------------------Method computeQuotRem( )--------------------------------------*/
/* compute the quotient and the remainder in the division of the first argument by the second
*/
static int computeQuotRem( int num1, int num2)
{
Program11.quotient = num1 / num2;
Program11.remain = num1 % num2;
}
} /*---- end of class Program11Methods ------*/
© 2011 Gilbert Ndjatou
Page 45
Packages and the import Statement
 A package is a named collection of related classes.
 Packages are used to organize classes so that they can be reused in future programs without access to
their source codes.
 Java predefined classes that are collectively referred to as Java class library, or the Java
Application Programming Interface (Java API) are grouped into packages. A subset of Java API
packages is provided in the table that follows:
Package
Description
Java.applet
Contains a class and several interfaces required to create java applets.
Contains the classes and the interfaces required to create and manipulate GUIs in early versions of
java.
Contains classes and interfaces that enable events handling for GUI components in both java.awt
and javax.swing packages.
Contains classes and interfaces for working with java’s advanced two-dimensional graphics
capabilities.
Contains classes and interfaces that enable programs to do data I/O.
Contains classes and interfaces that are required in many java programs.
Contains classes and interfaces that enable programs to communicate via computer networks like
the internet.
Contains classes and interfaces for working with databases.
Contains classes and interfaces that enable such actions as date and time manipulations, randomnumber processing, and processing of large amounts of data.
Contains utility classes and interfaces for implementing programs that perform multiple tasks in
parallel.
Contains classes and interfaces for working with java’s multimedia capabilities.
Contains classes and interfaces for working with java’s Swing GUI components that provide
support for portable GUIs.
Contains classes and interfaces that enable event handling for GUI components in package
javax.swing.
Contains classes and interfaces for working with web services in java.
Java.awt
Java.awt.event
Java.awt.geom
Java.io
Java.lang
Java.net
Java.sql
Java.util
Java.util.concurrent
Java.media
Java.swing
Javax.swing.event
Javax.xml.ws
 To each Java package is associated a directory or folder that contains the bytecode file of each of
the classes in that package.
 Classes in the java.lang package are automatically included in every Java program.
 However, in order to use any of the classes in the Java API, you must use one of the following three
methods:
a.
Use the entire path with the class name.
b. Import the class.
c. Import the package of which the class you are using is a part.
© 2011 Gilbert Ndjatou
Page 46
 The syntax of the import statement to include a class in a program is specified as follows:
import <pathname-with-the-class-name>;
Example:
import java.util.Scanner;
Will include the class Scanner (from the package java.util) in the program.
 The syntax of the import statement to include all the classes in a package in a program is specified
as follows:
import <pathname-of –of-the-package>.*;
Example:
import java.util.*;
Will include all the classes in the package java.util in the program.
 You must place the import statement before any executable statement in a program.
 There is no disadvantage to include extra classes in a program:
The object of the import statement is simply to notify the compiler that you will be using the
variables and methods that are in the included classes.
Example
The class Scanner of the Java API package java.util contains useful methods to deal with input in a
program. The object input of the class Scanner (on which input will be performed) can be instantiated in
one of the following ways:
1. Instantiate the object using the entire path with the class name:
java.util.Scanner input = new java.util.Scanner( System.in );
2. First import the class Scanner in your program:
Then instantiate the object as follows:
import java.util.Scanner;
Scanner input = new Scanner( System.in );
3. First import all the classes in the package java.util in your program:
Then instantiate the object as follows:
© 2011 Gilbert Ndjatou
import java.util.*;
Scanner input = new Scanner( System.in );
Page 47
Creating and Using Packages
 By using a package, you can create a class that other programmers can use in their applications, but
without having access to its source code.
 The following are the steps for defining and placing a class in a package:
1. Declare the class as a public class: a class that is not public can be used only by other classes in
the same package.
2.
Choose a unique package name.
3. Add the package statement to the source file that contains the class.
4. Compile the class source file: the corresponding bytecode file will be placed in the package
directory/folder.
 Because Java applications are used on the internet, Sun Microsystems (Oracle) has defined a
convention for giving a unique name to packages in which you use your internet domain in reverse
order. For example, at William Paterson University, a package name will start with edu.wpunj.
 An example of a package names (at William Paterson University) is:
edu.wpunj.cs.ndjatou.mypackage.
 The name of a package corresponds to the pathname of the directory (folder) that will contain the classes
that are placed in it.
 For example, the classes that are placed in the package ndjatou.mypackage will be stored on a Windows
computer in the folder (directory) with pathname: ndjatou/mypackage.
Package Statement
 The syntax of the package statement is:
Example:
package <package-name>;
package ndjatou.mypackage;
 The package statement indicates to the compiler that the (public) class declared in the source file is part
of the specified package.
 The package statement must appear at the beginning of the source file, outside of the class definition.
 A Java source file must have the following order:
1. A package statement (if any),
2. Import statements (if any), then
3. Class definitions.
© 2011 Gilbert Ndjatou
Page 48
Compiling a Packaged Class
 When you compile a Java source file that holds a class to be placed in a package, you use the javac
command-line option –d to specify where the first directory (folder) in the package name will be stored.
Example
Suppose that the package statement
package ndjatou.mypackage;
appears at the beginning of the source file Program12Methods.java
Then the command
javac -d E:\ Program12Methods.java
Will do the following:
 create the folder ndjatou in the root directory of drive E (my flash drive);
 create the folder mypackage inside folder ndjatou;
 strore Program12Methods class file (Program12Methods.class) inside folder mypackage.
Example P12.a
Creating a Package
/*-------------------------------------- Program12Methods.java file ------------------------------------------*/
/* Contains the class to be placed in the package edu.wpunj.ndjatou.mypackage
*/
package ndjatou.mypackage;
public class Program12Methods
{
/*---------------------------------------Method computeProd( )--------------------------------------*/
/* compute the product of two integer values and returns it
*/
public int computeProd( int num1, int num2)
{
return num1 * num2;
}
} /*---- end of class Program12Methods ------*/
The command:
javac -d E:\ Program12Methods.java
Will create the folder (directory) ndjatou/mypackage in the root directory of the flash drive in drive E
and place the class file Program12Methods.class into it.
© 2011 Gilbert Ndjatou
Page 49
Example P12.b
Using a Package
/*------------------------------------------ Program12.java file ---------------------------------------------------*/
/* Read two integer values, compute their product
*/
import ndjatou.mypackage.Program12Methods;
import java.util.Scanner;
public class Program12
{
public static void main( String [ ] args )
{
Scanner input = new Scanner( System.in );
int first,
second;
// for standard input
// to hold the first value
// to hold the second
/*-------------------------------read the two values -------------------------------*/
first = input.nextInt( );
second = input.nextInt( );
/*---------------------------Compute and print their product--------------------------------*/
Program12Methods objectRef = new Program12Methods ( );
System.out.println(“Their product is:\t” + objectRef .computeProd( first, second ) );
}
}
/*---- end of class Program12------*/
Static Import
 A static import declaration enables you to import the static members of a class or interface so you
can access them with their unqualified names (that means without the class name and the dot (.)) in
your class.
 You import a particular static member in a class by using a statement with the following syntax:
import static package-name.Class-name.static-member-name;
 You import all static members in a class by using a statement with the following syntax:
import static package-name.Class-name.*;
© 2011 Gilbert Ndjatou
Page 50
Example P13.a
Creating a Package
/*-------------------------------------- Program13Methods.java file ------------------------------------------*/
/* Contains the class to be placed in the package edu.wpunj.ndjatou.mypackage
*/
package ndjatou.mypackage;
public class Program13Methods
{
/*---------------------------------------Method computeProd( )--------------------------------------*/
/* compute the product of two integer values and returns it
*/
public static int computeProd( int num1, int num2)
{
return num1 * num2;
}
} /*---- end of class Program13Methods ------*/
The command:
javac -d E:\ Program13Methods.java
Will create the folder (directory) ndjatou/mypackage in the root directory of the flash drive in drive E
and place the class file Program13Methods.class into it.
Example P13.b
Using a Package
/*------------------------------------------ Program13.java file ---------------------------------------------------*/
/* Read two integer values, compute their product
*/
import static ndjatou.mypackage.Program13Methods.*;
import java.util.Scanner;
public class Program13
{
public static void main( String [ ] args )
{
Scanner input = new Scanner( System.in );
int first,
second;
// for standard input
// to hold the first value
// to hold the second
/*-------------------------------read the two values -------------------------------*/
first = input.nextInt( );
second = input.nextInt( );
/*---------------------------Compute and print their product--------------------------------*/
System.out.println(“Their product is:\t” + computeProd( first, second ) );
}
}
/*---- end of class Program13------*/
© 2011 Gilbert Ndjatou
Page 51
Hands-On Exercise P1
Type and execute the programs in Example P12 and Example P13 as follows: name your package
mypackage in the folder that contains your java source files. For example, if the folder that contains
your source files is CS4501, then, the name of the package will be CS4501.myfolder.
Note:
The following static import statements will allows you to call static methods as specified in the
following table:
Import Statement
Method Calls
import static java.lang.Byte.* ;
import static java.lang.Short.* ;
Import static java.lang.Integer.* ;
import static java.lang.Long.* ;
import static java.lang.Float.* ;
import static java.lang.Double.* ;
Byte. parseByte( s )
Short.parseShort( s )
Integer.parseInt( s )
Long.parseLong( s )
Float.parseFloat( s )
Double.parseDouble( s )
Method Calls with the Import
Statement
parseByte( s )
parseShort( s )
parseInt( s )
parseLong( s )
parseFloat( s )
parseDouble( s )
Import static java.lang.String.*;
String.valueOf( num )
String.format( )
valueOf( num )
format( )
© 2011 Gilbert Ndjatou
Page 52
Using a Class as an Abstract Data Type
 In addition to using classes to encapsulate variables and methods, a Java class can also be an
abstract data type (ADT): that means it is a user-defined data type that is used to create groups of
variables that may have different data types called objects as in C++.
 An Instance variable of class is a variable that is defined without the static modifier.
 An instance variable is also referred to as instance field. It corresponds to a class member variable
in C++: an instance of this variable is created for each object of the class.
 A class is an ADT only if it has at least one instance variable. So, class Program12Methods of
Example P12a, and class Program12 of Example P12b above are not ADTs.
 A Java class with instance variables (ADT) can also have instance methods (such as mutators,
accessors and constructors, etc) that correspond to the member functions in C++.
 The class in Example O1 is an example of a class that is an ADT: it has two instance variables, val1
and val2. val1 is a public instance variable, whereas val2 is a private instance variable.
Example O1
public class Demo1
{
public double val1;
private double val2;
// public instance variable
// private instance variable
public double getValue2(void)
{
return (val2);
}
// returns the value of the private instance variable
public void setValue2(double num) // set the value of the private instance variable
{
val2 = num;
}
public double getAverage(void)
// compute the average of both values
{
double total = computeSum( );
return(total / 2);
}
public double computeSum(void)
{
return (val1 + val2 ) ;
}
// compute the sum of both values and return it
}
© 2011 Gilbert Ndjatou
Page 53
Reference Types
 Java types are divided into primitive types and reference types.
 The primitive types are boolean, byte, char, short, int, long, float, and double.
 All non-primitive types such as classes and arrays are reference types.
 A variable of a reference type (also called a reference) is used to store the location of an object in the
computer’s memory. It is initialized by default to the value null.
 You define and initialize a reference variable with the location of an object in one of the following
ways:
a.
<Class-name> <variable-name> = new <Class-name>( );
b.
<Class-name> <variable-name> ;
<variable-name> = new <Class-name>( );
 You specify an object’s instance variable by first writing the name of a reference variable for that
object followed by the period (.) which is followed by the name of that variable.
Example O2
Given the class Demo1 of Example O1, we have the flowing declaration and initialization of reference
variables item1 and item2:
Declaration
Effects in Memory
Demo1 item1= new Demo1( );
item1.val1
item1.val2
Demo1 item2;
item2 = new
Demo1( );
item2.val1
item2.val2
 A private instance variable of a class can only be specified in an instance method of that class.
 A private instance method of a class can be called only by another instance method of that class.
 An instance method of a class can be called by a method that is not an instance method of that class
only on an object.
© 2011 Gilbert Ndjatou
Page 54
Example O3
Given the class Demo1 of Example O1, we define class Demo1Test1 with the class method main as follows:
import java.util.Scanner;
public class Demo1Test1
{
public static void main( String[ ] args)
{
Demo1 item = new Demo1( );
Scanner input = new Scanner( System.in );
int second;
item.val1 = input.nextInt( );
// for standard input
// to hold the value of instance variable val2
// read a value into the public instance variable val1
second = input.nextInt( );
item.setValue2(second);
// set the value of the private instance variable val2
System.out.printf(“\nThe average of:\t” + item.val1 + “ and “ + item.getValue2( ) + “ is:\t”);
/
System.out.printf( item.getAverage( ) );
}
}
Invalid Access to Instance Variables and Instance Methods in Method main
1. item.val2= input.nextInt( );
2. item.computeSum( );
3. getValue2( );
// val2 is a private instance variable
// computeSum is a private instance method
/* in a method that is not a class instance method, an instance method must be called on an
object */
Methods and Reference Types
 A reference type can be the return type of a method: a method can return an object.
Example O4
The following static method reads the values for the two instance variables of an object of the class Demo1
(defined in example O1 above) and then returns that object.
© 2011 Gilbert Ndjatou
Page 55
import java.util.Scanner;
public class Demo1Test2
{
static Demo1 inputValues (void)
{
Demo1 temp = new Demo1( );
Scanner input = new Scanner( System.in ); // for standard input
int second;
// to hold the value of instance variable val2
temp.val1 = input.nextInt( );
// read a value into the public instance variable val1
second = input.nextInt( );
temp.setValue2(second)
// set the value of the private instance variable val2
return (temp);
}
/*----------------------------------- the above function is called as follows ---------------------------*/
Demo1 item;
item = inputValues( );
}
 A reference type can be a parameter of a method: an object can be an argument to a method.
 A method with a reference type as a parameter can modify the values of the instance variables of the
object that it receives as argument.
Example O5
The following static method receives an object of the class Demo1 (defined in example O1 above) as
argument, and adds 3 to the value of each of its instance variables.
public class Demo1Test3
{
static void add3 (Demo1 item)
{
int num;
item.val1 += 3;
num = item.getValue2( );
item.setValue2( num + 3 );
}
/*----------------------------------- the above function is called as follows ---------------------------*/
Demo1 someItem = new Demo1( );
someItem.val1 = 10;
someItem.setValue2 ( 15 );
add3( someItem );
// someItem.value1 = 13 and someItem.value2 = 18
}
© 2011 Gilbert Ndjatou
Page 56
Exercise O1
The class Demo is defined as follows:
class Demo
{
private double val1;
private double val2;
// the first data member
// the second data member
public void setValues(double num1, double num2)
{
val1 = num1;
val2 = num2;
}
public double getValue1(void)
{
return (val1);
}
public double getValue2(void)
{
return (val2);
}
public double getAverage(void)
{
return( (valu1 + valu2) / 2);
}
}
Define the class DemoTest1 with the following methods:
A. Static method addDemo ( ) that receives as arguments two objects of the class Demo and then builds and
returns another object of the class Demo such that the value of each of its member variables is the sum of
the values of the corresponding member variables of its arguments.
B. Static method incrDemo2 that receives as argument an object of the class Demo and increments the value
of each of its member variables by 5.
C. method main that does the following:
1. Declare object item of the class Demo.
2. Read the values for the instance variables of object item, and set their values.
3. Compute the average of the values of the instance variables of object item and print it.
4. Declare object obj1 and set its instance variables to 5 and 7 respectively.
5. Declare object obj2 and set its instance variables to 14 and 9 respectively.
6. Create a third object named objR such that the value of each of its instance variables is the sum of
the values of the corresponding instance variables of objects obj1 and obj2 by calling addDemo ( ).
7. Increment the value of each instance variable of object obj1 by 5 by calling incrDemo( ).
8. Print the values of the instance variables of the objects objR and obj1.
© 2011 Gilbert Ndjatou
Page 57
 A static method with parameters or local variables that are objects of the class in which it is
defined can access the private instance variables of those objects.
Example O6
public class Demo1A
{
public double val1;
private double val2;
// public instance variable
// private instance variable
public double getValue2(void)
{
return (val2);
}
// returns the value of the private instance variable
public void setValue2(double num) // set the value of the private instance variable
{
val2 = num;
}
public void print( )
// output the value of each of the data members
{
System.out.println( “value1 =\t” + val1 );
System.out.println( “value2 =\t” + val2 );
}
/*---- this method receives as arguments two objects of the class Demo1A and returns another object
of the class Demo1A such that the value of each of its instance variables is the sum of the values
of the corresponding instance variables of its arguments ------------------------------------------*/
static Demo1A addDemo1A( Demo1A obj1, Demo1A obj2 )
{
Demo1A objR;
objR.val1 = obj1.val1 + obj2.val1;
objR.val2 = obj1.val2 + obj2.val2;
// access of private instance variables
return( objR );
}
}
 The method addDemo1A is called in method main as follows:
© 2011 Gilbert Ndjatou
Page 58
public class TestDemo1A
{
public static void main( String[ ] args)
{
Demo1A item1 = new Demo1A( )
item2 = new Demo1A( )
itemR = new Demo1A( );
item1.val1 = 10;
item1.setValue2 ( 15 );
item2.val1 = 4;
item2.setValue2 ( 7 );
itemR = Demo1A.addDemo1A( item1, item2 );
itemR.print( );
}
}
Exercise O2
1. Add to the class Demo of Exercise O1 the static method void decrDemo( Demo obj) that subtracts 1 to
the value of each of the instance variables of the object that it receives as argument.
2. Write the definition of the class DemoTest2 with the method main that does the following:
a. Declare object obj1 and set its instance variables to 5 and 7 respectively.
b. Decrement the value of each instance variable of object obj1 by 1 by calling decrDemo( ).
c. Print the value of each of the instance variables of object obj1.
© 2011 Gilbert Ndjatou
Page 59
Constructors
 As in C++, a constructor is a special instance method of a class that is used to initialize the member
variables of the objects of that class.
 A constructor of a class has the following characteristics:
o Its name is the same as the name of the class.
o It has no return type (not even void).
o It may or may not have parameters.
 A class may have more than one constructor.
 In Java, a constructor can only be called with the new operator: you cannot apply a constructor on
an existing object to reset its instance variables as you do in C++.
 The compiler provides a default constructor with no parameters in any class that does not explicitly
include.
 The default constructor initializes the instance variables of an object as follows:

All numeric variables are set to zero.

All Boolean variables are set to false.

All object variables are set to null.
 The instance variables of objects of the class Demo1 of Example O1 are initialized using that class
default constructor.
 Class Demo2 of Example O6 that follows has two constructors: one without parameters and another
one with parameters.
Example O7
public class Demo2
{
public Demo2( )
{
val1 = 0;
val2 = 0;
}
public Demo2( int n1, int n2)
{
val1 = n1;
val2 = n2;
}
public int getFirst( )
{
return val1;
}
© 2011 Gilbert Ndjatou
// default constructor
// constructor
// returns the value of the first member variable
Page 60
public int getSecond( )
// returns the value of the second member variable
{
return val2;
}
public void setValues( int n1, int n2)
// set the values of the variables
{
val1 = n1;
val2 = n2;
}
public void print( void )
{
System.out.println( “First value is:\t” + val1 + “\tSecond value is:\t” + val2 );
}
private int val1;
private int val2;
// instance (member) variable
// instance (member) variable
}
Initializing Objects with Constructors
 When an object is created with the new operator, its instance variables are initialized by calling a
constructor in one of the following ways:
a. <Class-name> <Referenve-Variable-name> = new <Constructor-Call> ;
b.
<Class-name> <Reference-Variable-name> ;
<Reference-Variable-name> = new <Constructor-Call>;
Example O8
Given the class Demo2 defined of Example O7, we have the following definitions and instantiations of
objects:
a. Demo2 item1 = new Demo2( );
// Default constructor call
/* create item1.val1 and itme1.valu2 and set them as follows: item1.val1 = 0, Item1.val2 = 0 */
b. Demo2 item2 = new Demo2( 5, 9 );
// constructor call
/* create item2.val1 and itme2.val2 and set them as follows: item2.val1 = 5, item2.val2 = 9 */
c. Demo2 item3;
item3 = new Demo2( );
// Default constructor call
/* create item3.val1 and itme3.valu2 and set them as follows: item3.val1 = 0, Item3.val2 = 0 */
d. Demo2 item4;
item4 = new Demo2( 7, 3 );
// constructor call
/* create item4.val1 and itme4.val2 and set them as follows: item4.val1 = 7, item4.val2 = 3 */
© 2011 Gilbert Ndjatou
Page 61
Note If your class has a constructor, you must also define its default constructor if you want to use one:
Java does not provide a default constructor for a class that has at least one constructor.
Copying Objects
 A reference variable behaves just like a C++ pointer variable.
 So, if you assign one reference variable to another one using the assignment operator, both variables
will refer to the same object: the one allocated for the assigned variable.
Example
Given the class Demo2 of Example O7 and the assignment that follows, the output will be as
specified below:
Demo2 obj1,
obj2 = new Demo2( 10, 20 );
obj1 = obj2;
/* both variables refer to the same object: you can access that object either using obj1 or obj2 */
/* the statement obj1.setValues( 4, 7 ); is the same as the statement obj2.setValues( 4, 7 ); */
/* and the statement obj2.setValues( 4, 7 ); is the same as the statement obj1.setValues( 4, 7 ); */
Class (Static) Variables and Objects
 A class that is defined as an ADT may also have class or static variables in addition to the instance
variables.
 An object created from a class that has a static variable has its own copy of each instance variable of
that class.
 However, there is only one fixed location for a static variable which is accessible to all the objects of
the class.
 A static variable can be used to keep track of the number of objects that have been created from a
particular class as is shown with the class in the example that follows:
© 2011 Gilbert Ndjatou
Page 62
Example O9
public class Demo3
{
public Demo3( )
{
val1 = 0;
val2 = 0;
objectCount ++ ;
objectNum = objectCount;
}
// constructor without parameters
// increment the number of objects created
// set this object’ s number
public Demo3( int n1, int n2)
{
val1 = n1;
val2 = n2;
objectCount ++ ;
objectNum = objectCount;
}
// constructor
public int getObjectNum( )
{
return objectNum;
}
// returns this object’s number
public int getFirst( )
{
return val1;
}
// returns the value of the first member variable
public int getSecond( )
{
return val2;
}
// returns the value of the second member variable
public void setValues( int n1, int n2)
{
val1 = n1;
val2 = n2;
}
// set the values of the variables
// increment the number of objects created
// set this object’ s number
public void print( void )
{
System.out.println( “First value is:\t” + val1 + “\tSecond value is:\t” + val2 );
}
private int val1;
private int val2;
private int objectNum;
// to hold an object’s number
static int objectCount = 0;
// to count the number of objects of this class
}
© 2011 Gilbert Ndjatou
Page 63
Application
Demo3 obj1 = new Demo3( );
Demo3 obj2 = new Demo3( 10, 20 );
System.out.println( “obj1 number is:\t” + obj1.getObjectNum( ) );
System.out.println( “obj2 number is:\t” + obj2.getObjectNum( ) );
System.out.println( “the number of objects created is:\t” + Demo3.ObjectCount );
output
obj1 number is: 1
obj2 number is: 2
The number of objects created is: 2
Data Validation
 It is in general essential to make sure that the value for an instance variable is a valid data before it is
assigned to that instance variable.
 This can be done in a class definition in one of the following two ways:
1. Define an instance method that does the data validation and that is called to validate a value
before it is assigned to the instance variable.
2. Do the data validation in the corresponding set method. In this case, the set method is called by
any instance method that would like to modify the value of the instance variable.
 When an invalid data is found, one of the following actions can be taken:
1. Print an error message and set the value of the instance variable to a default value.
2. Print an error message and call the exit( ) class (static) method of the class System to terminate
the execution of the program.
exit Library Class (static) Method
Signature:
void exit(int status). // Use status 0 if the program has terminated normally;
// any other value indicate an error.
Operation:
sends its argument to the operating system and terminates the execution of the
program.
© 2011 Gilbert Ndjatou
Page 64
Example O10
 In this example, we define a class to represent a day of a year with the month and day instance variables.
 The instance variable month is an integer variable with values in the range 1 to 12 and
 The instance variable day is a positive integer variable whose maximum value depends on the value of
the month instance variable as specified in the array daysPerMonth of the instance method checkDate( ).
 The static and final array monthList allows us to print the name of a month given its number (the value of
the instance variable month).
 Instance method void inputDate( Scanner scan ) uses the Scanner object that it receives as parameter
to read values for the month and the day instance variables.
 Instance method String getStringDate( ) returns the string consisting of the the name of the month
followed by the day.
 Instance method boolean equalTo(DayOfYear obj) receives an object of this class as a parameter and
compares it to the current object: it returns true if both objects are equal, and false otherwise.
 The instance methods of this class are tested in the method main of the class testDayOfYear.
import java.util.Scanner;
public class DayOfYear
{
private int month;
private int day;
// to hold the month (1 – 12)
// to hold the day (1 – 31)
static final String [ ] monthList = { “ “, “January”, “February”, “March”, “April”, “May”,
“June”, “July”, “August”, “September”, “October”, “November”, “December” };
public DayOfYear( )
{
month = 1;
day = 1;
}
// default constructor
public DayOfYear(int newMonth, int newDay)
{
month = newMonth
day = newDay;
checkDate( );
}
public void inputDate( Scanner scan )
{
// constructor
// use the Scanner object to read the month and the day
month = scan.nextInt( );
// read the month
day = scan.nextInt( );
checkDate( );
// read the day
}
© 2011 Gilbert Ndjatou
Page 65
String getStringDate( )
// returns the string consisting of the month followed by the day
{
return( monthList[ month ] + “ ” + day );
}
public int getMonth( )
{
return ( month);
}
// to return the month
public int getDay( )
{
return ( day);
}
// to return the day
public boolean equalTo( DayOfYear day )
{
return( month == day.month && year == day.year );
}
private void checkDate( )
// to validate the month and the day
{
final int [ ] daysPerMonth = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if ( (month < 1) || (month > 12) || (day < 1) || (day > daysPerMonth [ month ]) )
{
System.out.println( “Invalid date” );
System.exit ( 1 );
}
}
}
Public class testDayOfYear
{
/*------- Program is executed with a month and a day as command line arguments -----*/
public static void main( String [ ] args )
{
DayOfYear today = new DayOfYear( ),
// to hold today’s month and day
johnBirthday = new DayOfYear( 4, 25 );
// set John’s birthday
/*------------------------------------ read today’s month and day ---------------------*/
Scanner input = new Scanner( System.in );
System.out.println( “\nEnter today\’s month and day:\t” );
today.inputDate( input );
/*---------------------------output John’s birthday ----------------------------------------------*/
System.out.println( “John\’s birthday is:\t” + johnBirthday.getStringDate( ) );
© 2011 Gilbert Ndjatou
Page 66
if ( today.equalTo( johnBirthday )
System.out.println( “Happy Birthday John Doe” );
/*------------ output the twelve months of the year ----------------------------------------*/
for( int ct = 1; ct <= 12; ct ++ )
System.out.println( DayOfYear.monthList[ ct ] );
}
}
Exercise O3
A. Define a class named Date with three private instance variables named month (integer), day (integer), and year
(integer) as follows:






This class has a private instance method void checkDate( ) that validates a date as follows:
- The month must be an integer value from 1 to 12.
- The day must be a valid integer value for a given month.
- The year must be an integer value from 1960 to 2016.
Instance method checkDate( ) calls the System.exit( ) method to terminate the execution of the program if any
of the above conditions is not satisfied.
This class default constructor sets the month instance variable to 1, the day instance variable to 1, and the
year instance variable to 1960: The default date is 1/1/1960.
The class constructor with parameters calls function checkDate( ) to check the date after it has set the values
for the instance variables month, day, and year.
The class also has the following public instance methods:
 void inputDate(Scanner scan ) that uses the Scanner object parameter to read the values for the instance
variables, day, month, and year, and then calls function checkDate( ) to check the date.
 String getStringDate( ) that returns the date as a string in the format: month/day/year.
 boolean isEqualTo( Date obj ) that returns true if the value of each instance variable month, day, and
year of the current object is equal to the value of the corresponding instance variable of the object obj.
Otherwise, it returns false.
 int getMonth( ), int getDay( ), and int getYear( ). These instance methods return the value of the
month instance variable, the value of the day instance variable, and the value of the year instance variable
respectively.
The class also has the public static (class) method boolean isGreaterThan(Date obj1, Date obj2 ) that returns
true if obj1.year > obj2.year, and if they are equal, if obj1.month > obj2.month, and if they are equal, if
obj1.day > obj2.day. Otherwise, it returns false.
B. Define a class named TestDate with the method main that does the following:
 It first defines an object with the default date and then outputs this date as a string.
 It defines an object named today and initializes it with today’s date.
 It outputs the message “Today’s day is:\t” followed by today’s date as a string.
 It defines an object named dueDate and then reads values for its instance variables.
 It uses the instance method isEqualTo( ) to compare the object today and dueDay and if they are equal, it
outputs the message “Your project is on time”; otherwise, it uses the method isGreaterThan( ) to compare
these objects again and then output either the message “Your project is late” or “Your project is early” as
appropriate.
 It finally reads or sets an object with an invalid date (for example, 25, 4, 2000).
© 2011 Gilbert Ndjatou
Page 67
Objects as Instance Variables of a Class
 In Java, a class can have objects of other classes as instance variables.
 In C++, special constructs are used to call the constructor for data member objects. But in Java, there is
no need for it because an object variable is a reference to an object that is created somewhere else.
Example O11
 As an example of a class with objects of other classes as instance variables, we define the following
class Employee with the following instance variables:
 first name
- class String
 last name
- class String
 birth day
- class DayOfYear (above)
 hours
- integer
 pay rate
- double precision
 In addition of the constructors, the class also has:
 The instance method read(Scanner scan ) that reads the first name, last name, birth day, hours, and
pay rate of an employee, and
 the instance method String getEmployeeString( ) that returns a string in the following format:
NAME: <lastName + “, “ + firstName>
BIRTH DAY: <string-birth-day>
GROSS PAY: <gross-pay>
 The instance methods of this class are tested in the method main of the class testDayOfYear.
import java.util.Scanner;
public class Employee
{
private String firstName;
private String lastName;
private DayOfYear birthDay;
private int hours;
private double payRate;
// first name (object)
// last name (object)
// birth day (object)
// number of hours of work
// Employee’s pay rate
/*----------------default constructor ----------------------------------*/
/* initialize object instance variables firstName, lastName, and birthDay to null and
instance variables hours and pay rate to 0 */
Public Employee ( )
{
hours = 0;
rate = 0.0;
}
© 2011 Gilbert Ndjatou
Page 68
/*----------------------------------- constructor with parameters -------------------------------*/
Public Employee( string fname, string lname, DayOfYear bday, int hrs, double prate)
{
firstName = fname;
lastName = lname;
birthDay = bday;
hours = hrs,
payRate = prate;
}
/*-------------------------------- Member function getEmployeeString( )---------------------------------*/
/* return the string consisting of the name, birth day and gross pay
*/
public String getEmployeeString( )
{
String st = String.format(“\nNAME:\t%s\nBIRTH DAY:\t%s\nGROSS PAY:\t%f”,
lastName + “, “ + firstName, birthDay.getStringDate( ), (hours * payRate) );
return( st );
}
/*----------------------- Member function read( ) -----------------------------------------------*/
/* read the first name, last name, birth day, hours and pay rate of an object
*/
public void read( Scanner scan )
{
System.out.print( “\n Enter First Name:\t”);
firstName = scan.next( );
System.out.print( “\n Enter Last Name:\t”);
lastName = scan.next( );
System.out.print( “\n Enter Birth Day (month Day):\t”);
birthDay.inputDate( scan );
System.out.print( “\n Enter Hours:\t”);
hours = scan.nextInt( );
System.out.print( “\n Enter Pay Rate:\t”);
payRate = scan.nextDouble( );
}
}
© 2011 Gilbert Ndjatou
Page 69
Public class testEmployee
{
/*------set the following information about a secretary, compute his gross pay and output his information:
first name: “John”; last name: “Doe”; day of birth: 3/25; hours of work: 35; pay rate: 10.75
*/
/*-------------------------Define the object secretary and set his information --------------------------------*/
DayOfYear tempday new DayOfYear(3, 25);
Employee secretary = new Employee( “John”, “Doe”, tempday, 35, 10.75 );
/*------- compute his gross pay and output his information -----------------------------*/
String empst = secretary. getEmployeeString( );
System.out.println( empst );
/*------Read the information about an employee, compute his gross pay and output his information--------*/
Scanner input = new Scanner( System.in );
Employee emp = new Employee( );
emp.read( input );
/*------- compute his gross pay and output his information -----------------------------*/
String empst = emp. getEmployeeString( );
System.out.println( empst );
}
Note:
Object secretary could also be instantiated as follows:
Employee secretary = new Employee( “John”, “Doe”, new DayOfYear(3, 25 ) , 35, 10.75 );
Exercise O4
A. Using the class Date that you defined in Exercise O3, write the definition of the class named Employee with the
following private instance variables:
 first name
- class string
 last name
- class string
 ID number
- integer (the default ID number is 999999)
 birth day
- class Date
 date hired
- class Date
 base pay
- double precision (the default base pay is $0.00)
In addition to the constructors, the class has the following public instance methods:
 void readPInfo(Scanner scan ) that uses the Scanner object parameter to read the values for the instance
variables first name, last name, ID number, birth day, and date of hire.
 void readPayInfo(Scanner scan ) that uses the Scanner object parameter to read the value for the base pay
instance variable.
 String getPInfoString( ) that returns a string in the following format:
NAME: <lastName + “, “ + firstName>
ID NUMBER: <Id-Number>
BIRTH DAY: <string-birth-day>
DATE HIRED: < string-date-hired >
© 2011 Gilbert Ndjatou
Page 70




void setBpay( double newBpay ) that sets the value of the base pay to the new value, newBpay.
double getBpay( ) that returns the value of the base pay instance variable.
double getGpay( ) that returns the value of the gross pay (which is the base pay).
double computeTax( ) that computes the tax deduction on the gross pay and returns it as follows:
If gross pay is greater than or equal to 1000, 20% of the gross pay;
If 800 <= gross pay < 1000, 18% of gross pay
If 600 <= gross pay < 800, 15% of gross pay
Otherwise, 10 % of the gross pay.
 String getPayInfoString( ) that returns a string in the following format:
GROSS PAY: <gross-pay>
TAX DEDUCTION: <tax-deduction>
NET PAY: <Net-pay>
B. Define another class named TestEmployee that contains the method main that does the following:
a. Define an object with default values for the instance variables and then output its personal and pay information
(by calling the instance methods getPInfoString( ) and getPayInfoString( )).
b. Define an object and initialize its instance variables as follows:
John Doe 111111 10/25/1990 11/15/2010 750.00
And then output its personal and pay information (by calling the instance methods getPInfoString( ) and
getPayInfoString( )).
c. Define another object, read its personal and pay information (by calling the methods readPInfo(Scanner scan )
and readPayInfo(Scanner scan )) , and then output its personal and pay information (by calling the instance
methods getPInfoString( ) and getPayInfoString( )).
d. Define another object and instantiate it (or read the values for its instance variables) with an invalid date (date
of birth or date of hire).
© 2011 Gilbert Ndjatou
Page 71
Array of Objects
 In C++ you can define an array of objects of a class only if that class has a default constructor: the
member variables of the elements of an array of objects are all instantiated with the default constructor.
Example
If class DayOfYear of Example O10 was a C++ class, the member variables month and day of each
object element of the following array will be instantiated and set to 1 by the default constructor .
DayOfYear dayList [10];
// dayList[i].month = 1 and dayList[i].day = 1
 However, in Java, an array of objects is just an array of reference variables that need to be instantiated.
 You must follow the steps below to define and instantiate an array of objects:
o First define the array variable.
o Use the new operator to allocate memory locations for the elements of the array. Note that each
indexed-variable of the array is a reference variable.
o Use the new operator again to instantiate and initialize each indexed-variable of the array with a
class constructor.
Example O12
 Given the class DayOfYear that we defined in Example O10,

we define and instantiate the array dayList of 31 objects of this class as follows:
DayOfYear [ ] dayList = new DayOfYear [ 31 ];

We instantiate and initialize the indexed-variable of this array to hold the information about the days
of the month of January as follows:
for ( int day = 1; day <= 31; day ++ )
dayList[ day -1 ] = new DayOfYear( 1, day );

// 31 object indexed-variables are created
// set the days of January
We display the days of January as follows:
for ( int day = 1; day <= 31; day ++ )
{
System.out.println( dayList[ day -1 ]. getStringDate( ));
}
© 2011 Gilbert Ndjatou
Page 72
Exercise O5
Define the class named TestArrayEmployee with the method main that defines an array of 5 objects of the class
Employee that you defined in Exercise O4 and then does the following:
 Read the personal and pay information of each object in the array (by calling the methods readPInfo(Scanner
scan ) and readPayInfo(Scanner scan ))
 Output the personal and pay information of each object in the array (by calling the instance methods
getPInfoString( ) and getPayInfoString( )).
© 2011 Gilbert Ndjatou
Page 73
Arrays as Class Instance Variables
 There are two ways to declare an array as a class instance variable:
o
One way is to declare a fixed size array with memory locations allocated for its elements as in
Example O13.
o The other way is to have a variable-size array with its size declared as another instance variable
and its elements allocated in the class constructors as in Example O14.
Example O13
 This example consists of a class with a one-dimensional array of 12 double precision elements as an
instance variable: each object of this class will therefore have a one-dimensional array of 12 double
precision elements as instance variable.
 This array is used to hold the monthly sales made by a salesman in a year.
 The default constructor of the class initializes the elements of the array to 0.0.
 Class TestSalesPerson1 contains the main method where the instance methods of this class are tested.
/*--------------------------------------class SalesPerson1 ------------------------------------------*/
public class SalesPerson1
{
private double [ ] sales = new double [ 12 ]; // 12 monthly sales figures
public SalesPerson1( )
{
for ( int i = 0; i < 12; i++ )
sales[ i ] = 0.0;
}
// constructor
public void setSales( int mth, double amount ); // set sales for a specific month
{
/*--------- test for valid month and amount values -------------------*/
if ( mth >= 1 && mth <= 12 && amount >= 0 )
sales[ mth - 1 ] = amount;
// adjust for subscripts 0-11
else
// invalid month or amount value
{
System.out.println( "Invalid month or sales figure" );
System.exit( 1 );
}
}
public void printAnnualSales( )
// summarize and print yearly total sale
{
System.out.println( "The total annual sale is:\t $" + totalAnnualSales( ) );
}
© 2011 Gilbert Ndjatou
Page 74
private double totalAnnualSales( );
{
double total = 0.0;
for ( int i = 0; i < 12; i++ )
total += sales[ i ];
return total;
}
// add all monthly sales
// add month i sales to total
}
/*--------------------------------------class TestSalesPerson1 ------------------------------------------------*/
/* This program reads a salesperson’s 12 months sales into the array and computes and prints his yearly total sale
*/
import java.util.Scanner;
public class TestSalesPerson1
{
public static void main( String [ ]args )
{
SalesPerson1 first = new SalesPerson1( ) ;
Scanner input = new Scanner( System.in );
//create a SalesPerson1 object first
// for standard input
/*------------------------read the monthly sales into the array---------------------------------*/
System.out.print( “\n Enter the 12 monthly sales:\n”);
for( int i = 0; i < 12; i++ )
{
double amnt = input.nextDouble( );
first. setSales( i, amnt );
}
/*--------------compute his yearly total sale and print it -----------*/
first.printAnnualSales( );
}
}
© 2011 Gilbert Ndjatou
Page 75
Example O14
 The class in this example has two instance variables:

A one-dimensional array of double precision elements that are not instantiated, and

An integer variable that represents the number of elements in the array.
 This array is used to hold the monthly sales made by a salesman in a year, with the understanding that a
salesman does not have to work all 12 months of the year.
 The constructors of this class do the following:

Set the number of elements in the array (the default number of elements in an array is 12), and

Instantiate the elements of the array, and initialize them to 0.0.
 Class TestSalesPerson2 contains the main method where the instance methods of this class are tested.
/*--------------------------------------class SalesPerson2 ------------------------------------------*/
public class SalesPerson2
{
private int month;
// the number of month of sales
private double [ ] sales;
// array to hold the monthly sales figures
public SalesPerson2( )
//default constructor
{
/*------set the number of months to 12 and instantiate and initialize the elements of the array ---*/
month = 12;
//set the number of months
sales = new double [ 12 ];
for ( int i = 0 ; i < 12 ; i++ )
sales[ i ] = 0.0;
}
public SalesPerson2( int mct )
// constructor
{
/*----------------------------check for valid number of months --------------------------------------------*/
if ( mct < 1 || mct > 12)
// sales are from 1 to 12 month maximum
{
System.out.println( “Invalid number of month” );
System.exit ( 1 );
}
/*------set the number of months and instantiate and initialize the elements of the array ---*/
month = mct;
//set the number of months
sales = new double [ mct ];
for ( int i = 0 ; i < mct ; i++ )
sales[ i ] = 0.0;
}
© 2011 Gilbert Ndjatou
Page 76
public void setSales( int mth, double amount );
// set sales for a specific month
{
/*--------- test for valid month and amount values -------------------*/
if ( mth >= 1 && mth <= month && amount > 0 )
sales[ mth - 1 ] = amount;
// adjust for subscripts 0 - month - 1
else
// invalid month or amount value
{
System.out.println( "Invalid month or sales figure" );
System.exit( 1 );
}
}
public void printAnnualSales( )
// summarize and print yearly total sale
{
System.out.println( "The total annual sale is:\t $" + totalAnnualSales() );
}
private double totalAnnualSales( );
{
double total = 0.0;
// add all monthly sales
for ( int i = 0 ; i < month ; i++ )
total += sales[ i ];
// add month i sales to total
return total;
}
}
/*-----------------------------------------class TestSalesPerson2 ---------------------------------------------------*/
/* This program first reads the number of months of sales, then the amount of sales for each of those months into
the array and computes and prints his yearly total sale
*/
import java.util.Scanner;
public class TestSalesPerson2
{
public static void main( String [ ] args )
{
Scanner input = new Scanner( System.in );
// for standard input
/*------------------------------------- read the number of month of sales -------------------------------------*/
System.out.print( “\n Enter the number of months of sales:\n”);
int count = input.nextInt( );
//create the SalesPerson2 object first with that number of month of sales
SalesPerson2 first = new SalesPerson2( count ) ;
© 2011 Gilbert Ndjatou
Page 77
/*------------------------read the monthly sales into the array---------------------------------*/
System.out.print( “\n Enter the monthly sales:\n”);
for( int i = 0; i < count; i++ )
{
double amnt = input.nextDouble( );
first. setSales( i, amnt );
}
/*--------------compute his yearly total sale and print it -----------*/
first.printAnnualSales( );
}
}
Exercise O6
Write the definition of the class named Score1 with the following private instance variables: first name and last name
(objects of the class String); course name (object of class String); and an array of 5 test scores (double).
 The default constructor (constructor without parameters) initializes the String instance variables to null and the
elements of the array to 0.0.
 The constructor with parameters Score1( String fname, String lname, String courseNum, double[ ] list) initializes
the array of test scores with the values of the elements of another array of 5 elements that is passed to it as an
argument.
In addition to the constructors, it has the following public instance methods:
 double computeAverage( ) that computes the average score,
 void read(Scanner scan ) that uses the Scanner object parameter to read the first name, last name, course name, and
the 5 test scores into the array, and
 void print( ) that outputs the first name, last name, course name, the test scores, and the average test score.
Write the definition of the class TestScore1 with the main method that does the following:
a. Define an object of the class Score1 and initialize it with the default constructor.
b. Use the read method to read values into the instance variables of this object.
c. Use the print method to output the first name, last name, course name, the test scores, and the average test
score of this object.
d. Read the last name, first name, course name, and the 5 test scores into an array and use this information to
define and instantiate an object of the class Score1.
e. Use the print method to output the last name, first name, course name, the test scores, and the average test
score of this object.
© 2011 Gilbert Ndjatou
Page 78
Exercise O7
Write the definition of the class named Score2 with the following private instance variables: first name and last name
(objects of the class String); course name (object of class String); the number of test scores (integer); and an array
variable to hold the test scores (double).
 The default constructor (constructor without parameters) initializes the String instance variables to the null string
and set the number of test scores to 5, allocates memory locations for 5 array elements and initializes them to 0.0.
 The constructor Score2(int numElt) initializes the String instance variables to the null string, sets the number of test
scores to numElt, allocates memory locations for numElt array elements and initializes them to 0.0.
 The constructor with parameters Score2( String fname, String lname, String courseNum, double[ ] list) initializes
the array of test scores with the parameter array, and sets the number of test scores to its size.
In addition to the constructors, it has the following public instance methods:
 double computeAverage( ) that computes the average score,
 void read(Scanner scan ) that uses the Scanner object parameter to read the first name, last name, course name, and
the test scores into the array, and
 void print( ) that outputs the first name, last name, course name, the test scores, and the average test score.
Write the definition of the class TestScore2 with the main method that does the following:
a. Define an object of the class Score2 and instantiate it with the default constructor.
b. Read values into the instance variables of this object.
c. Output the first name, last name, course name, the test scores, and the average test score of this object.
d. Read the number of test scores and use it to define an object of the class Score2 that is instantiated with the
constructor with an integer value parameter.
e. Read values into the instance variables of this object.
f. Output the first name, last name, course name, the test scores, and the average test score of this object.
g. Read the last name, first name, course name, and 10 test scores into an array and use this information to define
and instantiate an object of the class Score2.
h. Output the last name, first name, course name, the test scores, and the average test score of this object.
© 2011 Gilbert Ndjatou
Page 79
Referring to the Current Object with the this Reference
 Java associates with each object the this reference that you can use to explicitly refer to that object in the
body of an instance method of its class.
Using this with Instance Variables
 The most common reason for using the this keyword is because an instance variable is shadowed by a
method or a constructor parameter.
Example O15
In the following definition of class Sample1, we use the this reference to refer to the instance variable of
the current object:
public class Sample1
{
private int value1;
private int value2
public Sample1( )
{
this.value1 = 0;
this.value2 = 0;
}
//default constructor (silly way )
public Sample1( int value1, int value2 )
{
this.value1 = value1;
this.value2 = value2;
}
public int getValue1( void )
// constructor (necessay)
// silly way
{
return ( this.value1 );
}
public int getValue2( void )
{
return( this.value2 ) ;
}
© 2011 Gilbert Ndjatou
// a little bit silly!
Page 80
/*---- this instance method increments the instance variables of the current object by 1
and then returns that object --------*/
public Sample plusPlus( )
{
value1++;
value2++;
return( this );
// not that silly!
}
public static void main( String [ ] args )
{
Sample obj1, obj2;
obj1 = new Sample( 12, 25 );
obj2 = obj1.plusPlus( );
}
}
Using this Keyword with a Constructor
 From within a constructor, you can use the this keyword to call another constructor from the same class.
Example

The following class Sample2 has two instance variables, and three constructors: the default
constructor, the constructor with one parameter, and the constructor with two parameters.

We define the default constructor and the constructor with one parameter by using the this keyword
to call the constructor with two parameters.
public class Sample2
{
private int value1;
private int value2
public Sample2( )
//default constructor
{
this( 0, 0 );
}
public Sample2( int num )
// constructor (with one parameter)
{
this( num, 0 );
}
public Sample1( int num1, int num2 )
// constructor (with two parameters)
{
value1 = num1;
value2 = num2;
}
. . .
}
© 2011 Gilbert Ndjatou
Page 81
Inheritance
 Inheritance is the process by which you create a new class by using all the instance variables and
methods of an existing class and then adding new instance variables and instance methods to them.
 The existing class is known as the super class. It is also called base class or parent class
 The new class is known as the subclass, derived class, or extended class, or child class. It is said
to inherit from the super class, or to extend the super class.
 The definition of a derived class begins like any other class definition, but the name of the class is
followed by the keyword extends followed by the name of the base class.
 Every instance variable or method of the super class becomes an instance variable or method of the
subclass. However, private instance variables and methods are not accessible in the subclass.
 When you write the default constructor of a subclass, you only initialize the additional instance
variables of the class: inherited instance variables are automatically initialized by the default
constructor of the super class.
 When you write a constructor with parameters for the subclass, you must use the super
statement to call a constructor of the super class to initialize the inherited instance variables.
 The super statement is made of the super keyword followed by parentheses in which the required
arguments for the constructor of the super class are passed.
 The super statement must be the first statement in the constructor of a subclass: If it is not present,
then these instance variables are initialized with the default constructor of the super class.
 In the following example, class Person is the super class, and class Student is the subclass.
Example O16
public class Person
{
private String name;
private int age;
public Person( )
{
name = “John Doe”;
age = 1;
}
// default constructor
public Person(String newName, int newAge );
{
name = newName;
age = newAge;
}
// constructor
public String getName( )
{
return( name );
}
© 2011 Gilbert Ndjatou
Page 82
public int getAge(
{
return ( age );
}
)
public void print( );
// print the value of the member variable
{
System.out.println( “name:\t” + name );
System.out.println( “Age:\t” + age );
}
}
public class Student extends
{
private double score;
public Student( )
{
score = 0;
}
Person
// inherits from class Person
// default constructor
// name = “John Doe”, age = 1
public Student(String newName, int newAge, double newScore);
// constructor
{
super( newName, newAge );
// call the Parent class constructor
score = newScore;
}
public char getGrade(
{
char grade;
if( score > 90 )
grade = ‘A’;
else if ( score > 80 )
grade = ‘B’;
else if( score > 70 )
grade = ‘C’;
else if( score > 60 )
grade = ‘D’;
else
grade = ‘F’;
return ( grade );
}
public void print( );
{
System.out.println(
System.out.println(
System.out.println(
System.out.println(
}
)
“name:\t” + getName( ) );
“Age:\t” + getAge( ) );
“Score:\t” + score );
“Grade:\t” + getGrade( ) );
}
© 2011 Gilbert Ndjatou
Page 83
 The following table lists the instance variables and methods of each of the classes above.
Class Person
Class Student
Instance Variables
 name
 age
 name (inherited from class Person, but not accessible)
 age (inherited from class Person, but not accessible)
 score
Instance Methods
 getName
 getAge
 print




getName (inherited from class Person)
getAge (inherited from class Person)
print
(overrides the print method of class Person)
getGrade
Method Overriding
 A method of the subclass is said to override a method of the super class when both methods have
the same name, and the number, order, and type of their parameters are exactly the same.
Example: instance method print of class Student overrides instance method print of class Person.
 If an instance method of the subclass overrides a method of the super class, then it must also have the
same return type as the method of the super class.
 Also, any reference of this method on an object of the subclass will referred to the definition of the
method in the subclass.
Example: the output of the program that follows is:
Output
Name:
Age:
Name:
Age:
Score:
Grade:
Mark Fisher
21
Alan Ford
18
93
A
public class StudentTest
{
Public static void main(String [ ] args)
{
Person per = new Person(“Mark Fisher”, 21);
Student stu = new Student(“Alan Ford”, 18, 93);
per.print( );
Stu.print( );
}
}
© 2011 Gilbert Ndjatou
Page 84
 An overridden instance method of the super class may be called in an instance method of the
subclass by preceding the call statement with the keyword super followed by a period.
Example:
The overridden instance method print of super class Person is called in the instance
method print of the subclass Student to output an object’s name and age as follows:
public void print( );
{
super.print( );
// output a student’s name and age
System.out.println( “Score:\t” + score );
System.out.println( “Grade:\t” + getGrade( ) );
}
The @Override Annotation
 It is always recommended to precede the definition of a method that overrides a method of the super
class with the @Override annotation.
 When this is done, the compiler checks to make sure that this method has the same name, and the
number, order, and type of parameters as the method of the super class and issues an error message
when this is not the case.
Example: Instance method print of subclass Student can then be rewritten as follows:
@Override
public void print( );
{
super.print( );
// output a student’s name and age
System.out.println( “Score:\t” + score );
System.out.println( “Grade:\t” + getGrade( ) );
}
Protected members of a Class
 A protected instance variable/method of a base class is like a private instance variable/method of
that class except that it can be directed accessed in an instance method of its subclasses.
 You make an instance variable/method a protected instance variable/method by preceding its
definition with the keyword protected instead of private.
Example
By making the instance variables name and age of class Person protected instead of private as
follows:
protected String name;
protected int age;
We can write the overridden method print of the class Student as follows:
© 2011 Gilbert Ndjatou
Page 85
public void print( );
{
System.out.println(
System.out.println(
System.out.println(
System.out.println(
}
“name:\t” + name );
“Age:\t” + age );
“Score:\t” + score );
“Grade:\t” + getGrade( ) );
Relationship between a Super Class and a Subclass
 An object of a subclass is also an object of the super class (without the additional instance
variables and instance methods):
 You can assign the reference of an object of a subclass to a reference variable of the super class.

However, you cannot use that reference variable to access the additional instance variables and methods
of the subclass.
Example
The following assignment statement is legal:
Person pers = new Student(“John Peter”, 22, 85);
But the statement:
char grade = pers.getGrade( ));
is illegal because the instance method getGrade is not an instance method of the class Person.
Explicit Casting
 A reference variable of the super class that holds the reference of an object of a subclass can be used
to access an instance variable or instance method of the subclass that is not an instance variable or
method of the super class by using the cast operator as follows:
Example
Given the following assignment statement:
Person pers = new Student(“John Peter”, 22, 85);
The following statements are legal
char grade = ((Student)pers).getGrade( );
or:
Student stu = (Student)pers;
char grade = stu.getGrade( ));
© 2011 Gilbert Ndjatou
Page 86
 A method that is defined to return an object of the super class can return an object of a
subclass without any lost of data.
Example
The following method is legal:
public Person someMethod( )
{
Student stu = new Student( “Mark”, 20, 83);
return( stu );
}
 A method that has a reference variable of the super class as parameter can be called with an
object of a subclass.
Example
Assume given the following method helper:
public static void helper( Person pers )
{
. . .
}
And the following declarations of objects:
Person mypers new Person(“Peter”, 23);
Student stu = new Student(“Bob”, 17, 75);
The following call statements are legal:
helper( mypers );
helper( stu );
 An object of the super class is not an object of a subclass.
 An object of the super class cannot then be used in a program where an object of the subclass is
needed.
Example
The following statement is illegal:
© 2011 Gilbert Ndjatou
Student stu = new Person( “Pat Reely”, 21);
Page 87
Dynamic Binding (Polymorphism)
 When an instance method of the super class is overridden in a subclass,

A call to that instance method does not depend on the reference variable, but on the object
instantiated for that reference variable.

It is bound (at run time) to the definition of the method in the class of that object.
Example
Assume given the following classes named Parent and Child:
class Parent
// class Parent
{
public void helper( )
{
printObject( );
}
public void printObject( )
{
System.out.println("parent");
}
}
class Child extends Parent
{
public void printObject( )
{
System.out.println("child");
}
}
// class Child
Given the following declarations of variables, the calls of the methods printObject and Helper will
produce the output as indicated below:
Parent pobj = new Parent( );
Parent cobj1 = new Child( );
Child cobj2 = new Child( );
Method Calls
pobj. printObject ( );
cobj1. printObject ( );
pobj.helper( );
cobj1.helper( );
cobj2.helper( );
© 2011 Gilbert Ndjatou
Output
parent
child
parent
child
child
Page 88
Also assume given the following definition of the static method newHelper:
static void newHelper( Parent obj )
{
obj. printObject ( );
}
The following calls to the methods newHelper will produce the indicated output:
Method Calls
Output
newHelper ( pobj );
newHelper ( cobj1 );
newHelper ( cobj2 );
parent
child
child
Exercise O8
A. Write the definition of the subclass of class Employee (that you defined in Exercise O4) named BonusEmployee
as follows:
1. It has one additional private instance variable named bonus (double precision) with the default value $0.0.
2. In addition to the constructors, it has the following public instance methods:
double getBonus( void )
that returns the value of the instance variable bonus.
3. Instance method void readPayInfo(Scanner scan ) is overridden in the class BonusEmploye: it now reads the
values for the instance variables base pay and bonus.
4. Instance method double getGpay( ) is overridden in the class BonusEmploye: it now returns the sum of the
value of the instance variable base pay and the value of the instance variable bonus.
5. Instance method String getPayInfoString( ) is overridden in the class BonusEmploye: it returns a string in the
following format:
BASE PAY: <base-pay>
BONUS: <bonus>
GROSS PAY: <gross-pay>
TAX DEDUCTION: <tax-deduction>
NET PAY: <Net-pay>
B. Define the class TestBonusEmployee with the method main( ) that is used to test your class as follows:
1. Method main first defines an object of the class Employee with the default values for its instance variables,
and then prints its personal and pay information.
2. It defines an object of the class BonusEmployee with the default values for its instance variables, and then
prints its personal and pay information.
3. It initializes an object of the class Employee as follows: first name: “John”; last name: “Doe”; ID #: 111111;
Date of birth: 10/ 25/1991; Date of hire: 5/10/2010; and base pay: $1250; and then prints its personal and pay
information.
4. It initializes an object of the class BonusEmployee as follows: first name: “Jobe”; last name: “Daly”; ID #:
222222; Date of birth: 1/ 5/1990; Date of hire: 6/30/2011; base pay: $850; and bonus: $250; then prints its
personal and pay information.
5. It reads the personal and pay information of an object of the class Employee, and then outputs its personal and
pay information.
6. It then reads the personal and pay information of an object of the class BonusEmployee and then outputs its
personal and pay information.
© 2011 Gilbert Ndjatou
Page 89
Exercise O9
Given the class Employee that you defined in Exercise O4 and class BonusEmployee that you defined in Exercise O8,
we define the objects eemp, bemp1, and bemp2 as follows:
Employee eemp = new Employee( );
Employee bemp1 = new BonusEmployee( );
BonusEmployee bemp2 = new BonusEmployee( );
1. Assuming that the input values are typed as followed:
Show the output of the following sequence of statements:
1000
600
500 2000 400 900
Scanner scan new Scanner( System.in );
eemp.readPayInfo( scan );
bemp1.readPayInfo( scan );
bemp2.readPayInfo( scan );
System.out.println( “Gross Pay of eemp=\t” + (eemp.getGpay( ) );
System.out.println( “Gross Pay of bemp1=\t” + (bemp1.getGpay( ) );
System.out.println( “Gross Pay of bemp2=\t” + (bemp2.getGpay( ) );
System.out.println( “Tax of eemp=\t” + (eemp.computeTax( ) );
System.out.println( “Tax of bemp1=\t” + (bemp1. computeTax ( ) );
System.out.println( “Tax of bemp2=\t” + (bemp2. computeTax ( ) );
2. Is the statement double bonus = bemp1.getBonus( ); legal? Explain your answer.
Exercise O10 (extra credit)
A. Write the definition of the derived class of class Employee (that you defined in Exercise O4) named
HourlyEmployee as follows:
1. It has three additional instance variables named hours (integer) and payRate (double precision), and overtime
(double precision). Their default values are 0 for hours, and $0.00 for payRate and overtime.
2. It also has a private instance method void computeBaseOvertimePay( ) that computes the base pay and the
overtime pay as follows:
a. If the value of the instance variable hours is less than or equal to 35, then it does the following:
i.
Set the value of the inherited instance variable base pay to payRate times hours.
ii.
Set the value of the instance variable overtime to 0.00.
b. Otherwise, it does the following:
i.
Set the value of the inherited instance variable base pay to payRate times 35.
ii.
Set the value of the instance variable overtime to payRate times 1.5 times (hours – 35).
3. The constructor with parameters has the following method header:
HourlyEmployee( string fn, string ln, int iD, Date bd, Date hd, int hrs, double prate)
Where hrs represents the number of hours of work and prate the pay rate.
It calls class Employee’s constructor with 0 as the argument for the data member base pay, and then
calls the private instance method computeBaseOvertimePay( ) to set the values of the instance variables
base pay and overtime.
4. In addition to the constructors, it has the following public instance methods:
a. int getHours( void )
returns the value of the data member hours.
b. double getPayRate( void ) returns the value of the data member payRate.
c. double getOvertime( void ) returns the value of the data member overtime.
© 2011 Gilbert Ndjatou
Page 90
5. Instance method void readPayInfo(Scanner scan ) is overridden in the class HourlyEmployee: it now reads the
values of the instance variables hours and payRate, and then calls the private instance method
computeBaseOvertimePay( ) to set the values of the instance variables base pay and overtime.
6. Instance method double getGpay( ) is overridden in the class HourlyEmployee: it now returns the sum of the
values of the instance variables base pay and overtime.
7. Instance method String getPayInfoString( ) is overridden in the class HourlyEmployee: it returns a string in the
following format:
HOURS: <hours>
PAY RATE: <pay-rate>
BASE PAY: <base-pay>
OVERTIME: <overtime>
GROSS PAY: <gross-pay>
TAX DEDUCTION: <tax-deduction>
NET PAY: <Net-pay>
B. Define the class TestHourlyEmployee with the method main that is used to test your class as follows:
1. Function main first defines an object of the class HourlyEmployee with the default values for its instance
variables, and then prints its personal and pay information.
2. It initializes an object of the class HourlyEmployee as follows: first name: “Mark”; last name: “Peter”; ID #:
333333; Date of birth: 1/10/1995; Date of hire: 7/10/2012; hours: 50; and pay rate: $25; then prints its personal
and pay information.
3. It initializes an object of the class HourlyEmployee as follows: first name: “Jane”; last name: “Doe”; ID #:
444444; Date of birth: 10/1/1998; Date of hire: 5/10/2011; hours: 30; and pay rate: $20; then prints its personal
and pay information.
4. It then reads the personal and pay information of an object of the class HourlyEmployee and then outputs its
personal and pay information.
© 2011 Gilbert Ndjatou
Page 91
Final Classes and Methods
 A class declared as final cannot be extended (inherited) and
 A method declared as final cannot be overridden.
 You make a class/method final by placing the keyword final either before or after the access
specifier in the class/method definition.
Example
1.
final public class MyClass
{
. . .
}
2.
public final class MyClass
{
. . .
}
3.
final public void myMethod( )
{
. . .
}
4.
public final void myMethod( )
{
. . .
}
© 2011 Gilbert Ndjatou
Page 92
Class Object
 Class Object is a direct or indirect super class of every Java class (including arrays).
 Its methods are therefore inherited by every Java class or array.
 The class Object defines 11 methods, five of which are used in the context of multithreading.
 The methods that we discuss here are the equals, getClass, and toString methods.
equals Method
 The equals method has the following header:
public boolean equals(Object obj)
 It returns true only if the reference variable on which it is called and the reference variable passed as
argument refer to the same object in memory.
 This method can be overridden in a class so that the contents of the two objects are compared
instead.
getClass Method
 This method has no parameters, and returns an object of the class Class (from the package
java.lang).
 The object that it returns contains the information about the object’s type, including its class name
that is returned by the instance method getName of the class Class.
Example:
Given the following declaration of object stu (where Student is the class defined in Example O16):
Student stu = new Student(“John”, 32, 87);
The output of the statement
System.out.println( stu.getClass( ).getName( ));
is: Student
toString Method
 This method has no parameters, and returns a String representation of the object on which it is
called: this string contains the package name and the name of the object’s class followed by the @
sign and the hexadecimal representation of the object.
 When you specify an object reference in your program where a string is required (such as an
argument to the print( ) or println( ) method or strings concatenation), the toString( ) method is
implicitly called on that object and the String object that it returns is used instead.
© 2011 Gilbert Ndjatou
Page 93
Example:
Given the following instantiation of an object (where Student is the class defined in Example O16):
Student stu = new Student(“John”, 32, 87);
The output of the statement
Also, the statement
System.out.println( stu ));
is: Student@b2fd4e:
String st = “My “ + stu; will assign the string My Student@b2fd4e to st.
 The toString( ) method is in general overridden in order to have a better string representation of the
object.
Example: if it is overridden in the class Student as follows:
@Override
public String toString( )
{
String s =
“\nName=” + name + “\nAge =” + age + “\nScore =” + score + “\nGrade =” + getGrade( );
return( s );
}
Then given the following object instantiation:
Student stu = new Student(“John”, 32, 87);
The output of the following statement System.out.println( stu ));
will be:
Output
Name = John
Age = 32
Score = 87
Grade = B
Exercise O11
1. Override the toString method of the class Date that you defined in Exercise O3: it returns the date as a string
in the format: month/day/year.
2. Override the toString method of the class Employee that you defined in Exercise O4 as follows: it returns a
string in the following format:
NAME: <lastName + “, “ + firstName>
ID NUMBER: <Id-Number>
BIRTH DAY: <string-birth-day>
DATE HIRED: < string-date-hired >
GROSS PAY: <gross-pay>
TAX DEDUCTION: <tax-deduction>
NET PAY: <net-pay>
3. Override the toString method of the class BonusEmployee that you defined in Exercise O8: it returns a string
in the following format:
© 2011 Gilbert Ndjatou
Page 94
NAME: <lastName + “, “ + firstName>
ID NUMBER: <Id-Number>
BIRTH DAY: <string-birth-day>
DATE HIRED: < string-date-hired >
BASE PAY: <base-pay>
BONUS: <bonus>
GROSS PAY: <gross-pay>
TAX DEDUCTION: <tax-deduction>
NET PAY: <net-pay>
4. Define the class TestToString with the method main that defines and instantiate an object of the class Date,
an object of the class Employee, and an object of the class BonusEmployee. It then displays each of these
objects by using the System.out.println( ) method.
5. Given an object named bug, write a statement that will display the name of the class of this object.
© 2011 Gilbert Ndjatou
Page 95
Abstract Classes and Abstract Methods
 You make a class abstract by declaring it with the keyword abstract as follows:
public abstract class Animal
{
// code
}
 You cannot create objects with an abstract class:

The purpose of an abstract class is to provide a superclass from which other classes can inherit and
thus share a common design.
 You declare an abstract method by using a statement that consists of the keyword abstract followed
by the header of the method as follows:
public abstract void move( );
 You make a method abstract when you do not want to provide its implementation.
 A class that contains one or more abstract methods must be declared as abstract.
 Subclasses that inherit an abstract class must provide the implementation of each of the abstract
methods. Otherwise, they must also be declared as abstract.
 Although you cannot create an object of an abstract class, you can declare a reference variable of that
abstract class and then assign to it the reference to an object of a subclass.
 The following example illustrates the use of an abstract class.
Example O17
 A company sales two shapes of tiles (rectangular and triangular) and the price of a tile is the unit price
per square inch times the area of the tile.
 Because the area of each of these types of tiles depends on its shape, we process the information about
these tiles as follows:
o We first design a base abstract class named Tile to represent the information common to all tiles:
- The instance variable unitPrice to hold a tile’s unit price.
- The instance method getUprice that returns the value of the instance variable unitPrice.
- The instance method computeArea which is an abstract method because its definition
depends on the shape of the tile.
- The instance method computePrice that computes and returns the price of a tile, and
- The instance method print that prints the price of a tile.
o We then create derived classes RectangleTile and TriangleTile to represent the information
about each shape of tile.
© 2011 Gilbert Ndjatou
Page 96
public abstract class Tile
{
private double unitPrice;
public Tile( )
{
unitPrice = 2.0;
}
public Tile ( double uprice )
{
unitPrice = uprice;
}
public double getUprice( void )
{
return unitPrice ;
}
public abstract double computeArea( void );
public double computePrice( )
{
double area;
area = computeArea( );
return( unitPrice * area );
}
// abstract method
// calling the abstract method
public void print( void )
{
System.out.println(“The price of the tile is:\t” + computePrice ( ));
}
}
© 2011 Gilbert Ndjatou
Page 97
Derived Classes:
/*-------------------------------- class RectangleTile -------------------------------------------*/
class RectangleTile extends Tile
// inherits class Tile
{
private double length;
private double width;
public RectangleTile( )
{
length = 0.5;
width = 1.0;
}
public RectangleTile(double len , double wth, double uprice )
{
super( uprice );
length = len;
width = wth;
}
public double computeArea( void )
{
return ( length * width );
}
// return the area of a rectangular tile
public void print( void )
{
System.out.println( “The length is:\t” + length );
System.out.println( “The width is:\t” + width);
System.out.println( “The price of the tile is:\t” + computePrice ( ));
}
}
© 2011 Gilbert Ndjatou
Page 98
/*-------------------------------- class TriangleTile -------------------------------------------*/
class TriangleTile extends Tile
{
private double height;;
private double base;
// inherits class Tile
public TriangleTile ( )
{
height = 0.5;
base = 1.0;
}
public TriangleTile (double ht , double bse, double uprice )
{
super( uprice );
height = ht;
base = bse;
}
public double computeArea( void )
{
return ( height * base / 2.0 );
}
// return the area of a triangular tile
public void print( void )
{
System.out.println( “The height is:\t” + height);
System.out.println( “The base is:\t” + base);
System.out.println( “The price of the tile is:\t” + computePrice ( ));
}
}
Exercise O12
Define the class TestTile with the method main that defines the following two objects:
Tile tile1 = new RectangleTile( 3.0, 5.0, 4.0 );
Tile tile2 = new TriangleTile( 2.0, 6.0, 8.0 );
And then outputs the information about these two objects.
© 2011 Gilbert Ndjatou
Page 99
Interfaces
 A Java interface is used to specify what is to be done but not how it is to be done.
 For example, a Vehicle should be capable of performing several tasks such as starting, stopping and
changing speed. All types of vehicles, be it a car or a motorcycle should be capable of doing these tasks.
 In such a case, we can define an interface Vehicle where these various methods are specified but the
definition of these methods are given in the classes like Car and Motorcycle which implement these
interfaces.
 A Java interface consists of only final static variables and abstract methods: no implementation is
provided for the methods.
 You declare an interface as follows:
<access-specifier> interface <interface-name>
{
<abstract-methods-and-final-static-variables>
}
 The interface name follows conventions similar to those followed by class names: the first letter of each
word in an interface is capitalized.
 The access specifier may be either public or unspecified. When stated as public, the interface is
available to all classes. When no access specifier is stated, default access restrictions are applied and the
interface is accessible only from classes within the same package. private and protected access
specifiers cannot be used here.
 Variables in an interface are implicitly final, static and public.
 And the methods are implicitly abstract and public.
 Use of specifiers that overwrite these default specifiers is not allowed.
 The following example shows the interface Vehicle with three abstract methods and a final static
variable CODE.
public interface Vehicle
{
int CODE = 347;
public void start();
public void stop();
public abstract void changeSpeed(int newSpeed);
}
// implicitly static, public, and final
// method is implicitly public and abstract
// method is implicitly abstract
// access specifier and abstract not necessary
 Note that a variable declared in an interface must have an initial value because it is a final variable.
© 2011 Gilbert Ndjatou
Page 100
Implementing an Interface
 A class implements an interface by providing the definition for each of its abstract methods.

A class that implements an interface is defined as follows:
<access-specifier> class <class-name> implements <interface-name>
{
<definitions-of-abstract-methods>
<other-methods-and-variables>
}
 A class that implements an interface may have constructors and other variables and methods.
Example
Class Aeroplane implements the interface Vehicle declared above as follows:
public class Aeroplane implements Vehicle
{
private int maxSpeed;
// the maximum speed of the plane
private int speed;
// the current speed
private String name;
// its name
public Aeroplane( )
{
maxSpeed = 500;
name = “Air Plane”;
}
public Aeroplane( int maxSp, String nme )
{
maxSpeed = maxSp;
name = nme;
}
public void start( )
{
speed = 50;
System.out.println(" Taking off:\t" + (CODE + 10) );
}
public void stop( )
{
speed = 0;
System.out.println(" Taking landing:\t" + (CODE + 10) );
}
© 2011 Gilbert Ndjatou
Page 101
@Override
public void changeSpeed( int newSp )
{
if( newSp > maxSpeed || newSp < 0 )
{
System.out.println( "Invalid speed" );
System.exit( 1 );
}
speed = newSp;
}
public void print( )
{
System.out.println(“The vehicle name is:\t” + name + “\nIts code is:\t” + (CODE + 10));
System.out.println(“Its maximum speed is:\t” + maxSpeed );
}
}
Notes:
a. The @Override annotation may be used before the definition of a method to ensure that we are using the
correct method definition.
b. A variable declared in an interface (such as CODE) becomes a variable of each class that implements
that interface: it can therefore be accessed in the definition of any method of that class.
c. A class that does not implement an interface can access a variable defined in that interface by preceding
its name with the name of the interface as in the following example:
int code= Vehicle.CODE;
d. A class can implement more than a single interface: these interfaces are included in the class declaration
with a comma separated list as shown below.
public class Aeroplane implements Vehicle, AnotherInterface
{
. . .
}
e. A class can extend a superclass in addition to implementing interfaces.
f. An interface can be implemented by more than one class.
g. If a class does not provide the implementations of all the methods declared in the interface, the class
itself should be defined as abstract. These abstract methods can then be defined in classes which extend
this one.
© 2011 Gilbert Ndjatou
Page 102
Interfaces as Data Types
 An interface is also an ADT. However you cannot create objects with an interface.
 You declare a variable with an interface data type to hold the reference of an object of a class that
implements that interface.
Example
Given the interface Vehicle and its class implementation Aeroplane above, the following statements
are legal:
Vehicle myVehicle = new Aeroplane( );
myVehicle.start( );
myVehicle.changeSpeed( 250 );
myVehicle.stop( );
However, the following statement is illegal because print is not a method of the interface Vehicle:
myVehicle.print( );
To be able to call this method, reference variable myVehicle needs to be first cast to an Aeroplane
variable as follows:
(( Aeroplane ) myVehicle).print( );
Or:
Aeroplane myAirPlane = ( Aeroplane ) myVehicle;
myAirPlane.print( );
 A method with return type an interface can return an object of a class that implements that
interface as in the following example:
public Vehicle meth( )
{
. . .
return new Aeroplane();
}
 A method with an interface parameter can be called with an object of a class that implements
that interface as in the following example:
public static void someMethod( Vehicle v )
{
//code
}
// call to the above method
someMethod( new Aeroplane() );
© 2011 Gilbert Ndjatou
Page 103
Note

The above technique of considering an interface as a data type brings out the reason behind the use of an
interface.

One can define a class that contains calls to the methods start( ) and stop( ) on Vehicle objects without
any concerns about the type of Vehicle: an Aeroplane or a Car.

Since only objects of the classes that have implemented the Vehicle interface can be passed to the class,
there is no need to worry if the class has the methods start( ) or stop( ).

However, to use method other than those defined in the interface, the object needs to be cast to an
appropriate type.
Interfaces and Inheritance
 Interfaces can also be extended just like classes by using the extends keyword as follows:
public interface SuperVehicle extends Vehicle
{
// code
}
 The new interface will have all the variables and methods declared in its super interfaces.
 Unlike classes, an interface can extend more than one interface by using a comma separated list as
follows:
public interface SuperVehicle extends Vehicle, anotherInterface
{
// code
}
Note

Inheritance is in general used in the context of interfaces when extending an interface is necessary.

For example, consider that the above Vehicle interface has been implemented by many other developers.
Now, if you add another method to this interface, all the classes created by the other developers would
break as a class when implementing an interface should provide definitions for all the methods that have
been declared in the interface.

The developers will have to modify their classes before they can be used once gain. To avoid such
complication, interfaces are extended when one wishes to modify them by adding new methods.
© 2011 Gilbert Ndjatou
Page 104
Exercise O13
The payroll interface is defined as follows:
public interface Payroll
{
double TAXRATE = 0.15;
double getGrossPay( );
double getDeductions( );
void printDetails( );
}
// tax rate
// to compute and return the gross pay
// to compute and return the deductions
// to output the payroll
A. Write the definition of the class HourlyPay that implements the interface Payroll as follows:
 It has two private instance variables hours (double) and payRate (double).
 The constructor without parameters initializes the instance variable hours to 40 and payRate to 10.00
 It has an additional private instance method double getOverTime( ) that does the following: it returns
1.5 *(hours – 40) * payRate if the value of the instance method hours is greater than 40; and 0 otherwise.
 Instance method getGrossPay( ) returns hours * payRate + overtime.
 Instance method getDeduction( ) returns TAXRATE * gross pay.
 Override the toString method of this class as follows: it uses the String.format( ) static method to create
and return the following string:
PAY RATE:
<pay rate>
HOURS:
<hours>
OVERTIME:
<overtime>
GROSS PAY:
<gross-pay>
TAX DEDUCTION: <tax-deduction>
NET PAY:
<net-pay>
 Public instance method printDetails( ) prints the payroll information above.
B. Write the definition of the class TestHourlyPay with the method main that does the following:
 Define an object and initializes it with the default constructor.
 Call the printDetails( ) method to print its payroll information.
 Define an object and initializes it with the hours 50 and pay rate $12.
 Call the printDetails( ) method to print its payroll information.
Default Interface Methods (Java SE 8)
© 2011 Gilbert Ndjatou
Page 105
Nested Classes
 The Java programming language allows you to define a class within another class. Such a class is
called a nested class and is illustrated as follows:
class OuterClass
{
. . .
static class StaticNestedClass
{
. . .
}
class InnerClass
{
. . .
}
}
 There are two categories of nested classes: static nested classes and non-static nested classes that
are also called inner classes.
Static Nested Classes
 A static nested class is behaviorally a top-level class that has been nested in another top-level class
for packaging convenience:

An outer class can access the instance variables and methods of an enclosed static nested class
only through an object reference.

A static nested class can access the instance variables and methods of the enclosing class only
through an object reference.
 However, static nested class StaticNestedClass enclosed in the class OuterClass is accessed in a
class that is not StaticNestedClass or OuterClass by using the enclosing class name as follows:
OuterClass.StaticNestedClass
For example, you create the object nestedObject of the class StaticNestedClass in a class that is not
StaticNestedClass or OuterClass as follows:
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass( );
© 2011 Gilbert Ndjatou
Page 106
Example

The program that follows consists of three classes: class StaticNestedClass is a static nested class of the
class OuterClass and class StaticNestedClassTest contains the main method which calls the instance
method printProd of the class OuterClass, and then the instance method printSum of the class
StaticNestedClass.

Instance method printProd of the class OuterClass calls the instance method getInnerNum of the class
StaticNestedClass and

Instance method printSum of the class StaticNestedClass calls the instance method getOuterNum of the
class OuterClass.
public class StaticNestedClassTest
{
public static void main(String[ ] args)
{
OuterClass outerObject = new OuterClass( );
outerObject.printProd( );
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass( );
nestedObject.printSum( );
}
}
class OuterClass
{
private int outerNum;
public OuterClass( )
{
outerNum = 5;
}
public int getOuterNum( )
{
return( outerNum );
}
public void printProd( );
{
StaticNestedClass obj = new StaticNestedClass( );
System.out.println( “outerNum * innerNum =\t” + (outerNum * obj.getInnerNum( ) );
}
static class StaticNestedClass
{
private int innerNum;
public StaticNestedClass( )
{
innerNum = 10;
}
© 2011 Gilbert Ndjatou
Page 107
public int getInnerNum( )
{
return( innerNum );
}
public void printSum( )
{
OuterClass obj = new OuterClass( );
System.out.println( “innerNum + outerNum =\t” + (innerNum + obj.getOuterNum( ) );
}
} // end of class StaticNestedClass
} // end of class OuterClass
Notes:

The two statements:
OuterClass outerObject = new OuterClass( );
outerObject.printProd( );
could be replaced with the statement:

(new OuterClass( )). printProd( );
And the two statements:
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass( );
nestedObject.printSum( );
could be replaced with the statement: (new OuterClass.StaticNestedClass( )).printSum( );
Exercise O14
Complete the following program as specified by the inserted comments.
public class Other
{
public static void main(String[ ] args)
{
/*--- 1 ------ write the sequence of statements to call the method innerMethod2 ------------*/
}
}
class OuterClass
{
public void outerMethod( )
{
System.out.println(“outer class”);
/*---- 2 ----- write the sequence of statements to call the method innerMethod1 ------------*/
}
© 2011 Gilbert Ndjatou
Page 108
static class NestedClass
{
public void innerMethod1( )
{
System.out.println(“nested class 1”);
}
public void innerMethod2( )
{
System.out.println(“nested class 2”);
/*---- 3 ----- write the sequence of statements to call the method outerMethod------------*/
}
} // end of class StaticNestedClass
} // end of class OuterClass
Inner Classes
 A non-static nested class is also referred to as an inner class.
 An inner class cannot declare or define any static member.
 An outer class can access the instance variables and instance methods of an enclosed inner class
only through an object reference.
 An inner class method has direct access to the variables and methods of the enclosing outer class.
 You instantiate an inner class in a class that is not the outer class or the inner class itself, by first
instantiating the outer class and then, creating the inner class object within the outer class object as
follows:
OuterClass outerObject = new OuterClass( );
OuterClass.InnerClass innerObject = outerObject.new InnerClass( );
Or:
OuterClass.InnerClass innerObject = (new OuterClass( )).new InnerClass( );
Example

The program that follows consists of three classes: class InnerClass is an inner class of the class
OuterClass and class InnerClassTest contains the main method which calls the instance method display
of the class InnerClass.

Instance method update of the class OuterClass calls the instance method getInnerNum of the class
InnerClass, and

Instance method display of the class InnerClass accesses the instance variable outerNum of the class
OuterClass, and calls instance method printOuterNum of the class OuterClass.
© 2011 Gilbert Ndjatou
Page 109
public class InnerClassTest
{
public static void main(String[ ] args)
{
OuterClass outerObject = new OuterClass( );
OuterClass.InnerClass innerObject = outerObject.new InnerClass( );
innerObject.display( );
}
}
class OuterClass
{
private int outerNum;
public OuterClass( )
{
outerNum = 5;
}
public int getOuterNum( )
{
return( outerNum );
}
public void update( )
{
InnerClass obj = new InnerClass( );
outerNum += obj.getInnerNum( );
}
public void printOuterNum( )
{
System.out.println( “outerNum:\t” + outerNum);
update( );
System.out.println(“\n updated outerNum:\t” + outerNum );
}
class InnerClass
{
private int innerNum;
public InnerClass( )
{
innerNum = 10;
}
public int getInnerNum( )
{
return( innerNum );
}
public void display( )
{
System.out.println( “innerNum + outerNum =\t” + (innerNum + outerNum );
printOuterNum( );
}
} // end of class InnerClass
} // end of class OuterClass
© 2011 Gilbert Ndjatou
Page 110
Notes:

The two statements:
OuterClass outerObject = new OuterClass( );
OuterClass.InnerClass innerObject = outerObject.new InnerClass( );
could be replaced with the statement:
OuterClass.InnerClass innerObject = (new OuterClass( )).new InnerClass( );

And the two statements:
InnerClass obj = new InnerClass( );
outerNum += obj.getInnerNum( );
could be replaced with the statement: outerNum += (new InnerClass( )).getInnerNum( );
Exercise O15
Complete the following program as specified by the inserted comments.
public class Other
{
public static void main(String[ ] args)
{
/*--- 1 ------ write the sequence of statements to call the method outerMethod -------------*/
/*--- 2 ------ write the sequence of statements to call the method innerMethod2 ------------*/
}
}
class OuterClass
{
private int outerNum;
public OuterClass( )
{
outerNum = 20;
}
public int getOuterNum( )
{
return( outerNum );
}
public void outerMethod( )
{
System.out.println(“outer class”);
/*---- 3 ----- write the sequence of statements to call the method innerMethod1 ------------*/
/*-- 4 -- write the sequence of statements to output the value of instance variable innerNum -*/
}
© 2011 Gilbert Ndjatou
Page 111
class InnerClass
{
private int innerNum;
public InnerClass( )
{
innerNum = 15;
}
public int getInnerNum( )
{
return( innerNum );
}
public void innerMethod1( )
{
System.out.println(“nested class 1”);
}
public void innerMethod2( )
{
System.out.println(“nested class 2”);
/*---- 5 ----- write the sequence of statements to call the method outerMethod------------*/
/* 6 - write the sequence of statements to output the value of instance variable outerNum -*/
}
} // end of class InnerClass
} // end of class OuterClass
Anonymous Classes
 An anonymous class is an inner class without a name that you can use to declare and instantiate a
class at the same time.
 You declare and instantiate an anonymous class in one of the following ways:

By extending a super class or

By implementing an interface.
 An anonymous class that implements an interface does not define any constructor.
 Anonymous classes are often used when there is a need to define a class just to use it to define a
single object.
© 2011 Gilbert Ndjatou
Page 112
Declaring and Instantiating an Anonymous Class by Extending a Super
Class
 You declare and instantiate an anonymous class by extending a super class as follows:
new <name-of-super-class> ( <arguments-to-a-constructor> )
{
<Instance methods (not defined in the abstract class)>
<Private-instance-methods, static-variables>
}
Example (extending a super class)
 The following abstract class has two instance methods that are used by a patron to place an order in a
restaurant:
 An object is instantiated with the greeting that the patron will say.
 Method sayGreeting( ) displays the patron’s greeting, and
 Method sayOrder( ) receives as a parameter the name of an order and displays what the patron will
say to place the order.
 Method sayOrder( ) is an abstract method because the patron can say his/her order in any language.
abstract class PlaceAnOrder1
{
private String greeting;
PlaceAnOrder1( String grting )
{
greeting = grting;
}
public void sayGreeting( )
{
System.out.println( greeting );
}
public abstract void sayOrder (String fd );
// abstract instance method
}
 This abstract class is used in the program that follows to instantiate two objects by means of
anonymous classes:
 Object frenchOrder is created to place an order in French, and
 Object englishOrder is created to place an order in English.
© 2011 Gilbert Ndjatou
Page 113
public class TakeOrderClass1
{
static int number = 1;
// outer class
public void main( String [ ] args )
{
/*-------- Define an object to be used to make an order in French------------------ */
PlaceAnOrder1 frenchOrder =
new PlaceAnOrder1 (“Bonjour! Je suis le numero:\t” + (number++))
{
/*---------------definition of the abstract method ----------------*/
public void sayOrder ( String food )
{
System.out.println( “Je veux du “ + food);
}
}
/*-------------------------Make your order in French------------------------------*/
frenchOrder.greeting( );
frenchOrder.sayOrder( “café” );
/*-------- Define and object to be used to make an order in Engish --------------------- */
PlaceAnOrder1 englishOrder =
new PlaceAnOrder1 (“Hello! I am number:\t” + (number++))
{
/*---------------definition of the abstract method ----------------*/
public void sayOrder ( String food )
{
System.out.println( “I would like to have “ + food);
}
}
/*----------------------------Make your order in English----------------------------*/
englishOrder.greeting( );
englishOrder.sayOrder( “coffee” );
}
}
© 2011 Gilbert Ndjatou
Page 114
Declaring and Instantiating an Anonymous Class by Implementing an
Interface
 You declare and instantiate an anonymous class by implementing an interface as follows:
new <name-of-interface> ( )
{
<Instance methods (specified in the interface)>
<Private-instance-methods, static-variables>
}
Example (implementing an interface)
 In this example we use the interface PlaceAnOrder2 with two instance methods that is defined as follows:
public interface PlaceAnOrder2
// interface
{
void sayGreeting( );
void sayOrder( String food );
}
 The methods of this interface are used by a patron to place an order in a restaurant:
 Method sayGreeting( ) displays the patron’s greeting, and
 Method sayOrder( ) receives as a parameter the name of an order and displays what the patron will
say to place the order in any language.
 This interface is used in the program that follows to instantiate two objects by means of anonymous
classes:
 Object frenchOrder is instantiated to place an order in French, and
 Object englishOrder is instantiated to place an order in English.
© 2011 Gilbert Ndjatou
Page 115
public class TakeOrderClass2
{
static int number = 1;
public void main( String [ ] args )
{
/*-------- Define and instantiate an object to be used to make an order in French---- */
PlaceAnOrder2 frenchOrder =
new PlaceAnOrder2 ( )
{
/*---------------- definition of the method sayGreeting( ) -----------------*/
public void sayGreeting( )
{
System.out.println( “Bonjour! Je suis le numero:\t” + (number++) );
}
/*---------------- definition of the method sayOrder( ) -----------------*/
public void sayOrder ( String food )
{
System.out.println( “Je veux du “ + food);
}
}
/*-------------------------Make your order in French------------------------------*/
frenchOrder.sayGreeting( );
frenchOrder.sayOrder( “café” );
/*-------- Define and instantiate an object to be used to make an order in English ---- */
PlaceAnOrder2 englishOrder =
new PlaceAnOrder2 ( )
{
/*---------------- definition of the method sayGreeting( ) -----------------*/
public void sayGreeting( )
{
System.out.println(“Hello! I am number:\t” + (number++) );
}
/*---------------- definition of the method sayOrder( ) -----------------*/
public void sayOrder ( String food )
{
System.out.println( “I would like to have “ + food);
}
}
/*----------------------------Make your order in English----------------------------*/
englishOrder.sayGreeting( );
englishOrder.sayOrder( “coffee” );
} // end of main
} // end of class TakeOrderClass2
© 2011 Gilbert Ndjatou
Page 116
Exercise O16
1. Using the following definition of the abstract class ChangeMaker:
abstract class ChangeMaker
{
private int val1;
private int val2;
public ChangeMaker( )
{
val1 = 0;
val2 = 0;
}
public ChangeMaker(int n1, int n2 )
{
val1 = n1;
val2 = n2;
}
public int getVal1( )
{
return val1;
}
public int getVal2( )
{
return val2;
}
public void setValues( int num1, int num2)
{
val1 = num1;
val2 = num2;
}
public abstract void makeChanges( );
// abstract method
@Override
public String toString( )
{
String s = “\nval1=” + val1 + “\nval2 =” + val2;
return( s );
}
}
Define a class named TestChangeMaker with the method main that doe the following:
a) Define the object obj1 by using an anonymous class that extends the abstract class ChangeMaker as follows:
 This object is initialized with the default constructor.
 Method makeChanges is defined as follows: It increments the value of each instance variable by 1.
b) Call the method makeChanges( ) on this object and then print it.
c) Define the object obj2 by using an anonymous class that extends the abstract class ChangeMaker as follows:
 This object is initialized with the value 3 for val1, and 4 for val2.
 Method makeChanges is defined as follows: It increments the value of each instance variable by 5.
d) Call the method makeChanges( ) on this object and then print it.
© 2011 Gilbert Ndjatou
Page 117
2. Using the following definition of the interface Expression:
public interface Expression
{
void saySomething( );
}
Define a class named TestExpression with the method main that doe the following:
a) Define and instantiate the object obj1 by using an anonymous class that implements the interface Expression
with the following definition of the method saySomething:
void saySomething( )
{
System.out.println( “I feel good”);
}
b) Call the mothod saySomething on this object.
c) Define the object obj2 by using an anonymous class that implements the interface Expression with the
following definition of the method saySomething:
void saySomething( )
{
System.out.println( “I do not feel well”);
}
d) Call the mothod saySomething on this object.
© 2011 Gilbert Ndjatou
Page 118
Exceptions
 An exception is an indication of a problem that occurs during the execution of a program.
 A program can generate many types of exceptions such as the following:





The execution of a statement to read from a file that does not exist.
The execution of a statement to write to a disk that is full.
The execution of an input statement when the user enters an invalid input data.
The execution of a statement in which an integer value is divided by 0.
Accessing the element of an array with an index value less than 0 or greater than the size of the
array.
 Methods known as exception handling are provided in Java to manage exceptions.
 These methods are provided in the class Exception (from the package java.lang), its subclasses, and
some other classes.
 An example of a class with exception handling methods that is not a subclass of the class Exception
is the class InputMismatchException (in the package java.util).
 You must therefore write one of the following two import statements in any program that handles the
input mismatch exception:
import java.util.InputMismatchException; or
import java.util.*;
 An input mismatch exception occurs during the execution of an input statement when the user
enters an invalid data.
 When an input mismatch exception occurs in a program, the wrong input data must first be removed
from the input buffer before a new input data can be read again.
 The class Exception is a subclass of the class Throwable.
 Class Exception and its subclasses represent error conditions that may be caught in a program and for
which a corrective actions can be specified. The Java exception (classes) hierarchy is provided
below.
 Another subclass of the class Throwable is the class Error.
 Class Error and its subclasses represent error conditions from which a program usually cannot
recover.
 An example of a program execution in which exceptions are thrown (exceptions occurs) is provided
in Example E0.
 If you execute this program with input data 7 and 0, an ArithmeticException (which is a subclass
of Exception) will be generated by the error “/ by zero” which occurred (or is thrown) in the
method quotient, and detected in the method main.
© 2011 Gilbert Ndjatou
Page 119

If you execute it with input data 10 and ko, an InputMismatchException will occur in the method
nextInt( ) from the class Scanner (when it receives the string ko which does not represent a valid
integer value) and detected in the method main. However, the cause of the exception will not be
specified.
Java Exception Hierarchy
o
java.lang.Exception
o
java.lang.CloneNotSupportedException
o
java.lang.InterruptedException
o
java.lang.ReflectiveOperationException
o
© 2011 Gilbert Ndjatou
o
java.lang.ClassNotFoundException
o
java.lang.IllegalAccessException
o
java.lang.InstantiationException
o
java.lang.NoSuchFieldException
o
java.lang.NoSuchMethodException
java.lang.RuntimeException
o
java.lang.ArithmeticException
o
java.lang.ArrayStoreException
o
java.lang.ClassCastException
o
java.lang.EnumConstantNotPresentException
o
java.lang.IllegalArgumentException
o
java.lang.IllegalThreadStateException
o
java.lang.NumberFormatException
o
java.lang.IllegalMonitorStateException
o
java.lang.IllegalStateException
o
java.lang.IndexOutOfBoundsException
o
java.lang.ArrayIndexOutOfBoundsException
o
java.lang.StringIndexOutOfBoundsException
o
java.lang.NegativeArraySizeException
o
java.lang.NullPointerException
o
java.lang.SecurityException
o
java.lang.TypeNotPresentException
o
java.lang.UnsupportedOperationException
Page 120
Example E0
The following program reads two integer values and computes the quotient in the division of the first
value by the second value by calling the class method int quotient(int num1, int num2).
/*------------------------------------------------------------ProgramE0-------------------------------------------------*/
/* Read two integer values, and compute the quotient in the division of the first value by the second */
import java.util.Scanner;
public class ProgramE0
{
public static void main( String [ ] args )
{
Scanner input = new Scanner( System.in );
int numerator,
denominator;
// for standard input
// to hold the numerator
// to hold the denominator
/*-------------------------------read the numerator -------------------------------*/
System.out.println( “\nPlease enter the numerator:\t” );
numerator = input.nextInt( );
/*-------------------------------- read the denominator ---------------------------------------------*/
System.out.println( “\nPlease enter the denominator:\t” );
denominator = input.nextInt( );
/*---------------------------Compute and print the quotient--------------------------------*/
int result = quotient( numerator , denominator );
//exception may be detected
System.out.printf( “\nThe result of: %d / %d = %d\n”, numerator, denominator, result);
} // end of method main
public static int quotient( int first, int second )
{
return( first / second );
// possible division by zero
}
} // end of class ProgramE0
Hands-On E1
A. Type and execute the program in Example E0 as follows:
a. With input values: 12 and 5.
b. With input values:
7 and 0.
c. With input values:
10 and ko.
B. Highlight the exceptions generated on your printouts.
© 2011 Gilbert Ndjatou
Page 121
1. Writing a Method that might throw Exceptions
 When you write a method that might cause (throw) an exception, you must follow its header with the
keyword throws which is followed by the list of all the exceptions that it might cause, separated with
commas.
 In the following examples, an arithmetic exception will occur in the method quotient if there is an
attempt to divide by zero.
Example:
public static int quotient( int first, int second ) throws ArithmeticException
{
return( first / second );
// possible division by zero
}
The try Block
 When you write a program, use the try block to enclose one or more statements in which an
exception that you want to handle in the program may be detected as follows:
try
{
<statements-in which-an-exception-that-you-want-to-handle-may-be-detected>
<statements-to-be-executed-only-if-no-exception-is-detected>
}
Example:
try
{
int result = quotient( numerator , denominator );
//exception may be detected
System.out.printf( “\nThe result of: %d / %d = %d\n”, numerator , denominator, result);
}
© 2011 Gilbert Ndjatou
Page 122
The catch Block
 In a Java program, every try block must be immediately followed by at least one catch block or a finally
block.
 You use a catch block to write the statements that must be execured when its corresponding exception is
be detected in the preceding try block.
 Whenever an exception occurs in a try block, the execution of the program jumps to its corresponding
catch block.
 The syntax of a catch block follows:
catch ( <name-of-exception-to-be-detected> <parameter> )
{
<statements-to.be-executed-when-the-above-exception-is-detected-in-the-try-block>
}
<parameter>:
 Is a reference to an object of the class that corresponds to the exception that is being detected.
 This object is used by the system to hold the information about the exception that has just been
detected.
Example E1
 The following program reads two integer values and computes the quotient in the division of the first
value by the second value by calling the class method int quotient(int num1, int num2).
 The program will repeatedly read the second value until the user enters a non-zero value.
 In this program as in other programs that follow, output to the standard error device (which is by default
the monitor) is performed by using the methods println and print on object System.err.
© 2011 Gilbert Ndjatou
Page 123
/*------------------------------------------------------------ProgramE1a-------------------------------------------------*/
/* Read two integer values, and compute the quotient in the division of the first value by the second */
/* The program will repeatedly read the second value until the user enters a non-zero value
*/
import java.util.Scanner;
public class ProgramE1a
{
public static void main( String [ ] args )
{
Scanner input = new Scanner( System.in );
int numerator,
denominator;
boolean continueLoop = true;
// for standard input
// to hold the numerator
// to hold the denominator
// set to false if the user enter a non-zero value
/*-------------------------------read the numerator -------------------------------*/
System.out.println( “\nPlease enter the numerator:\t” );
numerator = input.nextInt( );
while( continueLoop )
{
/*-------------------------------- read the denominator ---------------------------------------------*/
System.out.println( “\nPlease enter the denominator:\t” );
denominator = input.nextInt( );
try
{
/*---------------------------Compute and print the quotient--------------------------------*/
int result = quotient( numerator , denominator );
//exception may be detected
System.out.printf( “\nThe result of: %d / %d = %d\n”,numerator , denominator, result);
continueLoop = false;
// stop the repetition of the loop with a non-zero value
}
catch( ArithmeticException e )
{
System.err.printf( “\nException: %s\n”, e );
// display the exception detected
System.out.println( “zero is an invalid denominator. Please try again\n” );
}
}
} // end of method main
public static int quotient( int first, int second ) throws ArithmeticException
{
return( first / second );
// possible division by zero
}
} // end of class ProgramE1a
© 2011 Gilbert Ndjatou
Page 124
Notes:
1. When an exception is detected in a try block, the statements in the try block that follow the statement in
which the exception has been detected are not executed. Instead, the control of the execution is passed to
the first statement in the catch block that corresponds to the exception detected.
2. You can write a method in which an exception may be caused (thrown) and detected in the same
statement as in the following example.
/*------------------------------------------------------------ProgramE1b-------------------------------------------------*/
/* Read two integer values, and compute the quotient in the division of the first value by the second */
/* The program will repeatedly read the second value until the user enters a non-zero value
*/
import java.util.Scanner;
public class ProgramE1b
{
public static void main( String [ ] args ) throws ArithmeticException
{
Scanner input = new Scanner( System.in ); // for standard input
int numerator,
// to hold the numerator
denominator;
// to hold the denominator
boolean continueLoop = true;
// set to false if the user enter a non-zero value
/*-------------------------------read the numerator -------------------------------*/
System.out.println( “\nPlease enter the numerator:\t” );
numerator = input.nextInt( );
while( continueLoop )
{
/*-------------------------------- read the denominator ---------------------------------------------*/
System.out.println( “\nPlease enter the denominator:\t” );
denominator = input.nextInt( );
try
{
/*---------------------------Compute and print the quotient--------------------------------*/
int result = numerator / denominator;
//exception may be thrown and detected
System.out.printf( “\nThe result of: %d / %d = %d\n”, numerator , denominator, result);
continueLoop = false;
// stop the repetition of the loop with a non-zero value
}
catch( ArithmeticException e )
{
System.err.printf( “\nException: %s\n”, e );
// display the exception detected
System.out.println( “zero is an invalid denominator. Please try again\n” );
}
}
} // end of method main
} // end of class ProgramE1b
© 2011 Gilbert Ndjatou
Page 125
Using the Exception getMessage( ) Method
 Every Exception class has the method getMessage( ) that returns a string that describes the error that
caused that exception.
 This method may be called in a catch block as in the following program:
/*------------------------------------------------------------ProgramE1c-------------------------------------------------*/
/* Read two integer values, and compute the quotient in the division of the first value by the second */
/* The program will repeatedly read the second value until the user enters a non-zero value
*/
import java.util.Scanner;
public class ProgramE1c
{
public static void main( String [ ] args ) throws ArithmeticException
{
Scanner input = new Scanner( System.in ); // for standard input
int numerator,
// to hold the numerator
denominator;
// to hold the denominator
boolean continueLoop = true;
// set to false if the user enter a non-zero value
/*-------------------------------read the numerator -------------------------------*/
System.out.println( “\nPlease enter the numerator:\t” );
numerator = input.nextInt( );
while( continueLoop )
{
/*-------------------------------- read the denominator ---------------------------------------------*/
System.out.println( “\nPlease enter the denominator:\t” );
denominator = input.nextInt( );
try
{
/*---------------------------Compute and print the quotient--------------------------------*/
int result = numerator / denominator;
//exception may be thrown and detected
System.out.printf( “\nThe result of: %d / %d = %d\n”, numerator , denominator, result);
continueLoop = false;
// stop the repetition of the loop with a non-zero value
}
catch( ArithmeticException e )
{
System.err.printf( “\nException: %s\n”, e );
// display the exception detected
System.out.println( “\nThe error is:” + e.getMessage( ) + “. Please try again\n” );
}
}
} // end of method main
} // end of class ProgramE1c
© 2011 Gilbert Ndjatou
Page 126
Hands-On E2
Type and execute the programs E1a and E1c with input values: 5 and 0 and then 10 and 3.
Detecting Two or More Exceptions in a try Block
 A try block in which two or more exceptions may be detected must be followed immediately by a catch
block for each of the exceptions that may be detected in that try block.
 When there are more than one catch block immediately after a try block, they are examined in sequence
until a match is found for the exception that occurred.
 The matching catch block executes and each remaining catch block is bypassed.
 The catch block for an exception class must therefore be specified before the catch block for its super
class: because an exception of a class is also an exception of its super class.
Example E2
 The following program reads two integer values and computes the quotient in the division of the first
value by the second value.
 The program also makes sure that the user enters as input a valid integer value and that the second input
value is a non-zero value.
 The program will repeatedly read the two values until the user enters two valid integer values with the
second value a non-zero value.
 Note that when an invalid input value is encountered in the input stream, it must first be discarded before
another value can be read.
/*------------------------------------------------------------ProgramE2-------------------------------------------------*/
/* Read two integer values, and compute the quotient in the division of the first value by the second */
/* The program will repeatedly read the two values until both values are valid integer values and the second value
is a non-zero value
*/
import java.util.Scanner;
import java.util.InputMismatchException;
public class ProgramE2
{
public static void main( String [ ] args ) throws ArithmeticException
{
Scanner input = new Scanner( System.in ); // for standard input
int numerator,
// to hold the numerator
denominator;
// to hold the denominator
boolean continueLoop = true;
// set to false if the user enter a non-zero value
© 2011 Gilbert Ndjatou
Page 127
while( continueLoop )
{
try
{
/*----------------------------------read the numerator ----------------------------------------------*/
System.out.println( “\nPlease enter the numerator:\t” );
numerator = input.nextInt( );
// exception may be detected
/*-------------------------------- read the denominator ---------------------------------------------*/
System.out.println( “\nPlease enter the denominator:\t” );
denominator = input.nextInt( );
// exception may be detected
/*---------------------------Compute and print the quotient--------------------------------*/
int result = numerator / denominator;
//exception may be thrown and detected
System.out.printf( “\nThe result of: %d / %d = %d\n”, numerator , denominator, result);
continueLoop = false;
// stop the repetition of the loop with a non-zero value
}
catch( InputMismatchException e )
{
System.err.printf( “\nException: %s\n”, e );
// display the exception detected
String line = input.nextLine( );
// discard the invalid input data
System.out.println( “\nThe error is:” + e.getMessage( ) + “. Please try again\n” );
}
catch( ArithmeticException e )
{
System.err.printf( “\nException: %s\n”, e );
// display the exception detected
System.out.println( “\nThe error is:” + e.getMessage( ) + “. Please try again\n” );
}
}
} // end of method main
} // end of class ProgramE2
Hands-On E3
Type and execute program E2 with input values:
7 and 0, then 10 and kd, and finally 12 and 5.
Using the finally Block
 The finally block may be placed after all the catch blocks that immediately follow a try block.
 The code within a finally block executes whether or not the try block identifies Exceptions.
 Its syntax is as follows:
© 2011 Gilbert Ndjatou
Page 128
finally
{
<statements-to-be-executed-whether-or-not-exceptions-are-identified>
}
Example of a Method that throws Multiple Exceptions
 Method main of the following program has an array of five integer value constants which are the
possible numerators in a division.
 The denomirator of the division is read from the keyboard and the index of the numerator in the array
(which must be a value from 0 to 4) is also read from the keyboard.
 This method can throw an ArithmeticException if the user enters 0 for the denomirator and an
IndexOutOfBoundsException if he enters an index that is not a value from 0 to 4.
 Note that in addition to the exceptions ArithmeticException and IndexOutOfBoundsException that may
be detected in method main, the exception InputMismatchException may also be detected.
/*------------------------------------------------------------ProgramE3-------------------------------------------------*/
/* This program has an array of five integer values constants. It reads the index of an array element and makes
that element the value of the numerator. It then reads the value of the denominator and then computes the quotient
in the division of the numerator by the denominator */
import java.util.Scanner;
import java.util.InputMismatchException;
public class ProgramE3
{
public static void main( String [ ] args ) throws ArithmeticException , IndexOutOfBoundsException
{
Scanner input = new Scanner( System.in ); // for standard input
int[ ] numeratorList = { 23, 21, 7, 45, 3 };
// list of possible values for the numerator
int numerator,
// to hold the numerator
denominator,
// to hold the denominator
index;
// to hold an array index value
try
{
/*---------read an index value and use it to get the value of the numerator from the array-----*/
System.out.println( “\nPlease enter a value from 0 to 4:\t” );
index = input.nextInt( );
// exception may be detected
numerator = numeratorList[ index ];
// exception may be thrown and detected
/*-------------------------------- read the denominator ---------------------------------------------*/
System.out.println( “\nPlease enter the denominator:\t” );
denominator = input.nextInt( );
// exception may be detected
© 2011 Gilbert Ndjatou
Page 129
/*---------------------------Compute and print the quotient--------------------------------*/
int result = numerator / denominator;
//exception may be thrown and detected
System.out.printf( “\nThe result of: %d / %d = %d\n”, numerator , denominator, result);
}
catch( InputMismatchException e )
{
System.err.printf( “\nException: %s\n”, e );
// display the exception detected
String line = input.nextLine( );
// discard the invalid input data
System.out.println( “\nThe error is: You have entered an invalid input data\n” );
}
catch( ArithmeticException e )
{
System.err.printf( “\nException: %s\n”, e );
// display the exception detected
System.out.println( “\nThe error is: division by zero is not feasible\n” );
}
catch( IndexOutOfBoundsException e )
{
System.err.printf( “\nException: %s\n”, e );
// display the exception detected
System.out.println( “\nThe error is: you should have entered a value from zero to four\n” );
}
finally
{
System.out.println( “\nThank you for using this program. \n Bye bye\n” );
}
} // end of method main
} // end of class ProgramE3
Hands-On E4
Type and execute the program E3 as follows:
a. With input 6 and 4
b. With input z and 5
c. With input 2 and 0
d. With input 2 and 5
© 2011 Gilbert Ndjatou
Page 130
Wrapper Classes
 For each primitive data type, Java provides a wrapper class as follows:
Data Type
Wrapper Class
byte
short
int
long
float
double
char
boolean
Byte
Short
Integer
Long
Float
Double
Character
Boolean
 The purpose of a wrapper class is to represent a (primitive data type) value using an object that contains
that value.
 The object can then be used in a way similar to how other objects are used. Such as passing a (basic data
type) parameter to a function by reference.
 A wrapper class also contains methods which may be used in the processing of variables of the
corresponding data type. For example, the Character wrapper class contains methods that can be used to
check if a character is a digit, a letter of the alphabet, a whitespace, and so on.
Creating an Object of the Wrapper Class
 Each wrapper class has a constructor which can be used to create an object by passing to it an
expression that evaluates to a value of the corresponding primitive data type.
Data
Type
Wrapper Constructor
Class
Example
byte
short
int
long
float
double
char
boolean
Byte
Short
Integer
Long
Float
Double
Character
Boolean
Byte obj = new Byte(15);
© 2011 Gilbert Ndjatou
Byte(byte-epx)
Short(short-exp)
Integer(int-exp)
Long(long-exp)
Float(float/double-exp)
Double(float/double-exp)
Character(char-exp)
Boolean(boolean-exp)
Integer obj = new Integer(num + 123);
Double obj = new Double(123.45);
Character obj = new Character( ‘A’ );
Page 131
 Except for the Character and the Boolean wrapper classes, each wrapper class also has a constructor that
can be used to create an object by passing to it a string that represents a value of the corresponding
primitive data type.
Data
Type
Wrapper Constructor
Class
Example
byte
short
int
long
float
double
Byte
Short
Integer
Long
Float
Double
Byte obj = new Byte(“15”);
Byte(byte-string)
Short(shot-string)
Integer(int-string)
Long(long-string)
Float(float/double-string)
Double(float/double-string)
Integer obj = new Integer(“123”);
Double obj = new
Double(“123.45”);
Retrieving the value wrapped by a wrapper class object
 Each of the eight wrapper classes has an instance method that you can use to retrieve the value that was
wrapped in the object as follows:
Data
Type
Wrapper
Class
Method
Example
byte
short
int
long
float
double
char
boolean
Byte
Short
Integer
Long
Float
Double
Character
Boolean
byteValue()
shortValue()
intValue()
longValue()
floatValue()
doubleValue()
charValue()
booleanValue()
byte x = obj.byteValue( );
int x = obj.intValue( );
double x = obj.doubleValue( );
char x = obj.charValue( );
Auto boxing and auto unboxing
 Creating a wrapper class object using the constructors and retrieving the values wrapped by those objects
using the methods as shown above can become quite cumbersome.
 As an alternative, there exists auto boxing and auto unboxing.
 Auto boxing refers to an implicit call to the constructor and
 Auto unboxing refers to an implicit call to the *value( ) method.
© 2011 Gilbert Ndjatou
Page 132
 With Auto boxing, a new wrapper object is created by specifying the value to be wrapped just as we
would do for a primitive data type variable.
 With auto unboxing, the value of a wrapper object is retrieved and used by specifying the object name.
 It means that you can use a wrapper object in any expression where its value could be used.
Examples
Integer obj = 34;
int x= obj;
int x = obj + 7;
The above statements are equivalent to the following set of statements
Integer obj = new Integer (34);
int x = obj.intValue( );
int x = obj.intValue( )+ 7;
Using a Wrapper Class Object as a Reference Parameter
 Unlike objects of other classes, an object of a wrapper class is passed to a method by value and not
by reference.
Example
The following method swapper( ) is supposed to receive two Integer objects and to swap their values.
But it will not be able to accomplish it because the output of the program is:
obj1= 5
obj2= 10
objFirst= 10
objSecond= 5
/*-------------------------------------------------------TestSwapper --------------------------------------------*/
/* swap the values of two Integer objects
*/
public class TestSwapper
{
public static void main( String [ ] args )
{
Integer objFirst = 10,
// object for the first value
objSecond = 5;
// object for the second value
/*-------------------------------swap their values -------------------------------*/
Swapper( objFirst, objSecond );
System.out.printf(“objFirst=\t%d\nobjSecond=\t%d”, objFirst, objSecond);
}
© 2011 Gilbert Ndjatou
Page 133
/*--------------------------------------Class Method swapper( )--------------------------------------*/
/* interchange the values of the arguments */
static void swapper(Integer obj1, Integer obj2)
{
Integer temp = obj1,
obj1 = obj2 ;
obj2 = temp;
System.out.printf(“obj1=\t%d\nobj2\t%d”, obj1, obj2);
}
}
Comparing Objects of a Wrapper Class
 There is a generic interface in Java named Comparable<T> (in the package java.lang) with a single
method int compareTo( T obj) and
 It is possible to compare two objects of the same class if that class implements this interface.
 However, it is your responsibility to provide the definition of the method compareTo( ) such that it
compares the contents of two objects of your class and returns 0 if the objects are equal, a negative
integer value if object1 is less than object2 and a positive integer value if object1 is greater than
object2.
 Each wrapper class of a primitive type implements this interface.
 So, two Integer objects, integer1 and integer2 can be compared as follows:
integer1.compareTo( integer2 )
Example W2
The program in this example reads two integer values and computes the quotient in the division of the
largest value by the smallest by calling the static method void computeQuot(Integer obj1, Integer obj2).
/*-------------------------------------------------------ProgramW2 -------------------------------------------------*/
/* Read two integer values and print the quotient in the division of the largest value by the smallest */
import java.util.Scanner;
public class ProgramW2
{
public static void main( String [ ] args )
{
Scanner input = new Scanner( System.in ); // for standard input
Integer objFirst,
// object for the first value
objSecond;
// object for the second value
/*-------------------------------read the two values -------------------------------*/
objFirst = input.nextInt( );
objSecond = input.nextInt( );
© 2011 Gilbert Ndjatou
Page 134
/*----Compute and print the difference of the largest value minus the smallest------*/
computeQuot( objFirst, objSecond );
} // end of method main
/*--------------------Class Method computeQuot( )---------------------*/
/* compute the quotient in the division of the largest value by the small one
*/
static void computeQuot (Integer obj1, Integer obj2)
{
if( obj1.compareTo( obj2 ) < 0 )
{
Integer temp = obj1,
obj1 = obj2 ;
obj2 = temp;
}
System.out.printf(“The quotient in the division of the largest value by the smallest is:\t%d”,
obj1/obj2);
}
}
Hands-On W1
Type and execute program ProgramW2 above.
© 2011 Gilbert Ndjatou
Page 135
Class Number
 The abstract class Number (from the package java.lang) is the superclass of the wrapper classes Byte,
Double, Float, Integer, Long, and Short.
 It has the following instance methods:
Method & Description
public byte byteValue( ) : returns the value of the specified number as a byte. May involve rounding or truncation.
abstract double doubleValue( ) :
returns the value of the specified number as a double. May involve rounding or truncation.
abstract float floatValue( ) :
returns the value of the specified number as a float. May involve rounding or truncation.
abstract int intValue( ) : returns the value of the specified number as a int. May involve rounding or truncation.
abstract long longValue( ) : returns the value of the specified number as a long. May involve rounding or truncation.
short shortValue( ) : returns the value of the specified number as a short. May involve rounding or truncation.
 The subclasses of class Number must provide the implementation of these methods.
Example W3
The program in this example use the method void printNumArray( Number [ ] array) to output the string
representations of the elements of an array of numerical values:
public class ExampleW3
{
// method printNumArray
public static void printNumArray( Number [ ] inputArray )
{
// Display array elements
for ( E element : inputArray )
System.out.printf( "%s ", element );
System.out.println();
}
public static void main( String args[ ] )
{
// Create arrays of Integer, Double and Character
Integer[ ] intArray = { 1, 2, 3, 4, 5 };
Double[ ] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
© 2011 Gilbert Ndjatou
Page 136
// pass an Integer array
System.out.println( "Array integerArray contains:" );
printNumArray( intArray );
// pass a Double array
System.out.println( "\nArray doubleArray contains:" );
printNumArray( doubleArray );
}
}
This would produce the following result:
Array integerArray contains:
123456
Array doubleArray contains:
1.1 2.2 3.3 4.4
Hands-On W2
Type and execute program ProgramW3 above.
© 2011 Gilbert Ndjatou
Page 137
Generic Methods
 Generic methods enable programmers to specify, with a single method declaration, a set of related
methods.
 Using Java Generic concept, we might write a generic method for sorting an array of objects, then invoke
the generic method with Integer arrays, Double arrays, String arrays and so on.
 Based on the types of the arguments passed to a generic method, the compiler handles each method call
appropriately.
 The following are the rules to define Generic Methods:

All generic method declarations have a type parameter section delimited by angle brackets (< and
>) that precedes the method's return type.

Each type parameter section contains one or more type parameters separated by commas.

A type parameter, also known as a type variable, is an identifier that specifies a generic type name.

A type parameter can be used

o
to declare the return type of the method, and
o
to act as placeholders for the types of the arguments passed to the generic method.
A generic method's body is declared like that of any other method.
Examples
The following are examples of method headers of generic methods:

< E > void funct( E parm )
A void method with one parameter with data type the type variable E.

< E > E funct( )
A method that returns a value of data type the type variable E.

< E > E funct(int parm1, E parm2 )
A method with an integer parameter and a parameter with data type the type variable E and that returns a
value of data type the type variable E.

< V, T > void funct( V param1, T param2 )
A void method with a parameter with data type the type variable V. and another parameter with data type
the type variable T.
Note
A type variable can represent only reference types, not primitive types (like int, double, and char).
© 2011 Gilbert Ndjatou
Page 138
Example G1
The following example illustrates how we can print the string representations of the elements of arrays
of different types by using the generic method < E > void printArray( E[ ] inputArray ).
:
public class ExampleG1
{
// generic method printArray
public static < E > void printArray( E[ ] inputArray )
{
// Display array elements
for ( E element : inputArray )
System.out.printf( "%s ", element );
System.out.println();
}
public static void main( String args[ ] )
{
// Create arrays of Integer, Double and Character
Integer[ ] intArray = { 1, 2, 3, 4, 5 };
Double[ ] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[ ] charArray = { 'H', 'E', 'L', 'L', 'O' };
// pass an Integer array
System.out.println( "Array integerArray contains:" );
printArray( intArray );
// pass a Double array
System.out.println( "\nArray doubleArray contains:" );
printArray( doubleArray );
// pass a Character array
System.out.println( "\nArray characterArray contains:" );
printArray( charArray );
}
}
This would produce the following result:
Array integerArray contains:
123456
Array doubleArray contains:
1.1 2.2 3.3 4.4
Array characterArray contains:
HELLO
© 2011 Gilbert Ndjatou
Page 139
Bounded Type Parameters
 There may be times when you would like to restrict the reference types represented by a type
variable.
 For example, a method that operates on numbers can only accept the reference type Number and its
subclasses Byte, Double, Float, Integer, Long, and Short.
 This kind of type parameter is called a bounded type parameter.
 You declare a bounded type parameter by following its name with the extends keyword, followed
by its upper bound.
Examples

< T extends Number >

< T extends Comparable<T> > T can only be a class that implements the interface Comparable<T>.
T can only be the Number class or a subclass of the Number class.
Example G2
This example uses a Generic method that returns the largest of three Comparable objects.
public class MaximumTest
{
// determines the largest of three Comparable objects
public static <T extends Comparable<T>> T maximum(T x, T y, T z)
{
T max = x;
// assume x is initially the largest
if ( y.compareTo( max ) > 0 )
max = y;
if ( z.compareTo( max ) > 0 )
max = z;
return max; // returns the largest object
}
public static void main( String args[] )
{
System.out.printf( "Max of %d, %d and %d is %d\n\n", 3, 4, 5, maximum( 3, 4, 5 ) );
System.out.printf( "Max of %.1f,%.1f and %.1f is %.1f\n\n", 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ) );
System.out.printf( "Max of %s, %s and %s is %s\n","pear", "apple", "orange",
maximum( "pear", "apple", "orange" ) );
}
}
© 2011 Gilbert Ndjatou
Page 140
This would produce the following result:
Max of 3, 4 and 5 is 5
Max of 6.6, 8.8 and 7.7 is 8.8
Max of pear, apple and orange is pear
Hands-On G1
Type and execute the programs in Examples G1 and G2.
© 2011 Gilbert Ndjatou
Page 141
Generic Classes
 Generic classes/interfaces enable programmers to specify with a single class/interface declaration, a
set of related types.
 A generic class declaration looks like a non-generic class declaration, except that the class name is
followed by a type parameter section.
 As with generic methods, the type parameter section of a generic class can have one or more type
parameters separated by commas.
 These classes are known as parameterized classes or parameterized types because they accept one or
more Type variables.
Examples

class TobeDone< E >
{
Public TobeDone( )
// default constructor
{
. . .
}
. . .
}

class WhatToDo< V, T >
{
Public WhatToDo( int num )
// constructor with parameters
{
. . .
}
. . .
}
 When you write the definition of a constructor of a generic class, you do not follow the name of the
class with the the type parameter section.
 When you use a generic class to define a reference variable, you replace the type variable(s) in the
type parameter section with existing class names, and
 When you use a constructor of a generic class to create an object, you replace the type variable(s) in the
type parameter section with existing class names.
© 2011 Gilbert Ndjatou
Page 142
Examples

TobeDone< Integer > ref
= new TobeDone< Integer > (
);
Type parameter E is replaced by the class Integer.

WhatToDO< String, Double > objRef
= new WhatToDo< String, Double >( 10 );
Type parameter V is replaced by class String and type parameter T is replaced by class Double.
Example G3
The following example illustrates how we can define a generic class.
class Box<T>
{
private T ref;
public void add(T newRef)
{
ref = newRef;
}
public T get( )
{
return ref;
}
}
public class TestBox
{
public static void main(String[] args)
{
Box<Integer> integerBox = new Box<Integer>( );
Box<String> stringBox = new Box<String>( );
integerBox.add( new Integer(10) );
stringBox.add( new String("Hello World") );
System.out.printf("Integer Value :%d\n\n", integerBox.get( ));
System.out.printf("String Value :%s\n", stringBox.get( ));
}
}
This would produce the following result:
Integer Value :10
String Value :Hello World
© 2011 Gilbert Ndjatou
Page 143
Hands-On G2
Type and execute the programs in Example G3.
© 2011 Gilbert Ndjatou
Page 144
Introduction to Collections
 A collection represents a group of objects, known as its elements.
 Some collections allow duplicate elements and others do not.
 Some are ordered and others unordered.
 The Java API provides several predefined data structures, called collections that are used to store groups
of related objects.
 The collections-framework interfaces declare the operations to be performed generically on various
types of collections.
 Generic class implementations of these interfaces are also provided within the framework.
 The following table lists some of these interfaces, their descriptions, and some classes that implement
each of them.
Interfaces
Description
Implementation(s)

Collection<E>
Set<E>
List<E>
Queue<E>
Map<K, V>
The root interface in the collection hierarchy from
which interface Set, Queue, and List are derived.
 Collection is used commonly as parameter types in
methods to alloy polymorphic processing of
objects of classes that implement interface
Collection.
A collection that does not contain duplicates.
An ordered collection that can contain duplicate
elements.
A first-in, first-out collection that models a waiting
line; other orders can be specified.
A collection that associates keys to values and cannot
contain duplicate keys.
Class AbstractCollection<E>
HashSet<E>, TreeSet<E>
ArrayList<E>, LinkedList<E>, and
Vector<E>
PriorityQueue<E>
HashMap<K, V>, HashTable<K, V>,
TreeMap<K, V>
Interface Collection<E>
 E is the type of elements in the collection.
 The following table provides a description of the methods in the interface Collection<E> (from the
package java.util).
© 2011 Gilbert Ndjatou
Page 145
Method
boolean add(E e)
Description



Ensures that this collection contains the specified element:
Returns true if this collection changed as a result of the call.
Returns false if this collection does not permit duplicates and
already contains the specified element.

Collection c is the collection containing the elements to be
added to this collection.
Its elements must be objects of class E or a class that extends
Class E.
Returns true if this collection changed as a result of the call.
Returns false if this collection does not permit duplicates and
already contains the specified element.

boolean addAll(Collection<? extends E> c)
void clear( )
boolean contains(Object o)
boolean containsAll(Collection<?> c)
boolean equals(Object o)
int hashCode( )
boolean isEmpty( )




Removes all of the elements from this collection
The collection will be empty after this method returns.


Returns true if this collection contains the specified element.
Returns true if this collection contains all of the elements in
the specified collection.
Returns true if the specified object is equal to this collection
Returns the hash code value for this collection
Returns true if this collection contains no elements.
Returns an iterator over the elements in this collection. There
are no guarantees concerning the order in which the elements
are returned.
Removes a single instance of the specified element from this
collection, if it is present.
Returns true if this collection contains the specified element.
Removes all of this collection's elements that are also
contained in the specified collection.
After this call returns, this collection will contain no elements
in common with the specified collection.
Returns true if this collection changed as a result of the call.




Iterator<E> iterator( )

boolean remove(Object o)


boolean removeAll(Collection<?> c)



boolean retainAll(Collection<?> c)

int size( )



Object[] toArray( )

<T> T[] toArray(T[] a)

© 2011 Gilbert Ndjatou
Removes from this collection all of its elements that are not
contained in the specified collection.
Returns true if this collection changed as a result of the call.
Returns the number of elements in this collection.
Returns an array containing all of the elements in this
collection.
Returns all the elements of this collection in the specified
array if it is big enough to contain them.
Otherwise, builds a new array and returns them in that array.
Page 146
Interface List<E>
 The interface List<E> (from the package java.util) extends the interface Collection<E>.
 It therefore inherits all the methods of the interface Collection<E>. However, the following methods are
overridden in the interface List<E> as follows:
Method
boolean add(E e)
Description



Appends the specified element to the end of this list:
Returns true if this collection changed as a result of the call.
Returns false if this collection does not permit duplicates and
already contains the specified element.

Collection c is the collection containing the elements to be
appended to the end of the list.
Its elements must be objects of class E or a class that extends
Class E.
Returns true if this collection changed as a result of the call.
Returns false if this collection does not permit duplicates and
already contains the specified element.

boolean addAll(Collection<? extends E> c)



boolean remove(Object o)

Removes the first occurence of the specified element from
this list, if it is present.
Returns true if this list contains the specified element.
 The following table provides a description of the additional methods in the interface List<E>.
© 2011 Gilbert Ndjatou
Page 147
Method
Description
void add(int index, E element)
Inserts the specified element at the specified position in this list.
 Collection c is the collection containing the elements to be
inserted into the list at the specified position.
 Its elements must be objects of class E or a class that extends
Class E.
 Returns true if this collection changed as a result of the call.
 Returns false if this collection does not permit duplicates and
already contains the specified element.
boolean
addAll(int index, Collection<? extends E> c)
E get(int index)
int indexOf(Object o)
int lastIndexOf(Object o)
ListIterator<E> listIterator( )
ListIterator<E> listIterator( int index )
E remove(int index)
E set(int index, E element)
List<E> subList(int fromIndex, int toIndex)
© 2011 Gilbert Ndjatou
Returns the element at the specified position in the list.
Returns the index of the first occurrence of the specified element
in the list, or -1 if this element is not in the list.
Returns the index of the last occurrence of the specified element
in the list, or -1 if this element is not in the list.
Returns a list iterator over the elements in the list (in proper
sequence).
 Returns a list iterator over the elements in this list (in proper
sequence), starting at the specified position in the list.
 The specified index indicates the first element that would be
returned by an initial call to next.
 An initial call to previous would return the element with the
specified index minus one.
 Removes the element at the specified position in this list.
 Returns the element removed from the list.
 Replaces the element at the specified position in this list with
the specified element.
 Returns the element previously at that position.
 Returns a view of the portion of this list between the specified
fromIndex, inclusive, and toIndex, exclusive.
 The returned list is backed by this list: non-structural changes
in the returned list are reflected in this list, and vice-versa.
Page 148
Class ArrayList<E>
 The generic class ArrayList<E> (package: java.util) is an array implementation of the List<E>
interface that can dynamically change its size to accommodate more elements.
 This class is roughly equivalent to the class Vector<E>, except that it is unsynchronized.
 It has the following constructors:
ArrayList( )
Constructs an empty list with an initial capacity of ten.
ArrayList(Collection<? extends E> c)
Constructs a list containing the elements of the specified collection, in the order they are returned by the
collection's iterator.
ArrayList(int initialCapacity)
Constructs an empty list with the specified initial capacity.
Examples:

ArrayList <String> stringList new ArrayList<String>( );

ArrayList<Integer> integerList new ArrayList<Integer>( 20 );

ArrayList<Double> doubleList new ArrayList<Double>( 30 );
 The following table contains some additional instance methods of the class ArrayList<E>:
Method
void ensureCapacity(int minCapacity)
protected void
removeRange(int fromIndex, int toIndex)
© 2011 Gilbert Ndjatou
Description
Increases the capacity of this ArrayList instance, if necessary, to
ensure that it can hold at least the number of elements specified
by the minimum capacity argument.
Removes from this list all of the elements whose index is
between fromIndex, inclusive, and toIndex, exclusive. Shifts any
succeeding elements to the left (reduces their index). This call
shortens the list by (toIndex - fromIndex) elements. (If
toIndex==fromIndex, this operation has no effect.)
Page 149
Example C1
import java.util.ArrayList;
public class ProgramC1
{
public static void main( String[] args )
{
// create a new ArrayList of Strings with an initial capacity of 10
ArrayList< String > items = new ArrayList< String >( );
items.add( "red" );
items.add( 0, "yellow" );
// append an item to the list
// insert the value at index 0
// header
System.out.print( "Display list contents with counter-controlled loop:" );
// display the colors in the list
for ( int i = 0; i < items.size( ); i++ )
System.out.printf( " %s", items.get( i ) );
// display colors using foreach in the display method
display( items, "\nDisplay list contents with enhanced for statement:" );
items.add( "green" );
// add "green" to the end of the list
items.add( "yellow" );
// add "yellow" to the end of the list
display( items, "List with two new elements:" );
items.remove( "yellow" );
// remove the first "yellow"
display( items, "Remove first instance of yellow:" );
items.remove( 1 );
// remove item at index 1
display( items, "Remove second list element (green):" );
// check if a value is in the List
System.out.printf( "\"red\" is %sin the list\n",
items.contains( "red" ) ? "": "not " );
// display number of elements in the List
System.out.printf( "Size: %s\n", items.size() );
} // end main
// display the ArrayList's elements on the console
public static void display( ArrayList< String > list, String header )
{
System.out.print( header );
// display header
// display each element in items
for ( String item : list )
System.out.printf( " %s", item );
System.out.println();
// display end of line
} // end method display
} // end class ProgramC1
© 2011 Gilbert Ndjatou
Page 150
Example C2
import java.util.List;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class ProgramC2
{
public static void main( String[] args )
{
// add elements in colors array to list
String[] colors = { "MAGENTA", "RED", "WHITE", "BLUE", "CYAN" };
List< String > list = new ArrayList< String >( );
for ( String color : colors )
list.add( color );
// adds color to end of list
// add elements in removeColors array to removeList
String[] removeColors = { "RED", "WHITE", "BLUE" };
List< String > removeList = new ArrayList< String >( );
for ( String color : removeColors )
removeList.add( color );
// output list contents
System.out.println( "ArrayList: " );
for ( int count = 0; count < list.size( ); count++ )
System.out.printf( "%s ", list.get( count ) );
// remove from list the colors contained in removeList
removeColors( list, removeList );
// output list contents
System.out.println( "\n\nArrayList after calling removeColors: " );
for ( String color : list )
System.out.printf( "%s ", color );
} // end main
// remove colors specified in collection2 from collection1
private static void removeColors( Collection< String > collection1, Collection< String > collection2 )
{
Collection1.removeAll( collection2 );
} // end method removeColors
} // end class ProgramC2
© 2011 Gilbert Ndjatou
Page 151
Interface Iterator<E>
 The interface Iterator<E> (from the package java.util) has methods that allow you to access each
element of a collection in a loop.
 The interface ListIterator<E > (from the package java.util) which extends the interface Iterator<E>
has additional methods for a bidirectional traversal of a list, and the modification of its elements.
 The following table containg the interface Iterator<E> methods with their descriptions.
Methods with Description
boolean hasNext( ) Returns true if there are more elements in the collection. Otherwise, returns false.
Object next( )
Returns the next element. Throws NoSuchElementException if there is not a next element.
void remove( )
Removes the current element. Throws IllegalStateException if an attempt is made to call remove( ) that is not
preceded by a call to next( ).
 The following table contains the methods of the interface ListIterator<E>.
Methods with Description
void add(Object obj)
Inserts obj into the list in front of the element that will be returned by the next call to next( ).
boolean hasNext( ) Returns true if there is a next element. Otherwise, returns false.
boolean hasPrevious( ) Returns true if there is a previous element. Otherwise, returns false.
Object next( ) Returns the next element. A NoSuchElementException is thrown if there is not a next element.
int nextIndex( ) Returns the index of the next element. If there is not a next element, returns the size of the list.
Object previous( )
Returns the previous element. A NoSuchElementException is thrown if there is not a previous element.
int previousIndex( ) Returns the index of the previous element. If there is not a previous element, returns -1.
void remove( ) Removes the current element from the list. An IllegalStateException is thrown if remove( ) is
called before next( ) or previous( ) is invoked.
void set(Object obj)
Assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( ).
© 2011 Gilbert Ndjatou
Page 152
 In general, follow the steps below if you want to use an iterator to cycle through the contents of a
collections:
1.
Obtain an iterator to the start of the collection by calling the collection's iterator( ) method (or
one of the listIterator( ) method of a list).
2.
Set up a loop that makes a call to the hasNext( ) method: have the loop iterate as long as the
hasNext( ) method returns true.
3.
Within the loop, obtain each element by calling the next( ) method.
Example I1
Here is an example demonstrating both Iterator and ListIterator. It uses an ArrayList object, but the general
principles apply to any type of collection.
import java.util.*;
public class ProgramI1
{
public static void main(String args[ ])
{
// Create an array list and add elements to it
ArrayList<String> alist = new ArrayList<String>( );
alist.add("C");
alist.add("A");
alist.add("E");
alist.add("B");
alist.add("D");
alist.add("F");
// Use iterator to display contents of the list
System.out.print("\nOriginal contents of alist: ");
Iterator<String> itr = alist.iterator( );
while( itr.hasNext( ) )
{
Object element = itr.next( );
System.out.print(element + " ");
}
System.out.println( );
© 2011 Gilbert Ndjatou
Page 153
// Modify objects being iterated
ListIterator<String> litr = alist.listIterator( );
while( litr.hasNext( ) )
{
Object element = litr.next( );
litr.set(element + "-");
}
System.out.print("\nModified contents of alist: ");
itr = alist.iterator( );
while( itr.hasNext( ) )
{
Object element = itr.next( );
System.out.print(element + " ");
}
System.out.println( );
// Now, display the list backwards
System.out.print("\nModified list backwards: ");
while( litr.hasPrevious( ) )
{
Object element = litr.previous( );
System.out.print(element + " ");
}
System.out.println( );
}
}
This would produce the following output:
Original contents of alist: C A E B D F
Modified contents of alist: C- A- E- B- D- FModified list backwards: F- D- B- E- A- C-
© 2011 Gilbert Ndjatou
Page 154
Map<K, V> Interface
 A Map is an object that maps keys to values.
 A map cannot contain duplicate keys: Each key can map to at most one value.
 It models the mathematical function abstraction.
 The Map interface Map<K, V> (from the package java.util) includes the following instance methods:
Method
int size()
boolean isEmpty()
boolean containsKey(Object key)
boolean containsValue(Object value)
V get(Object key)
V put(K key, V value)
V remove(Object key)
void
putAll(Map<? extends K,? extends V> m)
void clear()
Set<K> keySet( )
Collection<V> values( )
© 2011 Gilbert Ndjatou
Description
Returns the number of key-value mappings in this map. If the map
contains more than Integer.MAX_VALUE elements, returns
Integer.MAX_VALUE.
Returns true if this map contains no key-value mappings.
Returns true if this map contains a mapping for the specified key.
Returns true if this map maps one or more keys to the specified
value.
Returns the value to which the specified key is mapped, or null if
this map contains no mapping for the key.
Associates the specified value with the specified key in this map
(optional operation). If the map previously contained a mapping for
the key, the old value is replaced by the specified value.
Removes the mapping for a key from this map if it is present
(optional operation).
Returns the value to which this map previously associated the key,
or null if the map contained no mapping for the key.
Copies all of the mappings from the specified map to this map
(optional operation). The effect of this call is equivalent to that of
calling put(k, v) on this map once for each mapping from key k to
value v in the specified map.
Removes all of the mappings from this map (optional operation).
The map will be empty after this call returns.
Returns a Set view of the keys contained in this map.
The set is backed by the map, so changes to the map are reflected in
the set, and vice-versa.
Returns a Collection view of the values contained in this map. The
collection is backed by the map, so changes to the map are reflected
in the collection, and vice-versa.
Page 155


The Java platform contains three general-purpose Map implementations: HashMap, TreeMap, and
LinkedHashMap.
Class HashMap< K, V> has the following constructors:
Contructor
HashMap( )
HashMap(int initialCapacity)
HashMap(Map<? extends K,? extends V> m)
Description
Constructs an empty HashMap with the default initial
capacity (16)
Constructs an empty HashMap with the specified initial
capacity
Constructs a new HashMap with the same mappings as the
specified Map.
Example M1

creating a Map instance:
Map<String, String> mapA = new HashMap<String, String> ( );
Map<String, String> mapB = new TreeMap<String, String> ( );

Adding elements to a Map:
mapA.put("key1", "element 1");
mapA.put("key2", "element 2");
mapA.put("key3", "element 3");

Obtain the value using the key:
String item = (String) mapA.get("key1");

Using an enhanced for statement to process the keys/values in the map:
//access via new for-loop
for(Object key : mapA.keySet( ) )
{
Object value = mapA.get(key);
<process the value/key>
}

You can iterate either the keys or the values of a Map. Here is how you do that:
// key iterator
Iterator<String> iterator = mapA.keySet().iterator( );
// value iterator
Iterator<String> iterator = mapA.values( ).iterator( );
© 2011 Gilbert Ndjatou
Page 156
Most often you iterate the keys of the Map and then get the corresponding values during the
iteration. Here is how it looks:
Iterator<String> iterator = mapA.keySet( ).iterator( );
while( iterator.hasNext( ) )
{
Object key = iterator.next( );
Object value = mapA.get(key);
}
Example M2

The following program generates a frequency table of the words found in its argument list.

The frequency table maps each word to the number of times it occurs in the argument list.
import java.util.*;
public class Freq
{
public static void main(String[] args)
{
Map<String, Integer> m = new HashMap<String, Integer>( );
// Initialize frequency table from command line
for ( String a : args )
{
Integer freq = m.get( a );
if( freq = = null )
freq = 1;
else
freq ++;
m.put(a, freq);
}
System.out.println(m.size( ) + " distinct words:");
System.out.println( m );
}
}
Try running this program with the command: java Freq if it is to be it is up to me to delegate
The program yields the following output:
8 distinct words:
{to=3, delegate=1, be=1, it=2, up=1, if=1, me=1, is=2}
© 2011 Gilbert Ndjatou
Page 157
Hands-On C1
Type and execute the programs in Example C1, Example C2, Example I1, and Example M2.
© 2011 Gilbert Ndjatou
Page 158
Data Streams
 Basic Input/output operations are performed in Java on either character or byte streams.
 A byte stream is an ordered sequence of 8-bit binary data,
 Whereas a character stream is an ordered sequence of 16-bit Unicode characters.
 However, communication over networks and between applications is mostly done using byte
streams.
 Streams are divided into two categories:
1. input streams that may only be read from, and
2. output stream that may only be written into.
 Byte-level input streams are represented in Java by subclasses of the abstract class InputStream
(package java.io). The following table lists all its low-levels subclasses.
 Byte-level output streams are represented by subclasses of the abstract class OutputStream
(package java.io). The second table that follows lists all its low-levels subclasses.
Byte-Level Input Stream Classes (package java.io)
Input Stream
Purpose of the Stream
AudioInputStream
ByteArrayInputStream
For reading the audio data contained in a stream
For reading bytes of data from an in-memory array
FileInputStream



For reading bytes of data from a file on the local file system.
is meant for reading streams of raw bytes such as image data.
For reading streams of characters, consider using the class FileReader.

FilterInputStream
ObjectInputStream
PipeInputStream
SequenceInputStream
StringBufferInputStream
© 2011 Gilbert Ndjatou
Contains some other input stream, which it uses as its basic source of data,
possibly transforming the data along the way or providing additional functionality.
 Overrides all methods of InputStream with versions that pass all requests to the
contained input stream.
 Subclasses of FilterInputStream may further override some of these methods and
may also provide additional methods and fields.
Enables entire objects to be read from a stream.
For reading bytes of data from a thread pipe.
For reading bytes of data from two or more low-level streams, switching from one
stream to the next when the end of the stream is reached.
For reading bytes of data from a string.
Page 159
Byte-Level Output Stream Classes (package java.io)
Input Stream
Purpose of the Stream

This class implements an output stream in which the data is written into a
byte array.

The buffer automatically grows as data is written to it.

For writing data to a file.

Whether or not a file is available or may be created depends upon the
underlying platform.

Some platforms, in particular, allow a file to be opened for writing by only
one FileOutputStream (or other file-writing object) at a time.

is meant for writing streams of raw bytes such as image data.

For writing streams of characters, consider using the class FileWriter.

This class is the superclass of all classes that filter output streams.

These streams sit on top of an already existing output stream (the underlying
output stream) which it uses as its basic sink of data,

but possibly transforming the data along the way or providing additional
functionality.

An ObjectOutputStream writes primitive data types and graphs of Java
objects to an OutputStream.

The objects can be read (reconstituted) using an ObjectInputStream.

Only objects that support the java.io.Serializable interface can be written to
streams.

A piped output stream can be connected to a piped input stream to create a
communications pipe.

The piped output stream is the sending end of the pipe.

Typically, data is written to a PipedOutputStream object by one thread and

data is read from the connected PipedInputStream by some other thread.
ByteArrayOutputStream
FileOutputStream
FilterOutputStream
ObjectOutputStream
PipedOutputStream
© 2011 Gilbert Ndjatou
Page 160
Methods of the abstract class InputStream (package java.io)
Method and Description
int available()throws IOException
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking
by the next invocation of a method for this input stream.
void close()throws IOException
Closes this input stream and releases any system resources associated with the stream.
void mark(int readlimit)
Marks the current position in this input stream. A subsequent call to the reset method repositions this stream at the last
marked position so that subsequent reads re-read the same bytes. readlimit is the maximum number of bytes that can
be reread.
boolean markSupported()
Tests if this input stream supports the mark and reset methods.
abstract int read()throws IOException
Reads the next byte of data from the input stream. The value byte is returned as an integer in the range 0 to 255. If no
byte is available because the end of the stream has been reached, the value -1 is returned.
int read(byte[] b) throws IOException
Reads some number of bytes from the input stream and stores them into the buffer array b. The number of bytes
actually read is returned as an integer.
int read(byte[] b, int off, int len) throws IOException
Reads up to len bytes of data from the input stream into array b, starting with element b[off]. The number of bytes
actually read is returned as an integer.
void reset()throws IOException
Repositions this stream to the position at the time the mark method was last called on this input stream.
long skip(long n) throws IOException
Skips over and discards n bytes of data from this input stream.
Methods of the abstract class OutputStream (package java.io)
Method and Description
void close()
Closes this output stream and releases any system resources associated with this stream.
void flush()
Flushes this output stream and forces any buffered output bytes to be written out.
void write(byte[] b)
Writes b.length bytes from the specified byte array to this output stream.
void write(byte[] b, int off, int len)
Writes len bytes from the specified byte array starting at offset off to this output stream.
abstract void write(int b)
Writes the specified byte to this output stream.
© 2011 Gilbert Ndjatou
Page 161
Properties of Files and Directories in Java
 The way you write the pathname string of a file or directory is operating system dependent:
For example, the file lab1.java which is in the subdirectory programs of the directory CS4501
Is specified in Windows as: CS4501\programs\lab1.java
And in UNIX as: CS4501/programs/lab1.java
 However, in Java, you can use the class File to create an abstract representation of a file or a directory
pathname that is operating system independent.
 This class has the following constructors for creating abstract pathnames:
public File(String pathname)
Creates a new File instance by converting the given pathname string into an abstract pathname.
Example:
File
abstractfn
= File(“\CS40501\java\programs\lab1.java”);
public File(String parent, String child)
Creates a new File instance from a file’s directory pathname string and a file name string.
Example:
File abstractfn = File(“\CS40501\java\programs\”,“lab1.java”);
public File(File parent, String child)
Creates a new File instance from a directory abstract pathname and a file name string.
Example:
File abstractpn = File(“\CS40501\java\programs\”,“lab1.java”);
File abstractfn = File(abstractpn,“lab1.java”);
 This class also has instance methods that return the properties of a file/directory such as:
 String getName( )
returns the name of a file/directory
 String getPath( )
returns the pathname of a file/directory
 int length( )
returns the number of bytes in a file/directory
 boolean canWrite( )
returns true if you can write into the file and false otherwise
 boolean isDirectory( ) returns true if it is a directory and false otherwise
 String getParent( )
returns the pathname of the directory of a file or subdirectory
© 2011 Gilbert Ndjatou
Page 162
Example FD1
 The following program receives the name of a file as a command line argument and does the following:
1. Print the name of the file.
2. Print the pathname of the file
3. Print either true/false depending on whether you can write into the file
4. Print either true/false depending on whether the file is a directory
5. Print the number of byte (length) of the file
6. Print the pathname of the directory that contains this file.
/*------------ Program Class GetFileProperties --------------------------*/
/* receive the pathname of a file as a command line argument and
create the corresponding File instance and output some of its properties
*/
import
java.io.*;
public class GetFileProperties
{
public static void main( String [ ] args )
{
/*----------- create the corresponding File instance ------------*/
File file = new File( args[0] )
/*----------- output the name of the file -----------------------*/
System.out.println( “Name:\t” + file.getName());
/*---------- output the pathname of the file --------------------*/
System.out.println( “Path:\t” + file.getPath( ));
/*--------- Can I write into the file ---------------------------*/
System.out.println(“Can I write into the file?:\t”+file.canWrite());
/*--------- is the file a directory? ----------------------------*/
System.out.println( “Is file a directory?:\t” + file.isDirectory( ));
/*----------output the length of the file -----------------------*/
System.out.println( “Length:\t” + file.length( ));
/*---------output the pathname of the file directory-------------*/
System.out.println( “Directory:\t” + file.getParent( ));
}
}
Hands-On FD1
Write and execute the program in example FD1 as follows:
java GetFileProperties GetFileProperties.java
© 2011 Gilbert Ndjatou
Page 163
Byte-Level File Input / Output
Input
 You perform a byte-level input from a file by using the subclass FileInputStream (package java.io) of
the class InputStream.
 This class is meant for reading streams of raw bytes such as image data.
 It has the following constructors:
public FileInputStream(String name)

Creates a FileInputStream by opening a connection to an actual file (the file named by the pathname name in
the file system).
public FileInputStream(File fileobj)

throws FileNotFoundException
throws FileNotFoundException
Creates a FileInputStream by opening a connection to an actual file (the file represented by the File object
fileobj in the file system).
public FileInputStream(FileDescriptor fdObj)

Creates a FileInputStream by using the file descriptor fdObj which represents an existing connection to an
actual file in the file system.
System.in
 is the standard input stream.
 A java program automatically creates this input stream instance (in the class System) and associates it
to the standard input device (which is by default the keyboard) when it starts execution.
 System.in is an instance of the class InputStream.
Output
 You perform a byte-level output to a file by using the subclass FileOutputStream (package java.io)
of the class OutputStream.
 This class is meant for writing streams of raw bytes such as image data.
 It class has the following constructors:
public FileOutputStream(String name)

throws FileNotFoundException
Creates a file output stream to write to the file with the specified name (the file named by the pathname name
in the file system).
© 2011 Gilbert Ndjatou
Page 164
public FileOutputStream(String name, Boolean append)
FileNotFoundException
throws

Creates a file output stream to write to the file with the specified name (the file named by the pathname name in the
file system).

If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
public FileOutputStream(File fileobj)

throws FileNotFoundException
Creates a file output stream to write to the file represented by the specified File object.
public FileOutputStream(File fileobj, Boolean append)
FileNotFoundException
throws

Creates a file output stream to write to the file represented by the specified File object.

If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
public FileOutputStream(FileDescriptor fdObj)

Creates a file output stream to write to the specified file descriptor, which represents an existing connection to an
actual file in the file system.
System.out
 is the standard output stream.
 A java program automatically creates this output stream instance (in the class System) and associates it to
the standard output device (which is by default the display output) when it starts execution.
 System.out is an instance of the class PrintStream
FilterOutputStream).
(which is a subclass of the class
System.err
 is the standard error output stream.
 A java program automatically creates this output stream instance (in the class System) and associates it to
the standard output device (which is by default the display output) when it starts execution.
 By convention, this output stream is used to display error messages or other information that should
come to the immediate attention of a user even if the principal output stream, the value of the variable
out, has been redirected to a file.
 System.err is an object of the class PrintStream
FilterOutputStream).
© 2011 Gilbert Ndjatou
(which is a subclass of the class
Page 165
Example FIO1
 The following program can be executed in one of the following ways:
1. With a command line argument that is the name of a text file with the following content: A B C D E F
2. Without a command line argument. But the input values A B C D E F are entered at the keyboard.
 This program reads the input values and outputs those values to the display output as bytes.
import java.io.*;
public class TestByteInput
{
public static void main(String args[])
{
InputStream input;
try
{
// Create an input stream
if (args.length = 1) // reading from the specified text file
input = new FileInputStream(args[0]);
else
// read from the keyboard (standard input)
input = System.in;
// Read the bytes of data until end of file (EOF) is reached
int data = input.read();
while (data != -1)
{
// Send byte to standard output
System.out.print( data );
data = input.read();
}
// Close the file
input.close();
}
catch (IOException ioe)
{
System.err.println ("I/O error - " + ioe);
}
}
}
Hands-On FIO1
Execute the program in Example FIO1 as specified in the example, first without a command line argument, and
second with one.
© 2011 Gilbert Ndjatou
Page 166
Example FIO2
 The following program must be executed with two command line arguments:

The first is the name of a text file with the following content: A B C D E F and

The second is the name of a file that will be created by the program for output: note that the filename
extension of this file must be .txt.
 This program reads the input values from the first file and outputs those values to the second file as bytes.
import java.io.*;
public class TestByteIO
{
public static void main(String args[])
{
/*---two command line arguments are required for this program --*/
if( args.lenth != 2 )
{
System.err.println(
“You must execute the program with two command line arguments”);
System.exit(1);
}
try
{
// Create an input stream for the first argument
FileInputStream input = new FileInputStream(args[0]);
// Create an output stream for the second argument
FileOutputStream output = new FileOutputStream(args[1]);
// Read bytes of data until end of file (EOF) is reached
int data = input.read();
while (data != -1)
{
// Send byte to the output file
output.write ( data );
data = input.read();
}
// Close both files
input.close();
output.close();
}
catch (IOException ioe)
{
System.err.println ("I/O error - " + ioe);
}
}
}
© 2011 Gilbert Ndjatou
Page 167
Hands-On FIO2
Execute the program in Example FIO2 as specified in the example and then print the contents of both files.
Exercise FIO1
Modify the program in Example FIO2 to close the files in a finally clause so the files will be closed even if an exception
is thrown.
© 2011 Gilbert Ndjatou
Page 168
Filter Streams
 In order to overcome the limitations of byte-level input/output, Java provides filter streams that add
additional functionality to existing streams in one of the following ways:

By processing data in some form such as buffering for performance (instead of processing data one
byte at a time) or

By offering additional methods that allow data to be read/written in a different manner such as
primitive data types.
 In order to add additional functionality to an existing stream, a filter stream must first be connected to
that stream.
 Input filter streams are subclasses of the class FilterInputStream (package java.io) and can be connected to
any byte-level input stream or even another input filter stream, and
 Output filter streams are subclasses of the class FilterOutputStream (package java.io) and can be connected
to any byte-level output stream or even another output filter stream.
 You connect a filter stream to an existing stream instance by using a constructor in which the existing
stream instance is passed as an argument to create an instance of the filter stream.
Example:

We connect the filter stream DataInputStream to the instance finput of the FileInputStream as
follows:
FileInputStream finput
=
new FileInputStream(“datafile.txt”);
DataInputStream dinput
=
new DataInputStream( finput );
 When you connect an input filter stream to an input stream instance, input from that input stream
instance is done by using the input filter stream instance instead, and
 When you connect an output filter stream to an output stream instance, output to that output stream
instance is done by using the output filter stream instance instead.
 However, read/write operations on the underlying stream instance can still take place, but not at the same
time as an operation on the filter stream instance.
 The most commonly used input filter streams are:
BufferedInputStream
Provide buffering of input data to improve efficiency
DataInputStream
Offer methods to read primitive data type values, such as int, float, double, or
even a line of text from an input stream.
 The most commonly used output filter streams are:
BufferedOutputStream
Provides buffering of output data to improve efficiency
DataOutputStream
Offer methods to output primitive datatype values such as int, double in binary
PrintStream
Offers additional methods for writing lines of text, and other datatypes as text
© 2011 Gilbert Ndjatou
Page 169
Class BufferedInputStream
 The purpose of I/O buffering is to improve system performance:

Rather than reading a byte at a time, a large number of bytes are read together the first time the
read( ) method is invoked.

When an attempt is made to read subsequent bytes, they are taken from the buffer, not the underlying
input stream.

This improves data access time and can reduce the number of times an application blocks for input.
 The class BufferedInputStream has no additional methods.
 Its most commonly used constructors are described as follows:
Constructor and Description
BufferedInputStream (InputStream input)
Creates a buffered stream that will read from the specified InputStream object.
BufferedInputStream (InputStream input, int bufferSize) throws java.lang.IllegalArgumentException
 Creates a buffered stream, of the specified size, which reads from the InputStream object passed as a
parameter.
 It allows you to specify a size, which can improve efficiency if large amounts of data are going to be
read.
Class DataInputStream

The class DataInputStream (package:Java.io) implements the interface DataInput (package:Java.io).

It offers methods that an application can use to read primitive data values from the underlying input
stream in a machine-independent way.

An application uses a DataOutputStream to write data that can later be read by a data input stream.

The following is the only field (instance variable) of the class DataInputStream:
protected InputStream in // This is the input stream to be filtered.
 The most commonly used constructors and methods of the class DataInputStream are described as
follows:
© 2011 Gilbert Ndjatou
Page 170
Method/Constructor and Description
public DataInputStream(InputStream in)
Creates a DataInputStream that uses the specified underlying InputStream.
int read(byte[] b) throws IOException
 Reads bytes from the contained input stream and stores them into the buffer array b.
 The number of bytes actually read is returned as an integer.
 This method blocks until input data is available, end of file is detected, or an exception is thrown.
int read(byte[] b, int off, int len) throws IOException
 Reads up to len bytes of data from the contained input stream into array b.
 The first byte read is stored at b[off], the second at b[off +1] . . ., etc.
 It returns the number of bytes actually read.
boolean readBoolean( ) throws IOException
Reads one input byte and returns true if that byte is nonzero, and false if it is zero.
byte readByte( ) throws IOException
Reads and returns one input byte.
char readChar( ) throws IOException
Reads two input bytes and returns a char value.
double readDouble( ) throws IOException
Reads eight input bytes and returns a double value.
float readFloat( ) throws IOException
Reads four input bytes and returns a float value.
void readFully(byte[ ] b) throws IOException
 Reads some bytes from an input stream and stores them into the buffer array b.
 The number of bytes read is equal to the length of b.
 The method blocks until b.length bytes of input data are available, or End of file is detected, or an I/O
error occurs.
void readFully(byte[] b, int off, int len) throws IOException
 Reads len bytes from an input stream and stores them into the buffer array b starting at b[off].
 The method blocks until len bytes of input data are available, or End of file is detected, or an I/O
error occurs.
int readInt( ) throws IOException
Reads four input bytes and returns an int value.
long readLong( ) throws IOException
Reads eight input bytes and returns a long value.
short readShort( ) throws IOException
Reads two input bytes and returns a short value.
int readUnsignedByte( ) throws IOException
Reads one input byte, zero-extends it to type int, and returns the result.
© 2011 Gilbert Ndjatou
Page 171
int readUnsignedShort( ) throws IOException
Reads two input bytes and returns an int value in the range 0 through 65535.
String readUTF( ) throws IOException
Reads in a string that has been encoded using a modified UTF-8 format and returns it.
static String readUTF(DataInput in) throws IOException
Reads from the specified stream the modified UTF-8 format representation of a string and returns it.
int



skipBytes(int n) throws IOException
Makes an attempt to skip over n bytes of data from the input stream, discarding the skipped bytes.
However, it may skip over some smaller number of bytes, possibly zero.
It returns the number of bytes actually skipped.
Class BufferedOutputStream
 The purpose of I/O buffering is to improve system performance:

Rather than writing a byte at a time to the output stream, bytes are written instead into a buffer, and
when the buffer is full (or when a request to flush the buffer is made), the buffer content is dumped
to the output stream to which the buffered stream is connected.
 The class BufferedOutputStream has no additional methods.
 However, the flush( ) method has been overridden: it will flush the content of a buffer, sending it
immediately to the output stream it is connected to.
 This is particularly important in networking, as a protocol request can't be sent if it is still stuck in
the buffer while the remote program is waiting for a response.
 Its most commonly used constructors are described as follows:
Constructor and Description
BufferedoutputStream (OutputStream output)
Creates a buffer ( of 521 bytes by default) for writing to the specified OutputStream object.
BufferedOutputStream(OutputStream output, int bufferSize) throws java.lang.IllegalArgumentException
Creates a buffer ( with the specified size) for writing to the specified OutputStream object.
© 2011 Gilbert Ndjatou
Page 172
Class DataOutputStream

The class DataOutputStream (package:Java.io) implements the interface DataOutput
(package:Java.io).

It offers methods that an application can use to write primitive data type values to the underlying output
stream in a machine-independent way.

Most of the read methods of DataInputStream have a corresponding write method mirrored in
DataOutputStream.

This allows you to write datatype values to a file or another type of stream, and to have them read
back by another Java application without any compatibility issues over how primitive datatypes are
represented by different hardware and software platforms.

The following is the only field (instance variable) of the class DataInputStream:
protected int written
// The number of bytes written to the data output stream so far
protected OutputStream out // This is the underlying output stream to be filtered
 The most commonly used constructors and methods of the class DataOutputStream are described as
follows:
Method/Constructor and Description
public DataOutputStream(OutputStream out)
 Creates a new data output stream object to write data to the specified underlying output stream. The
counter written is set to zero.
void flush( ) throws IOException
 Flushes this data output stream. This forces any buffered output bytes to be written out to the stream.
int size( )
 Returns the current value of the counter written, the number of bytes written to this data output
stream so far.
void write(byte[] b, int off, int len) ) throws IOException
 Writes len bytes from the specified byte array starting at offset off to the underlying output stream.
void write(int b) throws IOException
 Writes the specified byte (the low eight bits of the argument b) to the underlying output stream.
void writeBoolean(boolean v) throws IOException
 Writes a boolean to the underlying output stream as a 1-byte value.
 The value true is written out as the value (byte)1;
 the value false is written out as the value (byte)0.
void writeByte(int v) throws IOException
 Writes out a byte to the underlying output stream as a 1-byte value.
© 2011 Gilbert Ndjatou
Page 173
void writeBytes(String s) throws IOException
 Writes out the string to the underlying output stream as a sequence of bytes.
 Each character in the string is written out, in sequence, by discarding its high eight bits.
void writeChar(int v) throws IOException
 Writes a char to the underlying output stream as a 2-byte value, high byte first.
void writeChars(String s) throws IOException
 Writes a string to the underlying output stream as a sequence of characters.
 Each character is written to the data output stream as if by the writeChar method.
void writeDouble(double v) throws IOException
 Converts the double argument to a long using the doubleToLongBits method in class Double, and
 then writes that long value to the underlying output stream as an 8-byte quantity, high byte first.
void writeFloat(float v) throws IOException
 Converts the float argument to an int using the floatToIntBits method in class Float, and
 then writes that int value to the underlying output stream as a 4-byte quantity, high byte first.
void writeInt(int v) throws IOException
 Writes an int to the underlying output stream as four bytes, high byte first.
void writeLong(long v) throws IOException
 Writes a long to the underlying output stream as eight bytes, high byte first.
void writeShort(int v) throws IOException
 Writes a short to the underlying output stream as two bytes, high byte first.
void writeUTF(String str) throws IOException
 Writes a string to the underlying output stream using modified UTF-8 encoding in a machineindependent manner.
Class PrintStream
 The class PrintStream (package:Java.io) provides a convenient way to print primitive datatypes as text
using the print(..) method, and the println(..) method (to print and move to next line).
 The most commonly used constructors and methods of the class PrintStream are described as follows:
• PrintStream (OutputStream output)— creates a print stream for printing of datatypes as text.
• PrintStream (OutputStream output, boolean flush)— creates a print stream for printing of datatypes as text.
If the specified boolean flag is set to "true," whenever a byte array, println method, or newline character is
sent, the underlying buffer will be automatically flushed.
Methods
• boolean checkError()— automatically flushes the output stream and checks to see if an error has
occurred. Instead of throwing an IOException, an internal flag is maintained that checks for errors.
• void print(boolean value)— prints a boolean value.
© 2011 Gilbert Ndjatou
Page 174
• void print(char character)— prints a character value.
• void print(char[] charArray)— prints an array of characters.
• void print(double doubleValue)— prints a double value.
• void print(float floatValue)— prints a float value.
• void print(int intValue)— prints an int value.
• void print(long longValue)— prints a long value.
• void print(Object obj)— prints the value of the specified object's toString() method.
• void print(String string)— prints a string's contents.
• void println()— sends a line separator (such as '\n'). This value is system dependent and determined by
the value of the system property "line.separator."
• void println(char character)— prints a character value, followed by a println().
• void println(char[] charArray)— prints an array of characters, followed by a println().
• void println(double doubleValue)— prints a double value, followed by a println().
• void println(float floatValue)— prints a float value, followed by a println().
• void println(int intValue)— prints an int value, followed by a println().
• void println(long longValue)— prints a long value, followed by a println().
• void println(Object obj)— prints the specified object's toString() method, followed by a println().
• void println(String string)— prints a string followed by a line separator.
• protected void setError()— modifies the error flag to a value of "true."
© 2011 Gilbert Ndjatou
Page 175
Reading and Writing Primitive Types
Example FIO3
 This program outputs (using a DataOutputStream filter) the elements of one dimensional array of 5 integer values
into the binary file fio3.data, follow by the elements of a one dimensional array of 5 double precision values, and
finally the elements of a one dimensional array of 5 String values.
 It then reads the elements of these arrays from that file (using a DataInputStream filter) and outputs them into the
character-based file fio3.txt (using the PrintStream filter).
import java.io.*;
public class TestFilterIO3
{
public static void main(String args[])
{
int[] ilist = { 2, 13, 24, 35, 46 };
double[] dlist = { 3.5, 13.6, 24.7, 35.8, 46.9 };
String[] slist = { “John”, “Mark”, “Peter”, “Ann”, “Vicky”};
try
{
/*--- Create a byte-based output stream for the file: fio3.data---*/
FileOutputStream foutput = new FileOutputStream(“fio3.data”);
/*------- connect a DataOutputStream filter to this stream-------*/
DataOutputStream doutput = new DataOutputStream( foutput );
/*-----write the elements of the arrays into this file -----------*/
for( int i = 0; i < 5 ; i++ )
doutput.writeInt( ilist[ i ] );
for( int i = 0; i < 5 ; i++ )
doutput.writeDouble( dlist[ i ] );
for( int i = 0; i < 5 ; i++ )
doutput.writeUTF( slist[ i ] );
doutput.close( );
foutput.close( );
/*--- Create a byte-based input stream for the file: fio3.data---*/
FileInputStream finput = new FileInputStream(“fio3.data”);
/*------- connect a DataInputputStream filter to this stream-----*/
DataInputStream dinput = new DataInputStream( finput );
/*--- Create an output stream for the file: fio3.txt---*/
FileOutputStream newfoutput = new FileOutputStream(“fio3.txt”);
/*------- connect a PrintStream filter to this stream-----*/
PrintStream poutput = new PrintStream( newfoutput );
© 2011 Gilbert Ndjatou
Page 176
/*-----read the content of the binary file fio3.data and write it
into the text file fio3.txt ----------------------------*/
for( int i = 0; i < 5 ; i++ )
{
int inun =
dinput.readInt( );
poutput.println( inum );
}
for( int i = 0; i < 5 ; i++ )
{
double dnum = dinput.readDouble( );
poutput.println( dnum );
}
for( int i = 0; i < 5 ; i++ )
{
String st = dinput.readUTF( );
poutput.println( st );
}
// Close the files
dinput.close( );
finput.close( );
poutput.close();
newfoutput.close( );
}
catch (IOException ioe)
{
System.err.println ("I/O error - " + ioe);
}
}
}
Hands-On FIO3
Execute the program in Example FIO3 and display the content of the file fio3.txt.
Note that you cannot display the content of the file fio3.data because it is a binary file.
Buffered Input / Output
Example FIO4
This program does the same thing as the program in Example FIO3. However,
 The output to the file fio3.data is buffered by using the BufferedOutputStream filter, and
 The input from the file fio3.data is buffered by using the BufferedInputStream filter.
© 2011 Gilbert Ndjatou
Page 177
import java.io.*;
public class TestFilterIO4
{
public static void main(String args[])
{
int[] ilist = { 2, 13, 24, 35, 46 };
double[] dlist = { 3.5, 13.6, 24.7, 35.8, 46.9 };
String[] slist = { “John”, “Mark”, “Peter”, “Ann”, “Vicky”};
try
{
/*--- Create a byte-based output stream for the file: fio4.data---*/
FileOutputStream foutput = new FileOutputStream(“fio3.data”);
/*--- connect a BufferedOutputStream filter to this stream---*/
BufferedOutputStream boutput = new BufferedOutputStream(foutput);
/*- connect a DataOutputStream filter to the BufferedOutputStream
filter --*/
DataOutputStream doutput = new DataOutputStream( boutput );
/*-----write the elements of the arrays into this file -----------*/
for( int i = 0; i < 5 ; i++ )
doutput.writeInt( ilist[ i ] );
for( int i = 0; i < 5 ; i++ )
doutput.writeDouble( dlist[ i ] );
for( int i = 0; i < 5 ; i++ )
doutput.writeUTF( slist[ i ] );
doutput.close( );
boutput.close( );
foutput.close( );
/*--- Create a byte-based input stream for the file: fio4.data---*/
FileInputStream finput = new FileInputStream(“fio3.data”);
/*--- connect a BufferedInputStream filter to this stream---*/
BufferedInputStream binput = new BufferedInputStream(finput);
/*- connect a DataInputStream filter to the BufferedInputStream
filter --*/
DataInputStream dinput = new DataInputStream( binput );
/*--- Create an output stream for the file: fio4.txt---*/
FileOutputStream newfoutput = new FileOutputStream(“fio3.txt”);
/*------- connect a PrintStream filter to this stream-----*/
PrintStream poutput = new PrintStream( newfoutput );
© 2011 Gilbert Ndjatou
Page 178
/*-----read the content of the binary file fio3.data and write it
into the text file fio4.txt ----------------------------*/
for( int i = 0; i < 5 ; i++ )
{
int inun =
dinput.readInt( );
poutput.println( inum );
}
for( int i = 0; i < 5 ; i++ )
{
double dnum = dinput.readDouble( );
poutput.println( dnum );
}
for( int i = 0; i < 5 ; i++ )
{
String st = dinput.readUTF( );
poutput.println( st );
}
// Close the files
dinput.close( );
binput.close( );
finput.close( );
poutput.close();
newfoutput.close( );
}
catch (IOException ioe)
{
System.err.println ("I/O error - " + ioe);
}
}
}
Hands-On FIO4
Execute the program in Example FIO4 and display the content of the file fio4.txt.
Note that you cannot display the content of the file fio4.data because it is a binary file.
Exercise FIO2
Wire a program that has the following declarations of variables:
int inum = 7; double dnum = 10.5; String name = “John Doe”;
This program outputs (using a DataOutputStream filter) the values of these variables into the binary file efio2.data. It
then reads these values from that file (using a DataInputStream filter) and outputs them into the character-based file
efio2.txt (using the PrintStream filter).
© 2011 Gilbert Ndjatou
Page 179
Exercise FIO3
Rewrite the program in Exercise FIO2 with the following changes:
 The output to the file efio2.data is buffered by using the BufferedOutputStream filter, and
 The input from the file efio2.data is buffered by using the BufferedInputStream filter.
© 2011 Gilbert Ndjatou
Page 180
Introduction to Multithreading
 A multitasking operating system is an operating system that allows two or more applications to
execute at the same time.
 These applications execute either as processes or as threads.
 In a multithreading system (a system in which two or more threads can execute at the same time),
two different threads may execute the same program code or completely separate program codes.
 Treads that execute the same program code share the application-wide resources such as memory,
data, and files, but each one has its own method-call stack and program counter.
 You can create two or more threads in a Java program, allowing one thread to perform a task while
the other one is doing something else.
 In a computer system with only one CPU, the operating system continually makes decisions about
what thread should be executing and for how long.
 In some systems, threads are allocated priority levels such that a thread with a higher priority gets
the CPU before any thread with a lower priority.
 When a code running in some thread creates a new Thread object, the new thread has its priority
initially set equal to the priority of the creating thread.
 The fact that the order in which threads are executed depends on the operating system may be a
problem for an application developer: if the order of threads execution cannot be predicted, it is
impossible to know which task will be completed before the other in a program.
 In Java, you write the code to be executed by a thread in one of the following ways:
 By defining a subclass of class Thread (package: java.lang).
 By defining a class that implements the interface Runnable (package: java.lang).
 You execute/create a thread in one of the following ways:
1. By explicitly calling the class Thread instance method start in the method main, or
2. by using the Executor Framework to manage threads.
 In these notes, threads will be executed by calling the class Thread instance method start.
© 2011 Gilbert Ndjatou
Page 181
Writing a Thread Code by Defining a Subclass of Class
Thread
 You write the code to be executed by a thread by using a subclass of the class Thread (package:
java.lang) as follows:

Override the method run of class Thread with the code to be executed by the tread.
 You create/execute a thread (whose code is defined by using a subclass of the class Thread) in a program
by defining an instance of this subclass and then invoking the instance method start of class Thread on
it.
Class Thread
 This class is an implementation of the interface Runnable.
 The following table contains some of its constructors, methods, and static (class) variables.
Constructor/Method/Variable
Description
static int MAX_PRIORITY
The maximum priority that a thread can have.
static int MIN_PRIORITY
The minimum priority that a thread can have.
static int NORM_PRIORITY
The default priority that is assigned to a thread.
Thread( )
Allocates a new Thread object. This constructor has the same effect
as Thread (null, null, gname), where gname is a newly generated
name. Automatically generated names are of the form "Thread-"+n,
where n is an integer.
Thread(Runnable target)
Allocates a new Thread object. This constructor has the same effect
as Thread (null, target, gname), where gname is a newly generated
name. Automatically generated names are of the form "Thread-"+n,
where n is an integer.
Thread(Runnable target, String name)
Allocates a new Thread object so that it has target as its run object,
and the specified name as its name.
static Thread currentThread( )
Returns a reference to the currently executing thread object.
Long getId()
Returns the identifier of this Thread.
String getName()
Returns this thread's name.
Int getPriority()
Returns this thread's priority.
static Boolean holdsLock(Object obj)
Returns true if and only if the current thread holds the monitor lock
on the specified object.
© 2011 Gilbert Ndjatou
Page 182
void interrupt( )
Interrupts this thread.
static boolean interrupted()
Tests whether the current thread has been interrupted.
boolean isAlive()
Tests if this thread is alive.
boolean isDaemon()
Tests if this thread is a daemon thread.
boolean isInterrupted()
Tests whether this thread has been interrupted.
void join()
Waits for this thread to die.
void join(long millis)
Waits at most millis milliseconds for this thread to die.
void run()
If this thread was constructed using a separate Runnable run object,
then that Runnable object's run method is called; otherwise, this
method does nothing and returns.
void setName(String name)
Changes the name of this thread to be equal to the argument name.
Void setPriority(int newPriority)
Changes the priority of this thread.
static void sleep(long millis)
Causes the currently executing thread to sleep (temporarily cease
execution) for the specified number of milliseconds, subject to the
precision and accuracy of system timers and schedulers.
void start( )
Causes this thread to start execution; the Java Virtual Machine calls
the run method of this thread.
static void yield()
A hint to the scheduler that the current thread is willing to yield its
current use of a processor.
Example T1
 In this example, we create two classes FirstThreadT and SecondThreadT that are subclasses of class
Thread as follows:

The code in class FirstThreadT instructs a thread to display the numbers 1, 2, 3, 4, and 5 with a
one second delay in displaying the next number.

The code in class SecondThreadT instructs a thread to display the numbers 1, 2, 3, 4 and 5 with a
two second delay in displaying the next number.
 In the method main of our program (defined in the class ThreadCreatorT), we create two threads that
execute the code in the class FirstThreadT and one thread that executes the code in the class
SecondThreadT.
© 2011 Gilbert Ndjatou
Page 183
//This class is defines a thread by extending the class Thread.
import java.lang.Thread;
public class FirstThreadT extends Thread
{
//This method will be executed when this thread is started
public void run( )
{
// get the name of the current thread: (Thread.currentThread( )) could be replaced with this
String treadName = (Thread.currentThread( )).getName( );
//Looping from 1 to 5 to display numbers from 1 to 5
for ( int i=1; i<=5; i++)
{
//Displaying the numbers from this thread
System.out.println( "Messag from Thread : " + treadName + "\t:" +i );
// taking a delay of one second before displaying next number
try
{
Thread.sleep (1000);
}
catch (InterruptedException interruptedException)
{
/*Interrupted exception will be thrown when a sleeping or waiting thread is interrupted. */
System.out.println( "First Thread is interrupted when it is sleeping" + interruptedException);
}
}
}
}
//This class defines a thread by extending the class Thread.
import java.lang.Thread;
public class SecondThreadT extends Thread
{
//This method will be executed when this thread is started
public void run( )
{
// get the name of the current thread
String treadName = (Thread.currentThread( )).getName( );
//Looping from 1 to 5 to display numbers from 1 to 5
for ( int i=1; i<=5; i++)
{
//Displaying the numbers from this thread
System.out.println( "Messag from Thread : " + treadName + "\t:" +i );
//taking a delay of one second before displaying next number
try
{
Thread.sleep (2000);
}
© 2011 Gilbert Ndjatou
Page 184
catch (InterruptedException interruptedException)
{
/*--Interrupted exception is thrown when a sleeping or waiting thread is interrupted.---*/
System.out.println( "Thread is interrupted when it is sleeping" + interruptedException);
}
}
}
}
/*------------ create three threads: the first two executing the code defined in the class FirstThreadT, and
the last one executing the code defined in the class SecondThreadT----------------------------------*/
public class ThreadCreatorT
{
public static void main( String[ ] args )
{
System.out.println( "I am about to create threads");
/*--------- create three threads ------------------------ */
FirstThreadT thread1 = new FirstThreadT( );
FirstThreadT thread2 = new FirstThreadT( );
SecondThreadT thread3 = new SecondThreadT( );
System.out.println( " Threads are created and will start soon");
/*------------- start all three threads-----------------*/
thread1.start( );
thread2.start( );
thread3.start( );
System.out.println(" main is done");
}
}
© 2011 Gilbert Ndjatou
Page 185
Writing the Code of a Thread by defining a class that
implements the interface Runnable
 The interface Runnable declares only one method named run.
 A class that implements this interface must write the code to be executed by a thread in the method run.
 You create/execute a thread (whose code is defined by implementing the interface runnable ) as follow:
a) Define an instance of this subclass.
b) Define an instance of the class Thread by passing to the constructor the instance of the subclass
defined in step a).
c) Invoke the instance method start of class Thread on the object defined in step b).
Example T2
 In this example, we create two classes named FirstThreadR and SecondThreadR that implement the
Runnable interface as follows:

The code in class FirstThreadR instructs a thread to display the numbers 1, 2, 3, 4, and 5 with a
one second delay in displaying the next number.

The code in class SecondThreadR instructs a thread to display the numbers 1, 2, 3, 4 and 5 with a
two second delay in displaying the next number.
 In the method main of our program (defined in the class ThreadCreatorR), we create two threads that
execute the code in the class FirstThreadR and one thread that executes the code in the class
SecondThreadR.
import java.lang.*
//This class defines the code of a thread by implementing the "Runnable" interface.
public class FirstThreadR implements Runnable
{
//This method will be executed when this thread is started
public void run( )
{
// get the name of the current thread
String treadName = (Thread.currentThread( )).getName( );
//Looping from 1 to 5 to display numbers from 1 to 5
for ( int i=1; i<=5; i++)
{
//Displaying the numbers from this thread
System.out.println( "Messag from Thread : " + treadName + "\t:" +i );
© 2011 Gilbert Ndjatou
Page 186
// taking a delay of one second before displaying next number
try
{
Thread.sleep (1000);
}
catch ( InterruptedException interruptedException )
{
/*--Interrupted exception is thrown when a sleeping or waiting thread is interrupted.---*/
System.out.println( "First Thread is interrupted while it is sleeping" + interruptedException);
}
}
}
}
import java.lang.*
//This class defines the code of a thread by implementing the "Runnable" interface.
public class SecondThreadR implements Runnable
{
//This method will be executed when this thread is started
public void run()
{
// get the name of the current thread
String treadName = (Thread.currentThread( )).getName( );
//Looping from 1 to 5 to display numbers from 1 to 5
for ( int i=1; i<=5; i++)
{
//Displaying the numbers from this thread
System.out.println( "Messag from Thread : " + treadName + "\t:" +i );
//take a delay of one second before displaying next number
try
{
Thread.sleep (2000);
}
catch (InterruptedException interruptedException)
{
/*--Interrupted exception is thrown when a sleeping or waiting thread is interrupted.---*/
System.out.println( "Thread is interrupted when it is sleeping" + interruptedException );
}
}
}
}
© 2011 Gilbert Ndjatou
Page 187
/*------------ create three threads: the first two executing the code defined in the class FirstThreadR, and
the last one executing the code defined in the class SecondThreadR----------------------------------*/
public class ThreadCreator
{
public static void main( String[ ] args )
{
System.out.println( "I am about to create threads");
/*--------- create three threads ------------------------ */
FirstThreadR task1 = new FirstThreadR( );
Thread thread1 = new Thread( task1, "first" );
FirstThreadR task2 = new FirstThreadR( );
Thread thread2 = new Thread( task2, "second" );
SecondThreadR task3 = new SecondThreadR( );
Thread thread3 = new Thread( task3, "third" );
System.out.println( " Threads are created and will start soon");
/*------------- start all three threads-----------------*/
thread1.start( );
thread2.start( );
thread3.start( );
System.out.println(" main is done");
}
}
© 2011 Gilbert Ndjatou
Page 188
Hands-on T1
Type and execute the programs in examples T1 and T2.
Hands-On T2
Type and execute the program in example T1 by using the following definition of the method main:
/*------------ create two threads: the first one executing the code defined in the class FirstThreadT, and
the second one executing the code defined in the class SecondThreadT-----------------------------*/
public class HandsOnT2
{
public static void main( String[ ] args )
{
System.out.println( "I am about to create threads");
/*--------- create both threads ------------------------ */
FirstThreadT thread1 = new FirstThreadT( );
SecondThreadT thread2 = new SecondThreadT( );
System.out.println( " Threads are created and will start soon");
/*------------- start both threads-----------------*/
thread1.start( );
thread2.start( );
//Looping from 1 to 5 to display numbers from 1 to 5
for ( int i=1; i<=5; i++)
{
//Displaying the numbers from the current thread
System.out.println( "Messag from Thread : " + Thread.currentThread( ).getName( ) + "\t:" +i );
© 2011 Gilbert Ndjatou
Page 189
// taking a delay of one second before displaying next number
try
{
Thread.sleep (4000);
}
catch (InterruptedException interruptedException)
{
/*Interrupted exception will be thrown when a sleeping or waiting thread is interrupted. */
System.out.println("First Thread is interrupted when it is sleeping" + interruptedException);
}
}
}
Exercise T1
A.
1. The code to be executed by a thread has an array defined as follows:
char [ ] list = {‘A’, ‘B’, ‘C’, ‘D’, ‘E’};
A thread that executes this code outputs in a loop the string “I am thread #” followed by its assigned
number, which is followed by an element of this array by taking a delay of 2 seconds before displaying the
next element.
Write this code by defining the subclass ExerciseT1A1 of the class Thread as follows:
 This class has the instance variable: int threadNum; to hold the thread number.
 The constructor ExerciseT1A1( int number ) is used to instantiate a thread and also set its number.
2. The code to be executed by a thread outputs in a loop the string “I am thread #” followed by its assigned
number, which is followed by 10, then 20, then 30, then 40, and 50 with a delay of 3 second before
displaying the next value.
Write this code by defining the subclass ExerciseT1A2 of the class Thread as follows:
 This class has the instance variable: int threadNum; to hold the thread number.
 The constructor ExerciseT1A2( int number ) is used to instantiate a thread and also set its number.
3. Write a program that runs a thread that executes the code in the class ExerciseT1A1, and another thread
that executes the code in the class ExerciseT1A2 (use the class ExerciseT1A).
B.
1. Write the code in question A.1 by using the class ExerciseT1B1 that implements the interface Runnable.
2. Write the code in question A.2 by using the class ExerciseT1B2 that implements the interface Runnable.
3. Write a program that runs a thread that executes the code in the class ExerciseT1B1, and another thread
that executes the code in the class ExerciseT1B2 (use the class ExerciseT1B).
© 2011 Gilbert Ndjatou
Page 190
Controlling Threads
 Java also provides methods for control threads in one of the following ways:

Interrupting a sleeping thread

Waiting until a thread to terminate

Threads synchronization
Interrupting a Sleeping Thread
 The sleep(int elapsetime) instance method of the Thread class puts a thread to sleep for the specified
amount of time during which it is in general unable to rouse itself.
 However, you can invoke the void interrupt( ) instance method (of the Thread class) on a sleeping
thread to awaken it before the end of the specified amount of time in the sleep method call.
 We demonstrate the use of the void interrupt( ) instance method in the following example.
Example T3
 The application in this example conssits of a class file as follows:
The main thread creates another thread that sleeps for eight hours unless the user of the program
presses the enter key to cause the main thread to awaken it.
public class SleepyHead extends Thread
{
// Run method is executed when thread first started
public void run()
{
System.out.println ("I feel sleepy. Wake me in eight hours");
try
{
// Sleep for eight hours
Thread.sleep( 1000 * 60 * 60 * 8 );
System.out.println ("That was a nice nap");
}
catch (InterruptedException ie)
{
System.err.println ("Just five more minutes....");
}
}
© 2011 Gilbert Ndjatou
Page 191
// Main method to create and start threads
public static void main(String args[]) throws java.io.IOException
{
// Create a 'sleepy' thread
Thread sleepy = new SleepyHead();
// Start thread sleeping
sleepy.start();
// Prompt user and wait for input
System.out.println ("Press enter to interrupt the thread");
System.in.read();
// Interrupt the thread
sleepy.interrupt();
}
}
Waiting Until a Thread Terminates
 Sometimes, it is necessary to wait until a thread terminates its task before another action can be
performed.
 One such situation is when the results of the task are needed before the next step in the program.
 The Thread class has the instance method void join( ) which waits for a thread to terminate before the
next statement can be executed.
 There is an overloaded version of this method, void join(long millis) which waits for a thread to
terminate for at at most the specified amount of time.
 The following example illustrates the use of the void join( ) method.
Example T4
 The application in this example conssits of a class file as follows:
The main thread creates another thread (which goes to sleep for 5 seconds) and then waits for it to
terminate before it can continue.
© 2011 Gilbert Ndjatou
Page 192
public class WaitForDeath extends Thread
{
// Run method is executed when thread first started
public void run()
{
System.out.println ("This thread feels a little ill....");
// Sleep for five seconds
try
{
Thread.sleep(5000);
}
catch (InterruptedException ie)
{}
}
// Main method to create and start threads
public static void main(String args[]) throws
java.lang.InterruptedException
{
// Create and start dying thread
Thread dying = new WaitForDeath();
dying.start();
// Prompt user and wait for input
System.out.println ("Waiting for thread death");
// Wait till death
dying.join();
System.out.println ("Thread has died");
}
}
Threads Synchronization
 An important issue in an application with two or more threads is the race condition:
A situation where two or more threads are reading or writing a shared location and the final
result depends on the order in which they are run.
© 2011 Gilbert Ndjatou
Page 193
Example of race condition
A print spooler consists of the following:
1. a spooler directory (an array with many slots) to contain the names of the files to be printed.
2. a thread called printer daemon which periodically checks to see if there are any files to be
printed, and if there are, it prints them and removes their names from the directory.
3. Two shared variables: variable in points to the next free slot and out points to the next file to be
printed.
When a thread wants to queue a file for printing, it does the following:
1. Read the value of variable in into a local variable
2. Store the name of the file in the corresponding slot in the directory
3. Add 1 to the local variable
4. Copy the local variable into the variable in.
Problem
-
Two threads A and B want to print
-
Thread A reads the value of variable in (let’s say 7) into a local variable.
-
Before it can store the name of its file in the directory and update the value of variable in, it is
suspended by the OS and the CPU is given to thread B.
-
Thread B reads the value of variable in (7) into its own local variable, stores the name of its file
in the empty slot (7), and update the value of variable in (to 8).
-
When the CPU is given back to thread A, it continues where it left off, by storing the name of its
file in slot 7 (erasing the name of the file that thread B stored there), and updating the value of
variable in to 8.
Thread B will not have any output.
Critical Regions
 A process is said to be in its critical region or critical section when it is accessing a shared location.
 For the above example, a process is in its critical section if it is performing any of the steps 1 to 4.
Mutual Exclusion
 A solution to the race condition problem is Mutual exclusion: Not to allow two or more threads to
be in their critical sections at the same time.
 For the above example, it means that if a thread is performing one of the steps 1 to 4, no other thread
should be allowed to start step 1.
© 2011 Gilbert Ndjatou
Page 194
 In Java, this is accomplished in one of the following ways:
1. Use the synchronized keyword to mark the definition of every method that is invoked in a thread’s
critical section as follows:
synchronized <return-type> <function-name>( <parameter-list> )
{
<Body-of-the-function>
}
2. Use a block-level synchronization to incapsulate the statements in a thread’s critical section as
follows:
synchronized ( Object obj )
{
<statements>
}
Where obj is the object whose access is being protected.
Using Method-Level Synchronization
Example T5
 The application in this example consists of two Java class files:
 The fisrt file contains the class Counter with
 the instance variable countValue whose access should be synchronized.
 It also has the instance method increaseCount( ) that reads the values of the instance
variable countValue, sleeps for 5 milliseconds, and then increments it by one.
 The second files contains the class CountingThread that implements the Runnable interface with
the code that is used by three threads to concurrently access the instance variable countValue of
an object.
 This file also contain the code of the main thread that creates and starts, and wait for all three
threads to terminate.
© 2011 Gilbert Ndjatou
Page 195
public class Counter
{
private int countValue;
public Counter()
{
countValue = 0;
}
public Counter(int start)
{
countValue = start;
}
// Synchronized method to increase counter
public synchronized void increaseCount()
{
int count = countValue;
//
//
//
//
Simulate slow data processing and modification
Removing the synchronized keyword will demonstrate
how inaccurate concurrent access can be. Adjusting
this value may be necessary on faster machines.
try
{
Thread.sleep(5);
}
catch (InterruptedException ie)
{}
count = count + 1;
countValue = count;
}
// Synchronized method to return counter value
public synchronized int getCount()
{
return countValue;
}
}
© 2011 Gilbert Ndjatou
Page 196
public class CountingThread implements Runnable
{
Counter myCounter;
int
countAmount;
// Construct a counting thread to use the specified counter
public CountingThread (Counter counter, int amount)
{
myCounter = counter;
countAmount = amount;
}
public void run()
{
// Increase the counter the specified number of times
for (int i = 1; i <= countAmount; i++)
{
// Increase the counter
myCounter.increaseCount();
}
}
public static void main(String args[]) throws Exception
{
// Create a new, thread-safe counter
Counter c = new Counter();
// Our runnable instance will increase the counter
// ten times, for each thread that runs it
Runnable runner = new CountingThread( c, 10 );
System.out.println ("Starting counting threads");
Thread t1 = new Thread(runner);
Thread t2 = new Thread(runner);
Thread t3 = new Thread(runner);
t1.start();
t2.start();
t3.start();
// Wait for all three threads to finish
t1.join();
t2.join();
t3.join();
System.out.println ("Counter value is " + c.getCount() );
}
}
© 2011 Gilbert Ndjatou
Page 197
Using Block-Level Synchronization
Example T6
 The application in this example consists of one Java class file with the following:
 The class SynchBlock that implements the Runnable interface with the code that is used by three
threads to concurrently access the instance variable StringBuffer buffer (whose access should be
synchronized) of an object.
 This file also contain the code of the main thread that creates, starts, and waits for all three threads to
terminate.
public class SynchBlock implements Runnable
{
StringBuffer buffer;
int counter;
public SynchBlock()
{
buffer = new StringBuffer();
counter= 1;
}
public void run()
{
synchronized (buffer)
{
System.out.print ("Starting synchronized block ");
int tempVariable = counter++;
// Create message to add to buffer, including linefeed
String message = "Count value is : " + tempVariable +
System.getProperty("line.separator");
try
{
Thread.sleep(100);
}
catch (InterruptedException ie)
{}
buffer.append (message);
System.out.println ("... ending synchronized block");
}
}
© 2011 Gilbert Ndjatou
Page 198
public static void main(String args[]) throws Exception
{
// Create a new runnable instance
SynchBlock block = new SynchBlock();
Thread t1 =
Thread t2 =
Thread t3 =
Thread t4 =
t1.start();
t2.start();
t3.start();
t4.start();
new
new
new
new
Thread
Thread
Thread
Thread
(block);
(block);
(block);
(block);
// Wait for all three threads to finish
t1.join();
t2.join();
t3.join();
t4.join();
System.out.println (block.buffer);
}
}
Communication with Pipes
 You create a communication from one thread (the sender) to another thread (the receiver) using a pipe as
follows:
1. Create an instance of the PipeedOutputStream class that is used by the sending process to write the
message.
2. Create an instance of the PipedInputStream class that is used by the receiving thread to read the
message and connect it to the instance of the PipeedOutputStream class created in step 1.
Example T7
import java.io.*;
public class PipeDemo extends Thread
{
PipedOutputStream output;
// Create an instance of the PipeDemo class
public PipeDemo(PipedOutputStream out)
{
// Copy to local member variable
output = out;
}
© 2011 Gilbert Ndjatou
Page 199
public void run()
{
try
{
// Create a printstream for convenient writing
PrintStream p = new PrintStream( output );
// Print message
p.println ("Hello from another thread, via pipes!");
// Close the stream
p.close();
}
catch (Exception e)
{
// no code req'd
}
}
public static void main (String args[])
{
try
{
// Create a pipe for writing to by the writer thread
PipedOutputStream pout = new PipedOutputStream();
// Create a pipe for reading, and connect it to output pipe
PipedInputStream pin = new PipedInputStream(pout);
// Create a new pipe demo thread, to write to our pipe
PipeDemo pipedemo = new PipeDemo(pout);
// Start the thread
pipedemo.start();
// Read thread data,
int input = pin.read();
// Terminate when end of stream reached
while (input != -1)
{
// Print message
System.out.print ( (char) input);
// Read next byte
input = pin.read();
}
}
catch (Exception e)
{
System.err.println ("Pipe error " + e);
}
}
}
© 2011 Gilbert Ndjatou
Page 200
Hands-On Exercise IA2 T3?
1.
2.
3.
4.
Type and execute the programs in examples T3 and T4.
Type and execute the programs in examples T5 first with method-level synchronization and second without it.
Type and execute the programs in examples T6 first with block-level synchronization and second without it.
Type and execute the programs in example T7.
© 2011 Gilbert Ndjatou
Page 201