Akinola Java Book
Akinola Java Book
Programming principles
OOP Concepts
Java Fundamentals
Applets
Java Arrays and Vectors
Methods
Object-based Programming
Packages
Inheritance
File Handling
Database Handling
Over 70 implemented
Programs
2
Java for Beginners
Copyright ©
Published by
First Edition:
ISBN
3
Preface
All the programs cited in this book were all implemented by the
author and the codes are available on demand.
4
Java for Beginners
Acknowledgements
5
Dedication
And
To all my students who had passed through me and those who will
still pass through me in Java programming.
And
To all those who will use this book for teaching or leaning
6
Java for Beginners
Contents
Preface …………………………………………………….
Acknowledgement…………………………………………
Dedication …………………………………………………
2: Java Fundamentals
2.0 Introduction ………………………………………..
2.1 Creating and Running a Java Program……………..
2.2 Writing your first program…………………………
2.3 Inserting Comments into Your Program ………….
2.4 Inputting Data into Java Programs ………………..
2.5 Using the Scanner Facility ……………………….
2.6 Using the Swing Facility …………………………
2.7 Java Variables and Objects ………………………
2.8 Scope of Variables ……………………………….
2.9 Variable Initialization …………………………….
2.10 Final Variables / Java Constants …………………
2.11 Data Types ……………………………………….
2.12 Operators …………………………………………
2.13 The Math Class …………………………………..
2.14 Shift and Logical operators ………………………
2.15 Other Operators …………………………………..
7
2.16 Expressions ………………………………………….
2.17 Operators’ Order of Precedence ……………………..
2.18 Statements ……………………………………………
2.19 Blocks ………………………………………………..
2.20 Formatting Your Outputs ……………………………..
8
Java for Beginners
5.5 Void Methods ………………………………………..
5.6 Recursive Methods ………………………………….
9: Java Packages
9.0 Introduction ………………………………………….
9.1 Benefits of Packages …………………………………
9.2 Creating packages……………………………………..
9.3 Why the com. Naming Convention?.............................
9.4 Compiling a file containing a package…………………
9.5 To use packages ………………………………………..
9
10: ntroduction to the Concept of Inheritance
10.0 Introduction
10.1 What is Inheritance? …………………………………
References …………………………………………….
Index……………………………………………………
10
Java for Beginners
1
Fundamental Principles
of Programming
1.0 Introduction
11
together to perform some tasks. For instance, an operating system is
a system program having several functional modules (programs)
working to achieve the goal of coordinating the entire hardware
resources.
12
Java for Beginners
measurement tools and other aids comprise a complete programming
environment.
Flowcharts
Flowcharts are basic symbolic representations of solution pathway to a
problem. In other words, it is diagrammatic representation of solution to
problems. The following basic symbols are common used:
I < = 10 Yes
No
13
6. Small Circle for connecting two parts of the flowchart
together
A
Algorithms
An algorithm literarily means the step-by-step procedure of solving
a problem. Technically, it is defined as a finite solution steps to
problem. As a matter of fact, an algorithm must have the following
properties:
(i) Finiteness: It must have a terminating point after some
points.
(ii) Definiteness: It must be clear and unambiguous.
(iii) Input: It must have allowable set of data input to the
system.
(iv) Output: It must properly define the nature of result
expected; that is, the format.
(v) Efficiency: Its implementation must be space (memory)
and time efficient.
The algorithm:
14
Java for Beginners
Else
Print out Results, Sum, Count
Terminate
The Flowchart:
Start
Count = 0
Sum = 0
Read
D t
Yes
d >= 0? Yes= sum + d
Sum
Count = count + 1
No
A A
Print out
Results,
sum, count
Stop
15
1.4 Steps of Programming
16
Java for Beginners
17
1.6 Good Programming Style
18
Java for Beginners
7. The program must be well structured for readability.
Well-structured programs are aesthetically readable and
maintainable. The use of indentations and white spaces to
separate the parts of a program promotes structuring of
programs.
8. Modularize the program for easy maintenance. The
program should be broken down into various functional
units. This is achieved through the use of subroutines and
functions in programs.
9. Appropriate documentation formats such as comments
and white spaces (blank lines) must be used in the program.
The white spaces separate the program into logical
functional sections for ease of debugging and maintenance.
10. Test the program with different sets of data (both valid and
invalid) to ascertain that the program is error-free.
19
instance, if we supposed to use <= in our statement but
we now use >=, then logic error will occur. What
usually happen in this case is that the program will
compile and execute successfully but a wrong output
will be obtained. This is due to the fact that the
programmer has used a wrong logic somewhere in the
program. Infinite looping is a serious case of logic errors
in programs. To resolve this error, the programmer has
to go back to the program and check all important
sections of the code for logic correctness.
4. Compile-time Errors: These are the errors brought out
during the compilation stage of the program
development. They are actually syntax and semantic
errors.
5. Run-time Errors: These are errors brought out during
the execution stage of the program development. For
instance, when we try to divide by zero, memory
overflows and so, error results.
20
Java for Beginners
compiles an equivalent machine code object program. (If the
source program contains syntax errors, the compiler outputs a
number of messages indicating the nature of the errors and where
they occur).
Object
Source Compile Program Executable Run
Program Link Program
(Machine
Code)
Library
Subprograms
21
programming languages found around such as COBOL,
C++, C, Java, FORTRAN, etc.
22
Java for Beginners
is no stringent rule for declaring variables in these
languages. Take for example, FORTRAN. In this language,
any variable name starting with I, J, K, L, M or N is
regarded as being Integer-numeric. So, if we don’t declare
those variables before they are used, they are implicitly
regarded as integers. Other ones beginning with other letters
are implicitly regarded as Real or floating point numbers.
Visual Basic too is somehow weak. It also has implicit
naming convention. For example, a variable declared such
as Num% is regarded as Integer-numeric. Weakly typed
languages are not necessarily case sensitive.
23
isolated and found very more easily than in a single complete
(monolithic) program. It is usually only necessary to correct code in
the section in which the problem occurred so that re-programming
can also be minimized. Conclusively, a structured program must be
made up of a series of sections (modules). Each of which must be
able to do the following:
24
Java for Beginners
Process Action
25
There are two approaches normally used to design a structured
program:
1. Top-down Approach
26
Java for Beginners
programmers. With tasks and relationships thus defined
and documentation available to identify data and fields,
several programmers may work independently, with the
probability that the parts will work as a whole when they
are all combined.
2. Bottom-up Approach
This begins with the lowest levels of the design to the highest, i.e.,
we work from the detailed to the general. Common routines /
functions that may be used by higher modules are identified. For
instance, a system having many modules that needs to sort a list.
Then, sort function is shared commonly by all these modules.
Essentially, the following steps are taken in Bottom-up approach:
We identify each of the lower level functions / modules as
independent tasks to be completed.
We then begin integrating each function /module into a
program by creating a separate routine.
Finally, we build all these routines from the bottom up into a
complete system.
27
3. Sufficient Information: Does it include clear and sufficient
information for its users in form of instructions and
documentations?
4. Logically Written: Is the program logically and clearly
written, with short modules and subprograms as
appropriate?
5. Time and Space Efficient: Does it make efficient use of
time and space?
28
Java for Beginners
functions are action-oriented and do not really correspond to the
elements of the problem.
Functions Functions
29
Some of the striking features of object-oriented programming are:
Emphasis is on data rather than procedure.
Programs are divided into what are known as objects.
Data structures are designed such that they characterize
the objects.
Functions that operate on the data of an object are tied
together in the data structure.
Data is hidden and cannot be accessed by external
functions.
Objects may communicate with each other through
functions.
New data and functions can be easily added whenever
necessary.
Follows bottom-up approach in program design.
30
Java for Beginners
1.13.1 Objects
Program objects should be chosen such that they match closely with
the real-world objects. Objects take up space in the memory and
have an associated address like a record in Pascal, or a structure in
C.
Objects are just like the real world objects we see around. They
share two characteristics- State and Behaviour. For example, dogs
have state (name, colour, breed, hungry) and behaviour (barking,
fetching and wagging tail). Bicycles have state (current gear, current
pedal cadence, two wheels, number of gears) and behaviour
(braking, accelerating, slowing down, changing gears).
31
Everything that the software object knows (state) and can do
(behaviour) is expressed by the variables and the methods within
that object.
1.13.2 Classes
Fruit mango;
32
Java for Beginners
Objects vs. Classes: you probably noticed that all the illustrations of
objects and classes look very similar. And indeed, the difference
between them is often the source of some confusion. In the real
world, it’s obvious that classes are not themselves the objects they
describe. A blueprint of a bicycle is not a bicycle. However, it’s a
little more difficult to differentiate classes and objects in software.
This is partially because software objects are merely electronic
models of real-world objects or abstract concepts in the first place.
But it’s also because the term “object” is sometimes used to refer to
both classes and instances.
33
be changed at any time without affecting the other objects that
depend on it. For instance, you don’t need to understand the
gear mechanism on your bike to use it.
Since the classes use the concept of data abstraction, they are known
as Abstract Data Types (ADT).
1.13.4 Inheritance
34
Java for Beginners
Note that each sub-class defines only these features that are unique
to it. Without the use of classification, each class would have to
explicitly include all of its features.
1.13.5 Polymorphism
35
1.13.7 Message Passing
36
Java for Beginners
Message passing techniques for communication between objects
makes the interface descriptions with external systems much
simpler.
Software complexity can be easily managed.
2. Develop in stages
37
represents. Always use IMPLICIT NONE statement to force
explicit typing of variables and arrays.
4. Modularise
6. Clarity
7. Testing
Once you have eliminated the syntax errors from your program and
subroutines, try running them using suitable test data. Calculate what
the results should be, and check that the actual results correspond. If
they do not, you will have to revise some of the steps above to
correct the errors in your logic. To determine the cause of an error,
you may have to insert extra PRINTING statements to print out the
values of variables etc. at various stages.
Many debugging options or tools can help you finding errors. For
the arrays, the "bound checking" options are very useful to detect
errors at execution. Your test data should be designed to test the
various logical paths through your program. For example, to test the
38
Java for Beginners
quadratic roots program you should use data designed to obtain two,
one and no real roots, as well as a value of zero for a.
Tutorial Questions
39
5. Consider the following code snippets in C-like language,
identify the type of errors (logical, semantic or syntax) in each
of the snippets and explain how to correct them:
a. I = 1;
while (I <= 10);
I++ ;
c. int sum(int n) {
if (n = 0)
return 0;
else
n + sum(n – 1);
}
40
Java for Beginners
2
Java Fundamentals
2.0 Introduction
41
data in the application. Java does not concentrate on
procedures only.
3. Platform independent: Java has the ability to move
from one computer to the other or from one operating
system to another without any difficulty.
4. Robust: Java is strictly a strongly-typed language. It
requires explicit declaration. Java has exception
handling features, the programmer does not need to
worry about memory allocation, and it does not have
pointer and pointer arithmetic.
5. Security: Java is totally secured. It provides a controlled
environment for the execution of the program. It never
assumes that the code is safe for execution. It provides
several layers of security control.
6. Distributed: Java can be used to develop applications
that are portable across multiple platforms, operating
systems and graphical user interfaces (GUI). Java is
designed to support network applications.
7. Multi-threaded: Java programs use a process called
multithreading to perform many tasks simultaneously.
42
Java for Beginners
Virtual Machine, translates and executes java bytecode)
system uses to run your program [4 times the size of your
source code file].
Finally execute the program by typing java <filename>.
Don’t type the extension name.
Note: Bytecode is the low-level computer language translation
of a java source code.
Alternatively,
Open a DOS command window
Type Cd.. to go to the root directory
Type Cd J2sdk1.4.1_02\bin to go the bin directory of the
java toolkit. The J2sdk must be the version you install on the
computer.
Type Edit <myprogram.java> to edit your program.
Myprogram must be the class name of the program you want
to develop.
After keying in your codes, save and exit
Now continue the compilation (javac <myprogram.java>)
and the execution (java <myprogram>).
43
Follow the steps below to run programs with JCreator.
1. Open the JCreator via the start menu.
2. Click New icon on the toolbar.
3. Type the name of your file. Remember the filename will be
the name to be given to the class and the extension would be
.java
4. Click the Location button and navigate to C:>, then the Java
toolkit and finally the Bin subfolder of the toolkit.
5. Key in your code in the code editor window.
6. Save the file by pressing Ctrl + S
7. To compile, click Build then Compile File.
8. To execute the program, click Execute File
44
Java for Beginners
2.2 Writing your first program
This line could be regarded as the heading for the program. Java sees
a program as a class and the name of the class must be the same as
the name of the file, i.e., the name you use to save the file. In this
case we save the file as Welcome.java. Any nonempty string of
letters and digits can be used for the class name as long as it begins
with a letter and contains no blanks.
(b) The second line begins with the left brace character; just like
BEGIN in Pascal. There must be a corresponding right brace
at the last line of the program, i.e. representing END as in
Pascal. The two braces form the program block, which
encloses the program’s body.
45
with it – public, static, and void discussed below. A method or
function could have zero or more list of arguments, enclosed in open
and close brackets after the function’s name. The default argument
for method main is args, which is an array of strings.
public means that the contents of the following block (the
function/method) are accessible from all other classes.
static means that the method being defined applies to the
class itself rather than to objects of the class
void means that the method being defined has no return
value.
main means this is the name of the method being defined,
just as Welcome is the name of the class being defined. The
parenthesized string following main forms the parameter list
for the main method, which are local variables used to
transmit information to the method from the outside world;
(String[ ] args). It states that this method has one
parameter, its name is args and it is an array of string
objects.
(d) The two closing braces, } mark the end of the program. The
first closes the main method and the other closes the class.
Both print( ) and println( ) are standard output functions that print
data to the monitor screen. The statement:
46
Java for Beginners
will print the values of the data items a, b and c on a single line and
the cursor will remain at the end of the printing.
a = 2;
b = 4;
c = 6;
d= 8;
For Line 1, 2 and 4 will be printed on a single line and the blinking
cursor will remain at the end of that line, waiting for another printing
action. In Line 2, 6 will be printed after 4 on the same line with the
previous printing. In Line 3, the cursor moves to next line without
printing any value, since no data was given. In Line 4, 8 would be
printed in the second line where the cursor was before in Line 3 and
after the printing, it moves to next line. Println( ) is a post-active
function. The final output will look like below:
2 4 6
8
47
2.3 Inserting Comments into Your Program
*/
X = X – 4 // subtracting 4 from X
But, the comment style is only meant for one line. If there is need to
extend comments to another line, we have to put another comment
symbol (//) against that line.
48
Java for Beginners
Note: Adding comments to your programs is called documenting
your code and comments are normally ignored during compilation.
Comments promote readability, understand-ability and
maintainability of programs.
The truth is that every data input into java environment is always
regarded as being string. This is due to the fact that the parameter
passed into the main method, (args) is an array of string. For
numeric data input, the data has to be converted or parsed into the
equivalent numeric type. See implemented example E1.
E1:
import java.util.Scanner;
public class Hello {
public static void main(String[ ] args) throws
IOException {
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(reader);
System.out.print(“Enter your name: “);
String name = input.readLine();
System.out.println(“Hello,” + name + “!”);
}
}
Sample Output:
C:\j2sdk1.4.2_04\bin>java Hello
Enter your name: Akinola
Hello,Akinola!
49
The first line tells the javac compiler to look in the Java.io
library for the definitions of the three I/O classes used in the
program, IOException, InputStreamReader and the
BufferedReader.
The fourth line defines the object reader to be an instance of the
InputStreamReader class, binding it to the system Input Stream
System.in. This means that the object reader will serve as a
conduit, conveying data from the keyboard into the program.
The fifth line defines the object input to be an instance of the
BufferedReader class, binding it to the reader object.
The seventh line declares the name object as string and
initializes it with the string that is to be returned by the
input.readLine method. The result is that the name object
contains whatever you typed at the keyboard, which is then
printed out in line 8th. The expression “Hello,” + name + “!”
means to concatenate (i.e. string together) the three strings –
Hello, name and ! to form a single string to be sent to the screen.
If you are using an IDE (Integrated Development Environment)
such as CodeWarrior, NetBeans, JCreator or Jbuilder to key in
your source program, the editor will help you locate syntax
errors unlike the Microsoft Notepad Editor.
Note: the throws IOException allows the program to use the
readLine method.
50
Java for Beginners
int n = 44; //n is a 32-bit integer initialized to be 44
Note: Java assumes that all data input into the program would be
string data type because its main method takes a String argument,
args. So, all numeric data input must be converted or ‘parsed’ into
the appropriate data type. Example program below illustrates this.
E2:
Sample Output:
C:\j2sdk1.4.2_04\bin>javac Birth.java
C:\j2sdk1.4.2_04\bin>java Birth
Enter your age: 37
Enter this year’s value e.g. 2007: 2005
You are 37 years old now
So you were probably born in 1968
Note:
In the line
51
int age = new Integer(text).intValue( ); // parsing ‘text’ to int
The keyword ‘new’ is used to create or better still instantiate a new
integer object (called text in this case) from the class int while the
method intValue( ) does the parsing of the text to numeric integer
value. Alternatively, the line could have been written thus:
E3:
// Computing the Area of a circle
import java.io.*;
public class Area {
public static void main(String[ ] args) throws
IOException {
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(reader);
System.out.print(“Enter the radius: “);
String text = input.readLine();
//converting ‘text’ to double
double r = Double.parseDouble(text);
double area = Math.PI*r*r;
System.out.println(“The Area of a circle of radius ” +
r + “is “ + area);
}
}
Sample Output:
C:\j2sdk1.4.2_04\bin>java Area
Enter the radius: 28.5
The Area of a circle of radius 28.5 is 2551.7586328783095
52
Java for Beginners
2.5 Using the Scanner Facility
E4:
//program to compute average of any three numbers
import java.util.Scanner;
class add {
public static void main(String[ ] args) {
Scanner input = new Scanner(System.in);
// Reading in the input data a, b and c
System.out.println("Enter the value of a");
float a = input.nextFloat(); //nextInt for int data
System.out.println("Enter the value of b");
float b = input.nextFloat();
System.out.println("Enter the value of c");
double c = input.nextDouble(); // for double data
System.out.println("What is your name");
String n = input.next(); // Reading a string data
double sum = a + b + c;
double avg = sum/3.0;
System.out.print("Hello! " + n + " \n The Average
of your data is: " + avg + "\nBye....");
System.exit(0);
}
}
53
Output Screen Shot
E5:
import javax.swing.*;
// program to add two numbers together
public class Addition {
public static void main(String args[ ]) {
// Declaring your variables …
String firstNumber, secondNumber;
int number1, number2, sum;
firstNumber = JOptionPane.showInputDialog("Enter
54
Java for Beginners
first Number");
secondNumber = JOptionPane.showInputDialog("Enter
second Number" );
number1= Integer.parseInt(firstNumber);
number2= Integer.parseInt(secondNumber);
sum = number1 + number2;
JOptionPane.showMessageDialog(null,"The sum is"+
sum, "Result", JOptionPane.PLAIN_MESSAGE);
System.exit(0);
} //end main method
} //end class Addition
Output:
Explanations:
(i) The JOptionPane is a subclass of the swing class and has some
methods or functions associated with it. One of which is the
showInputDialog used above. The purpose of this method is to
draw an input textbox, in which the user will type in his / her
data. What is typed in double quote as an argument in the
method will serve as a prompt for the user to know what he is
55
to do with the textbox when it comes onto the screen.
However, any data captured by the showInputDialog( )
method is a string, even if you had entered a number!
are the lines of code that converts (parse) the numeric data
captured by the showInputDialog( ) into numeric data, either
float, double or int or long. However, both the line for
showInputDialog( ) and the parsing can be combined into only
one line to minimize space and time. Thus the two lines:
firstNumber = JOptionPane.showInputDialog("Enter first
Number");
number1= Integer.parseInt(firstNumber);
56
Java for Beginners
prompting messages are doubly quoted along with the variable
values to be printed out. The title given to the message box as
the third parameter must be typed in double quotes and should
be relevant to the output to be brought out. The last parameter
is the icon to be attached to the message box. This time, we
used the JoptionPane.PLAIN_MESSAGE, meaning that no
icon will show. We can also use
JOptionPane.INFORMATION_MESSAGE or
JOptionPane.ERROR_MESSAGE. Note the use of the
underscore.
These hold data in Java. A variable has a type and hold a single
value. An object is an instance of a class and may contain many
variables, the composite of whose values is called the “state” of the
object. Whereas every variable has a unique name, on being
declared, objects have references instead of names, and they need
not be unique. An object is created by using the “new” operator to
invoke a “Constructor” and it dies when it has no references. E.g. in
the Circle program above, r and area are the 2 variables while reader,
input, text, x and System.out are the five objects in the program.
These objects are instances of the classes inputStreamReader,
BufferedReader, String, Double and PrintStream respectively. In the
Java programming language, the following must hold true for a
simple name:
57
code. (We will cover this in the next section,
Scope.)
4. It must not be a java reserved identifier such as
swing, String, int, short etc. Reserved words are pre-
defined in java, and so, cannot be re-defined.
member variable
local variable
method parameter
exception-handler parameter
58
Java for Beginners
59
block between { and } that follow a catch statement. We shall deal
with this topic later.
if (...) {
int i = 17;
...
}
System.out.println("The value of i = " + i); // error
The final line won't compile because the local variable i is out of
scope. The scope of i is the block of code between the { and }. The i
variable does not exist anymore after the closing }. Either the
variable declaration needs to be moved outside of the if statement
block, or the println method call needs to be moved into the if
statement block.
60
Java for Beginners
The previous statement declares a final variable and initializes it, all
at once. Subsequent attempts to assign a value to aFinalVar result in
a compiler error. You may, if necessary, defer initialization of a
final local variable. Simply declare the local variable and initialize it
later, like this:
final int blankfinal;
...
blankfinal = 0;
A final local variable that has been declared but not yet initialized is
called a blank final. Again, once a final local variable has been
initialized, it cannot be set, and any later attempt to assign a value to
blankfinal is an error.
8-bit two's
Byte Byte-length integer
complement
61
16-bit two's
Short Short integer
complement
32-bit two's
Int Integer
complement
64-bit two's
Long Long integer
complement
Single-precision
Float 32-bit IEEE 754
floating point
Double-precision
Double 64-bit IEEE 754
floating point
(other types)
16-bit Unicode
Char A single character
character
A boolean value
Boolean true or false
(true or false)
NB: In other languages, the format and size of primitive data types
may depend on the platform on which a program is running. In
contrast, the java programming language specifies the size and
format of its primitive data types. Hence, we don’t have to worry
about system-dependencies.
int anInt = 4;
62
Java for Beginners
int are integers in the range of 1 to a few thousands. However, if a
variable is going to run into millions, we’d better declare it as long.
For instance, when we are writing a factorial program, the factorial
of big numbers like 20 may run into large values. short and byte are
usually used in systems programming dealing with registers and
memory addresses.
float is designed for real data whose number of decimal places may
run not more than 5 places, e.g. 245.234. But double is used if we
have a recurring decimal running up to say 10 decimals places like
pi ( ). For instance, Java insists that whenever we are carrying out
division, the variable to assign the result to must be declared as
double, so as to avoid loss of precision.
Arrays, classes and interfaces are reference data types. The value
of a reference type variable, in contrast to that of primitive type, is a
reference to (an address of) the value or set of values represented by
the variable. A reference is called a pointer, or a memory address in
other languages. The java programming does not support the explicit
use of addresses like other languages do. We use the variable’s name
instead.
objectName
reference
An object
or an
array
63
2.12 Operators
Op++
Increments op by 1; evaluates to the
++ e.g
value of op before it was incremented
i++;
++op
Increments op by 1; evaluates to the
++ e.g
value of op after it was incremented
++i;
64
Java for Beginners
int y, x;
float b;
double a, c;
a = c + b + y + x;
The next table summarizes how java handles these situations. The
data type returned by the arithmetic operators is based on the data
type of the operands. The necessary conversions take place before
the operation is performed.
Data
Type of Data Type of Operands
Result
65
Neither operand is a float or a double (integer
int
arithmetic); neither operand is a long.
66
Java for Beginners
Oper- Example
Use Equivalent to
ator
&= Op1 &= op2 op1 = op1 & op2 We shall study
Note that +=, ++ and others are to be written together without any
space in between them.
67
2.12.3 Relational and Conditional Operators:
> op1 > op2 op1 is greater than op2 e.g. if (a > b)
< op1 < op2 op1 is less than op2 e.g. if (a < b)
68
Java for Beginners
import javax.swing.JOptionPane;
// program for comparing values
public class comparison1 {
//main method begins execution of Java application
public static void main( String args[] ) {
String firstNumber; // first string entered by the user
String secondNumber; // second string entered by the user
String result; // a string containing the output
int number1; //first number to compare
int number2; //second number to compare
69
if ( number1 == number2)
result = result + number1 + "==" + number2;
if ( number1 != number2 )
result = result + number1 + "!=" + number2;
// Display results
JOptionPane.showInputDialog(null, result, "Comparison Result",
JOptionPane.INFORMATION_MESSAGE);
System.exit( 0 ); //terminate application
}
}
Output:
70
Java for Beginners
E7:
/***This program prints the constants e and , absolute of –1234,
cos(/4), sin(/2), tan(/4), ln(1), e and five random double numbers
between 0.0 and 1.1 **/
71
System.out.println("The first five Random numbers from 1 to 100
are .... ");
// To generate random numbers …
for (int i=0;i<5;++i)
System.out.println(Math.floor(Math.random()*100)
+ " ");
System.out.println();
}
}
Output:
C:\j2sdk1.4.2_04\bin>java MathApp
Math.E = 2.718281828459045
Math.PI = 3.141592653589793
Math.abs(-1234) = 1234
Math.cos(Math.PI/4) = 0.7071067811865476
Math.sin(Math.PI/2) = 1.0
Math.tan(Math.PI/4) = 0.9999999999999999
Math.log(1) = 0.0
Math.exp(Math.PI) = 23.140692632779267
The first five Random numbers from 1 to 100 are ....
35.0
13.0
4.0
35.0
79.0
72
Java for Beginners
System.out.println(“m - n= “ + difference);
int product = m*n;
System.out.println(“m * n = “ + product);
int quotient = m/n;
System.out.println(“m/n = “ + quotient);
int remainder = m%n;
System.out.println(“m%n = “ + remainder);
}
}
Output:
C:\j2sdk1.4.2_04\bin>java Arith
m = 25
n=7
m + n = 32
m - n= 18
m * n = 175
m/n = 3
m%n = 4
73
Each operator shifts the bits of the left-hand operand over by the
number of positions by the right-hand operand. The shift occurs in
the direction indicated by the operator itself. For example, The
following statement shifts the bits of the integer 13 to the right by
one position:
13 >> 1;
The following table shows the four operators the java programming
language provides to perform bitwise functions on their operands:
When its operands are numbers, the & operation performs the
bitwise AND function on each parallel pair of bits in each operand.
The AND function sets the resulting bit to 1 if the corresponding bit
in both operands is 1, as shown below:
74
Java for Beginners
0 0 0
0 1 0
1 0 0
1 1 1
For instance, suppose that you were to AND the values 13 and 12,
like this: 13 & 12. The result of this operation is 12 because the
binary representation of 12 is 1100 and that of 13 is 1101.
1101 // 13
& 1100 // 12
1100 // 12
0 0 0
0 1 1
1 0 1
1 1 1
Exclusive OR means that if the two operand bits are different, the
result is 1, otherwise the result is 1.
75
Op1 Op2 Result
0 0 0
0 1 1
1 0 1
1 1 0
Finally, the complement operator inverts the value of each bit of the
operand bits is 1, the result is 0 and if the operand bit is 0, the result
is 1.
floatArray[6];
76
Java for Beginners
Note that array indices begin at 0 in java.
77
Op1 instanceOf op2
Op1 must be the name of an object and op2 must be the name of a
class. Ann object is considered to be an instance of a class if that
object directly or indirectly descends from that class.
Examples
Q1: What are the values of i and n after the code is executed?
Answer: i = 11, n = 0
Q2: What are the final values of i and n if instead of using postfix
increment operator (i++), we use the prefix version (++i)?
Answer: i = 11, n = 1
Can you give reasons for these answers? Check relevant tables
up.
Answer: i = 8
78
Java for Beginners
2.16 Expressions
x + y / 100
x + (y / 100) // Unambiguous, recommended
79
2.17 Operators’ Order of Precedence
Multiplicative *, ?, %
Additive +, -
Equality ==, !=
Bitwise exclusive OR ^
Bitwise inclusive OR |
Logical OR ||
Conditional ?:
80
Java for Beginners
2.18 Statements
2.19 Blocks
A block is a group of zero or more statements between balanced
braces and can be used anywhere a single statement is allowed. The
81
following program snippet shows two blocks each containing a
single statement;
if (Character.isUpperCase(aChar)) {
System.out.println (“The character “ + aChar + “ is
upper case”);
} else {
System.out.println(“The character “ + aChar + “ is
Lower case”);
}
2.20.1 Integers
82
Java for Beginners
System.out.printf( “%d\n”, 26 );
System.out.printf(“%d\n”, +26 );
System.out.printf(“%d\n”, -26 );
System.out.printf( “%o\n”, 26 );
System.out.printf( “%x\n”, 26 );
System.out.printf( “%X\n”, 26 );
83
2.20.2 Floating-Point Numbers
Conversion
character Description
e or E Display a floating-point value in exponential
notation. When conversion character E is used, the
output is displayed in uppercase letters.
f Display a floating-point value in decimal format.
g or G Display a floating-point value in either the floating-
point format f or the exponential format e based on
the magnitude of the value. If the magnitude is less
than 10 3, or greater than or equal to 10 7, the
floating-point value is printed with e (or E).
Otherwise, the value is printed in format f. When
conversion character G is used, the output is
displayed in uppercase letters.
a or A Display a floating-point number in hexadecimal
format. When conversion character A is used, the
output is displayed in uppercase letters.
84
Java for Beginners
Values printed with the conversion characters e, E and f are output
with six digits of precision to the right of the decimal point by
default (e.g., 1.045921). Other precisions must be specified
explicitly. For values printed with the conversion character g, the
precision represents the total number of digits displayed, excluding
the exponent. The default is six digits (e.g., 12345678.9 is displayed
as 1.23457e+07). Conversion character f always prints at least one
digit to the left of the decimal point. Conversion character e and E
print lowercase e and uppercase E preceding the exponent and
always print exactly one digit to the left of the decimal point.
Rounding occurs if the value being formatted has more significant
digits than the precision.
Outputs
1.234568e+07
1.234568e+07
-1.234568e+07
1.234568E+07
12345678.900000
85
1.23457e+07
1.23457E+07
Outputs
A
This is a string
This is also a string
THIS IS ALSO A STRING
86
Java for Beginners
1234
Conversion
suffix
character Description
c Display date and time formatted as
day month date hour:minute:second time-zone year
with three characters for day and month, two digits
for date, hour, minute and second and four digits for
yearfor example, Wed Mar 03 16:30:25 GMT-05:00
2004. The 24-hour clock is used. In this example,
GMT-05:00 is the time zone.
F Display date formatted as year-month-date with four
digits for the year and two digits each for the month
and the date (e.g., 2004-05-04).
D Display date formatted as month/day/year with two
digits each for the month, day and year (e.g.,
03/03/04).
87
Conversion
suffix
character Description
r Display time formatted as hour:minute:second
AM|PM with two digits each for the hour, minute and
second (e.g., 04:30:25 PM). The 12-hour clock is
used.
R Display time formatted as hour:minute with two
digits each for the hour and minute (e.g., 16:30). The
24-hour clock is used.
T Display time formatted as hour:minute:second with
two digits for the hour, minute and second (e.g.,
16:30:25). The 24-hour clock is used.
Conversion
suffix
character Description
A Display full name of the day of the week (e.g.,
Wednesday).
a Display the three-character short name of the day of
the week (e.g., Wed).
B Display full name of the month (e.g., March).
b Display the three-character short name of the month
(e.g., Mar).
d Display the day of the month with two digits, padding
with leading zeros as necessary (e.g., 03).
m Display the month with two digits, padding with
leading zeros as necessary (e.g., 07).
88
Java for Beginners
Conversion
suffix
character Description
e Display the day of month without leading zeros (e.g.,
3).
Y Display the year with four digits (e.g., 2004).
y Display the last two digits of the year with leading
zeros as necessary (e.g., 04).
j Display the day of the year with three digits, padding
with leading zeros as necessary (e.g., 016).
Conversion
suffix
character Description
H Display hour in 24-hour clock with a leading zero as
necessary (e.g., 16).
I Display hour in 12-hour clock with a leading zero as
necessary (e.g., 04).
k Display hour in 24-hour clock without leading zeros
(e.g., 16).
l Display hour in 12-hour clock without leading zeros
(e.g., 4).
M Display minute with a leading zero as necessary (e.g.,
06).
S Display second with a leading zero as necessary (e.g.,
05).
Z Display the abbreviation for the time zone (e.g.,
89
Conversion
suffix
character Description
GMT-05:00, stands for Eastern Standard Time, which
is 5 hours behind Greenwich Mean Time).
P Display morning or afternoon marker in lower case
(e.g., pm).
p Display morning or afternoon marker in upper case
(e.g., PM).
90
Java for Beginners
19 // printing with conversion characters for date
20 System.out.printf( “%1$tA, %1$tB%1$td, %1$tY\n”, dateTime);
21 System.out.printf(“%1$TA, %1$TB%1$Td, %1$TY\n”, dateTime);
22 System.out.printf(“%1$ta, %1$tb%1$te, %1$ty\n”, dateTime);
23
24 // printing with conversion characters for time
25 System.out.printf( “%1$tH:%1$tM:%1$tS\n”, dateTime );
26 System.out.printf(“%1$tZ%1$tI:%1$tM:%1$tS%tP”, dateTime);
Outputs
Tue Jun 29 11:17:21 GMT-05:00 2011
2011-06-29
06/29/11
11:17:21 AM
11:17:21
Tuesday, June 29, 2011
TUESDAY, JUNE 29, 2011
Tue, Jun 29, 11
11:17:21
GMT-05:00 11:17:21 AM
Conversion
character Description
b or B Print "true" or "false" for the value of a boolean or
Boolean. These conversion characters can also format
the value of any reference. If the reference is non-null,
"TRue" is output; otherwise, "false" is output. When
conversion character B is used, the output is displayed
in uppercase letters.
91
Conversion
character Description
h or H Print the string representation of an object's hash code
value in hexadecimal format. If the corresponding
argument is a null reference, "null" is printed. When
conversion character H is used, the output is displayed
in uppercase letters.
% Print the percent character.
N Print the platform specific line separator (e.g., \r\n on
Windows or \n on UNIX/LINUX).
Outputs
false
true
true
FALSE
Hashcode of "hello" is 5e918d2
Hashcode of "Hello" is 42628b2
Hashcode of null is NULL
Printing a % in a format string
Printing a new line
next line starts here
92
Java for Beginners
2.20.6 Printing with Field Widths and Precisions
8. System.out.printf(“%4d\n”, 1);
9 System.out.printf(“%4d\n”, 12 );
10 System.out.printf(“%4d\n”, 123);
11 System.out.printf(“%4d\n”, 1234);
12 System.out.printf(“%4d\n”, 12345); // data too large
13
14 System.out.printf(“%4d\n”, -1);
15 System.out.printf(“%4d\n”, -12 );
16 System.out.printf(“%4d\n”, -123 );
17 System.out.printf(“%4d\n”, -1234); // data too large
18 System.out.printf(“%4d\n”, -12345); // data too large
Outputs
1
12
123
1234
12345
-1
-12
-123
-1234
93
-12345
Method printf also provides the ability to specify the precision with
which data is printed. Precision has different meanings for different
types. When used with floating-point conversion characters e and f,
the precision is the number of digits that appear after the decimal
point. When used with conversion character g, the precision is the
maximum number of significant digits to be printed. When used
with conversion character s, the precision is the maximum number
of characters to be written from the string. To use precision, place
between the percent sign and the conversion specifier a decimal
point (.) followed by an integer representing the precision. The code
below demonstrates the use of precision in format strings. Note that
when a floating-point value is printed with a precision smaller than
the original number of decimal places in the value, the value is
rounded. Also note that the format specifier %.3g indicates that the
total number of digits used to display the floating-point value is 3.
Because the value has three digits to the left of the decimal point, the
value is rounded to the ones position.
Outputs:
94
Java for Beginners
Flag Description
- (minus Left justify the output within the specified field.
sign)
+ (plus Display a plus sign preceding positive values and a
sign) minus sign preceding negative values.
space Print a space before a positive value not printed with
the + flag.
# Prefix 0 to the output value when used with the octal
conversion character o.
Prefix 0x to the output value when used with the
hexadecimal conversion character x.
0 (zero) Pad a field with leading zeros.
, (comma) Use the locale-specific thousands separator (i.e., ',' for
U.S. locale) to display decimal and floating-point
numbers.
( Enclose negative numbers in parentheses.
95
floating-point number. Note that line 9 serves as a counting
mechanism for the screen output.
Columns:
0123456789012345678901234567890123456789
hello 7 a 1.230000
hello 7 a 1.230000
The next code prints a positive number and a negative number, each
with and without the + flag. Note that the minus sign is displayed in
both cases, but the plus sign is displayed only when the + flag is
used.
786 -786
+786 -786
96
Java for Beginners
11 System.out.printf(“%#x\n”, c );
Outputs:
037
0x1f
The next snippet combines the + flag, the 0 flag and the space flag to
print 452 in a field of width 9 with a + sign and leading zeros, next
prints 452 in a field of width 9 using only the 0 flag, then prints 452
in a field of width 9 using only the space flag.
Outputs:
+00000452
000000452
452
The next snippet use the comma (,) flag to display a decimal and a
floating-point number with the thousands separator.
8 System.out.printf(“%,d\n”, 58625);
9 System.out.printf( “%, .2f”, 58625.21 );
10 System.out.printf(“%, .2f”, 12345678.9);
Outputs:
58,625
58,625.21
12,345,678.90
97
8 System.out.printf(“%(d\n”,50 );
9 System.out.printf(“%(d\n”,-50);
10 System.out.printf(“%(.1e\n”,-50.0);
Outputs:
50
(50)
(5.0e+01)
Outputs:
Parameter list without reordering: first second third fourth
Parameter list after reordering: fourth third second first
98
Java for Beginners
2.20.10 Printing Literals and Escape Sequences
99
Note:
Attempting to print as literal data in a printf statement a double
quote or backslash character without preceding that character with a
backslash to form a proper escape sequence might result in a syntax
error.
E9
3 import java.util.Formatter;
4 import javax.swing.JOptionPane;
5
6 public class FormatterTest 7 {
8 public static void main( String args[ ] ) {
9
10 // create Formatter and format output
11 Formatter formatter = new Formatter();
12 formatter.format(“%d = %#o = %#X”, 10, 10, 10);
13
14 // display output in JOptionPane
15 JOptionPane.showMessageDialog( null, formatter.toString());
16 } // end main
17 } // end class FormatterTest
100
Java for Beginners
java.sun.com/j2se/5.0/ docs/api/java/util/Formatter.html.
101
TUTORIAL QUESTIONS
102
Java for Beginners
(c) Consider the following code snippet:
System.out.println(x);
System.out.print(y);
System.out.println( );
System.out.print(z);
103
3
Control Flow Statements
3.0 Introduction
When you write a program, you type statements into a file. Without
control flow statements, the interpreter executes these statements in
the order they appear in the file from left to right, top to bottom.
Basically, there are three types of control structures in a
programming language. The following table gives a summary of
these structures.
104
Java for Beginners
Character.isUpperCase(aChar):
char c;
...
if (Character.isUpperCase(aChar)) {
System.out.println("The character " + aChar + "
is upper case.");
}
Decision making /
if-else, switch-case
selection
105
program prints debugging information, based on the value of a
boolean variable named DEBUG. If DEBUG is true, your program
prints debugging information, such as the value of a variable, such as
x. Otherwise, your program proceeds normally. A segment of code
to implement this might look like this:
if (DEBUG) {
System.out.println("DEBUG: x = " + x);
}
if (logical expression) {
statement(s)
}
As another example:
if (x < 50)
System.out.println(“The score is below cut off”);
106
Java for Beginners
...
// response is either OK or CANCEL depending
// on the button that the user pressed
...
if (response == OK) {
// code to perform OK action
} else {
// code to perform Cancel action
}
E10:
public class IfElse {
public static void main(String[ ] args) {
int testscore = 76;
char grade;
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
107
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " +
grade);
}
}
Grade = C
You may have noticed that the value of testscore can satisfy more
than one of the expressions in the compound if statement: 76 >= 70
and 76 >= 60. However, as the runtime system processes a
compound if statement such as this one, once a condition is satisfied,
the appropriate statements are executed (grade = 'C';), and control
passes out of the if statement without evaluating the remaining
conditions.
-b d
X =
2a
d = discriminant = b2 – 4ac
108
Java for Beginners
E11:
// program to compute the roots of a quadratic equation
import java.util.Scanner;
class quadratic {
public static void main(String[ ] args) {
Scanner input = new Scanner(System.in);
// getting the values of the coefficients a, b and c
System.out.println("Enter the value of a");
float a = input.nextFloat();
System.out.println("Enter the value of b");
float b = input.nextFloat();
System.out.println("Enter the value of c");
float c = input.nextFloat();
//computing the discriminant d
double d = b*b - 4.0*a*c;
// testing for the solution path
if (d<0) {
System.out.println("Complex roots pleas...");
}
else if (d == 0) {
System.out.println("Only one real root exists with
value....");
double x =( -b)/(2*a);
System.out.println(x);
}
else {
double x1 = ((-b) + Math.sqrt(d))/(2*a);
double x2 = ((-b) - Math.sqrt(d))/(2*a);
System.out.println("Two real roots exists with values...");
System.out.println(x1 + " and " + x2);
}
System.out.println("Bye - Bye to the user");
System.exit(0);
}
}
109
Ternary Operator ?:
if (Character.isUpperCase(aChar)) {
System.out.println("The character " + aChar + " is
upper case.");
}
else {
110
Java for Beginners
System.out.println("The character " + aChar + "
is lower case.");
}
Here is how you could rewrite that statement using the ?: operator:
Another example:
Can you guess what output will be printed out from the above
program segment if x were to be 47?
111
E12:
The switch statement evaluates its expression, in this case the value
of month, and executes the appropriate case statement. Thus, the
output of the program is: August. Of course, you could implement
this by using an if statement:
int month = 8;
if (month == 1) {
System.out.println("January");
} else if (month == 2) {
System.out.println("February");
}
. . . // and so on
112
Java for Beginners
can make decisions based only on a single integer value. Also, the
value provided to each case statement must be unique. Another point
of interest in the switch statement is the break statement after each
case. Each break statement terminates the enclosing switch
statement, and the flow of control continues with the first statement
following the switch block. The break statements are necessary
because without them, the case statements fall through. That is,
without an explicit break, control will flow sequentially through
subsequent case statements. Following is an example,
SwitchDemo2, which illustrates why it might be useful to have case
statements fall through:
E13:
public class SwitchDemo2 {
public static void main(String[ ] args) {
int month = 2;
int year = 2000;
int numDays = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) && !(year%100 == 0))
|| (year % 400 == 0) )
numDays = 29;
else
numDays = 28;
113
break;
}
System.out.println("Number of Days = " + numDays);
}
}
Technically, the final break is not required because flow would fall
out of the switch statement anyway. However, we recommend using
a break for the last case statement just in case you need to add more
case statements at a later date. This makes modifying the code easier
and less error-prone. You will see break used to terminate loops in
Branching Statements. Finally, you can use the default statement at
the end of the switch to handle all values that aren't explicitly
handled by one of the case statements.
int month = 8;
...
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
default: System.out.println("Hey, that's not a valid
month!"); break;
}
114
Java for Beginners
The following program gives a real-life application of the switch –
case structure. The program computes the area and pperimeters of
some common plane shapes.
E14:
import java.util.Scanner;
class shapes {
public static void main(String[ ] args) {
Scanner input = new Scanner(System.in);
System.out.println("This program computes the area and perimeter
of plane shapes" + " \n Enter 1 for Rectangle \n Enter 2 for
Square \n Enter 3 for Circle \n Enter 4 for Parallelogram" +
"\n Enter 5 for Triangle \n Enter 6 to exit the program \n\n Your
Option here...");
int option = input.nextInt();
System.out.println();
switch (option) {
case 1: System.out.println("You have chosen Rectangle");
System.out.println("Enter its length");
float l = input.nextFloat();
System.out.println("Enter its breadth");
float b = input.nextFloat();
double a = l * b;
double p = 2.0 *(l + b);
System.out.println("Area = "+ a +" Cm"+ "\nPerimeter =
"+ p + " Cm-square");
System.out.println();
break;
116
Java for Beginners
case 6: System.out.println("You have chosen to exit, Thank you,
Program stops...");
System.out.println();
System.exit(0); break;
System.out.println();
System.out.println("Thanks for using this program, Bye...");
System.out.println();
System.exit(0);
} // end method main
} // end class shapes
Sample Output:
117
3.3 The for Statement
The for statement provides a compact way to iterate over a range of
values. It is used when we know ahead the number of times a section
of code is to be repeated. It is a counter-controlled loop.
The general form of the for statement can be expressed like this:
for ( ; ; ) {
The Demo program that follows adds the numbers from 1 to 10 and
displays the result.
E15:
public class Demo {
public static void main(String[ ] args) {
int sum = 0;
for (int i = 1; i<= 10; i++) {
sum += i;
}
118
Java for Beginners
System.out.println("Sum = " + sum);
}
}
Other Examples
E16: To sum all odd numbers together from 1 to n
import java.util.Scanner;
public class number {
public static void main(String[ ] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the maximum
number to compute");
int n = in.nextInt( );
int sum = 0;
for (int i = 1; i<= n; i+=2) {
sum += i;
} //next i
System.out.println( );
System.out.println("Sum of odd from 1 to " +
n + " = " + sum);
System.out.println();
}
}
119
The sum is being used as an accumulator here and has to be
initialized to 0. It accumulates all the summations in the loop.
Often for loops are used to iterate over the elements in an array, or
the characters in a string. The following sample, ForDemo, uses a for
statement to iterate over the elements of an array and print them:
E17:
public class ForDemo {
public static void main(String[ ] args) {
int[ ] arrayOfInts = { 32, 87, 3, 589, 12,
1076,2000, 8, 622, 127 };
for (int i = 0; i < arrayOfInts.length; i++) {
System.out.print(arrayOfInts[i] + " ");
} //next i
System.out.println();
}
}
Consider the following example below which sum any 5 data items
together and report their summation:
import javax.swing.*;
class summation3 {
public static void main(String[ ] args) {
int count = 0;
float sum = 0;
for (int i =1; i<=5 ;i++ ) {
float data = Float.parseFloat(JOptionPane.
showInputDialog("Enter data no. " + i));
count++;
sum += data;
} //next i
120
Java for Beginners
JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
Exercise: Copy the above program into your editor and run it with
the following set of data: 4.6, 89, 56.7, 12.3, 10
Q? How can you modify this program to accept any number of data
items instead of only 5 data items? Compare your own solution with
the solution below:
E18:
import javax.swing.*;
class summation3 {
public static void main(String[ ] args) {
int count = 0;
float sum = 0;
int n = Integer.parseInt(JoptionPane.
ShowInputDialog(“How many numbers you want to
sum up?”));
for (int i =1; i<=n; i++ ) {
float data = Float.parseFloat(JOptionPane.
showInputDialog("Enter data no. " + i));
count++;
sum += data;
}
JOptionPane.showMessageDialog(null, "Sum of " + count +
121
" data added is " + sum, "Results",
JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
Note that you can declare a local variable within the initialization
expression of a for loop. The scope of this variable extends from its
declaration to the end of the block governed by the for statement so
it can be used in the termination and increment expressions as well.
If the variable that controls a for loop is not needed outside of the
loop, it's best to declare the variable in the initialization expression.
The names j, k, and i are often used to control for loops; declaring
them within the for loop initialization expression limits their life
span and reduces errors.
Nested For-loops
In some cases, two or more for-loops can be nested with each other.
In such cases, the innermost for-loop will run faster than the outer
one. This means that the innermost loop will have to run into
completion before the control is passed to the outermost loop.
for ( i loop) {
for (j loop) {
S;
} // next j
} // next i
Consider the example code below, which computes the times table
from 1 to 10:
E19:
class times {
public static void main(String [ ] args) {
122
Java for Beginners
for (int i = 1; i <= 10; i++) { //outermost loop
for (int j = 1; j <= 10; j++) { //innermost loop
int Times = i * j;
System.out.print(“|” + Times + “\t”);
} // Ending Innermost loop
System.out.println(“…………………………………………………….”);
} //Ending outermost loop
} // End main
} //End class
Output………………..
TIMES TABLE
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10
---------------------------------------------------------------------
| 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20
----------------------------------------------------------------------
| 3 | 6 | 9 | 12 | 15 | 18 | 21 | 24 | 27 | 30
----------------------------------------------------------------------
| 4 | 8 | 12 | 16 | 20 | 24 | 28 | 32 | 36 | 40
----------------------------------------------------------------------
| 5 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50
----------------------------------------------------------------------
| 6 | 12 | 18 | 24 | 30 | 36 | 42 | 48 | 54 | 60
----------------------------------------------------------------------
| 7 | 14 | 21 | 28 | 35 | 42 | 49 | 56 | 63 | 70
----------------------------------------------------------------------
| 8 | 16 | 24 | 32 | 40 | 48 | 56 | 64 | 72 | 80
----------------------------------------------------------------------
| 9 | 18 | 27 | 36 | 45 | 54 | 63 | 72 | 81 | 90
----------------------------------------------------------------------
| 10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100
Explanation:
At the first entry of the two for-loops, each of the loop invariants i
and j have initial values of 1 and 1 respectively. After the first
iteration, the innermost j will have to increment to 2 while i still
123
remain at 1. This is how the innermost loop will increment up to 10.
At the end of the 10th iteration, then a line will be printed and then i
now increment to 2, while j starts the iterations again as before. Note
the use of System.out.print in the innermost loop, just to print the
results in a line; and the use of System.out.println in the outermost
loop, just to move on to next line.
while (expression) {
Statements;
}
Consider the following program segment that sums all numbers from
1 to 10.
124
Java for Beginners
int sum = 0;
int i = 1;
while (i <= 10) {
sum += i;
i++;
}//end while
System.out.print(“Total sum of numbers from 1 to 10 = “ + sum);
The while first of all tests for value of i if it is less or equal to 10. If
true, then the block of code for while is executed and i is
incremented in the block. The while will continue like this until the
condition i<=10 is no more valid. Then it will jump to the statement
that follows the while block – System.out.print(“Total sum of
numbers from 1 to 10 = “ + sum);
E20:
public class WhileDemo {
public static void main(String[ ] args) {
String copyFromMe = "Copy this string until you " +
"encounter the letter 'g'.";
StringBuffer copyToMe = new StringBuffer();
int i = 0;
char c = copyFromMe.charAt(i);
while (c != 'g') {
copyToMe.append(c);
c = copyFromMe.charAt(++i);
}
System.out.println(copyToMe);
}
}
The value printed by the last line is: Copy this strin.
125
As another example: consider the following program, which
continuously accepts some positive numbers until when a negative
number is entered. The negative number terminates the loop. Any
data that is used to terminate a loop like the negative number in this
case is called a sentinel.
E21:
import javax.swing.*;
class summation {
public static void main(String[ ] args) {
int count = 0;
float sum = 0;
float data = Float.parseFloat (JOptionPane.showInputDialog("Enter
first data"));
while (data > 0) {
count++;
sum += data;
data = Float.parseFloat(JOptionPane.showInputDialog( "Enter
next data"));
}//end while
JOptionPane.showMessageDialog(null, "Sum of " + count + " data
added is " + sum,"Results",
JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
Exercise: Type the program into an editor and run the program for
the following sets of data. Record your observations.
(i) 5, 6, -5, 8, -9
(ii) –8, 8, -7
126
Java for Beginners
3.4.2 Do-while
do {
statement(s)
} while (expression);
E22:
public class DoWhileDemo {
public static void main(String[ ] args) {
String copyFromMe = "Copy this string until
you" +"encounter the letter 'g'.";
StringBuffer copyToMe = new StringBuffer();
int i = 0;
char c = copyFromMe.charAt(i);
do {
copyToMe.append(c);
c = copyFromMe.charAt(++i);
} while (c != 'g');
System.out.println(copyToMe);
}
}
The value printed by the last line is: Copy this strin.
127
For the second example on do-while, we have the following program
segment:
import javax.swing.*;
class summation1 {
public static void main(String[ ] args) {
int count = 0;
float sum = 0;
float data = Float.parseFloat(JOptionPane.showInputDialog
("Enter first data"));
do {
count++;
sum += data;
float data = Float.parseFloat (JOptionPane.showInputDialog
("Enter next data"));
} while (data > 0);
JOptionPane.showMessageDialog(null, "Sum of " + count + " data added is
" + sum,"Results", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
Practical Exercise: Type the program into an editor and run the
program for the following sets of data. Record your observations.
(i) 5, 6, -5, 8, -9
(ii) –3,6,7,8,-1,8
(iii) –8, 8, 7
128
Java for Beginners
3.5 Exception Handling Statements
try {
statement(s)
} catch (exceptiontype name) {
statement(s)
} finally {
statement(s)
}
129
3.6 Handling Errors with Exceptions
If you have done any amount of Java programming at all, you have
undoubtedly already encountered exceptions. Your first encounter with
Java exceptions was probably in the form of an error message from the
compiler like this one:
in = new FileReader(filename);
^
This message indicates that the compiler found an exception that is not
being handled. The Java language requires that a method either catch all
"checked" exceptions (those that are checked by the runtime system) or
specify that it can throw that type of exception.
The Java runtime system and many classes from Java packages
throw exceptions under some circumstances by using the throw
statement. You can use the same mechanism to throw exceptions in
your Java programs.
130
Java for Beginners
statementName: someJavaStatement;
The break statement has two forms: unlabeled and labeled. You saw
the unlabeled form of the break statement used with switch earlier.
As noted there, an unlabeled break terminates the enclosing switch
statement, and flow of control transfers to the statement immediately
following the switch. You can also use the unlabeled form of the
break statement to terminate a for, while, or do-while loop. The
131
following sample program, Breakdemo, contains a for loop that
searches for a particular value within an array:
E23:
public class BreakDemo {
public static void main(String[ ] args) {
int[ ] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127
};
int searchfor = 12;
int i = 0;
boolean foundIt = false;
for ( ; i < arrayOfInts.length; i++) {
if (arrayOfInts[i] == searchfor) {
foundIt = true;
break;
}
} //end for
if (foundIt) {
System.out.println("Found " + searchfor + " at index " + i);
} else { System.out.println(searchfor + "not in the array");
}
}
}
The break statement terminates the for loop when the value is found.
The flow of control transfers to the statement following the
enclosing for, which is the print statement at the end of the program.
The output of this program is: Found 12 at index 4
132
Java for Beginners
E24:
public class BreakWithLabelDemo {
public static void main(String[ ] args) {
int[ ][ ] arrayOfInts = { { 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i = 0;
int j = 0;
boolean foundIt = false;
search:
for ( ; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
if (foundIt) {
System.out.println("Found " + searchfor + " at "
+ i + ", " + j);
} else {
System.out.println(searchfor + "not in the
array");
}
}
}
133
3.11.2 The Continue Statement
You use the continue statement to skip the current iteration of a for,
while, or do-while loop. The unlabeled form skips to the end of the
innermost loop's body and evaluates the boolean expression that
controls the loop, basically skipping the remainder of this iteration of
the loop. The following program, ContinueDemo, steps through a
string buffer checking each letter. If the current character is not a p,
the continue statement skips the rest of the loop and proceeds to the
next character. If it is a p, the program increments a counter, and
converts the p to an uppercase letter.
E25:
public class ContinueDemo {
public static void main(String[ ] args) {
StringBuffer searchMe = new StringBuffer(
"peter piper picked a peck of pickled
peppers");
int max = searchMe.length();
int numPs = 0;
//process p's
numPs++;
searchMe.setCharAt(i, 'P');
}
System.out.println("Found " +
numPs + " p's in the string.");
System.out.println(searchMe);
}
}
Here is the output of this program:
Found 9 p's in the string.
Peter PiPer Picked a Peck of Pickled
PePPers
134
Java for Beginners
The labeled form of the continue statement skips the current iteration
of an outer loop marked with the given label. The following example
program, ContinueWithLabelDemo, uses nested loops to search for a
substring within another string. Two nested loops are required: one
to iterate over the substring and one to iterate over the string being
searched. This program uses the labeled form of continue to skip an
iteration in the outer loop:
E26:
public class ContinueWithLabelDemo {
public static void main(String[ ] args) {
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;
int max = searchMe.length() - substring.length();
test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++) !=
substring.charAt(k++)) {
continue test;
} // end if
} // end while
foundIt = true;
break test;
} // end for
System.out.println(foundIt ? "Found it" :
"Didn't find it");
}
}
135
Another example
Consider the following code, which writes and computes the sum of
all prime numbers from 20 to 100.
E27:
public class prime {
public static void main(String[ ] args) {
int sum = 0, i, j;
L1: for (i = 20; i <= 100; i++) { // numbers from 20 to 100
for (j = 2; j < i; j++) {
if (i%j = = 0) // remainder of i by j from 2 to i – 1
continue L1;
}// Next j
System.out.print(i + "\t");
sum += i;
}// Next i
System.out.println("\n" + "Total sum of prime
numbers from 20 to 100 = " + sum);
}
}
Output:
136
Java for Beginners
works like GOTO statement found in other languages like
FORTRAN. But it only works with nested loops.
return ++count;
The data type of the value returned by return must match the type of
the method's declared return value. When a method is declared void,
use the form of return that doesn't return a value: return;
Tutorial Questions
137
(a) Debug the snippet for errors (if any). If possible,
state the type of error committed and the line
number.
(b) What would be the output from the snippet given the
following streams of data as input test data:
(i) 5, -3, 2
(ii) –4, 5, 0, 1, 3
(iii) –2.5, 0, -1.7, -1, 3, 5, -3
(c) Examine whether or not the count does the real
counting for the total number of test data added. If
not, fix the error.
138
Java for Beginners
ax + by = c ……………..eq.(1)
dx + ey = f ……………..eq.(2)
(iii) do {
++x;
System.out.print( “x = ” + x);
} while (x < m);
8. (a) Find the errors (if any) in each of the following Java
code segments and explain how to correct them:
(i) i = 0;
while (i < 0)
k++;
139
float sum = 0;
for (int k = 1; k >=10; k ++)
sum = k;
140
Java for Beginners
141
The following is a logical representation of a single dimensional
array in memory.
A(1) to A(5) are subscripts of the array A and they can contain any
valid values of the same data type. The individual cell or location in
the array is also called a subscript. Subscript A(1) could contain 56
as its data. So, we reference this 56 with the subscript number, A(1).
SCORE
20 40 10 50 30
142
Java for Beginners
4.2 Creating a One-dimensional Array
Examples:
float[ ] x; // declares x to be a reference to an array of floats
x = new float[8]; // allocates an array of 8 floats, referenced by x
boolean [ ] flags = new boolean[8];
int [ ] score = new score[20];
143
anything about java zero-based indexing. Data entered at this point
will be assigned to location 0 of the array. The for loop will iterate
until the length of the array has been filled up. Note that the
termination point of the loop should be 1 less than the total array
length because we are starting from subscript zero (i <
arrayName.length). If we had used i <= arrayName.length, then we
would have commited an arrayOutOfBoundException error, i.e., we
go beyond the length of the array. The length function should not
contain parenthesis, ( ) as in the String length function.
Study the code below and explain the algorithm for reversing the
elements of a one-dimensional array.
E28:
import javax.swing.*;
class arrayReverse {
public static void main (String[] args) {
int n = Integer.parseInt(JOptionPane.showInputDialog
("Enter the length of the array"));
int[ ] a = new int[n];
// Reading Data into the Array a
for (int m = 0; m < n; m++)
a[m] = Integer.parseInt(JOptionPane.showInputDialog
("Enter data"+ (m+1)));
144
Java for Beginners
System.out.print(a[l] + "\t");
System.out.println("\n");
145
4.6 Character Arrays
The element-type of character Array is char. The strings are nearly
the same as the character array but with little difference. The
program below compares a string object with a char array.
E29:
class TestCharArrays {
public static void main(String args[ ]) {
String s = new String( "ABCDEFG");
char[ ] a = s.toCharArray();
System.out.print("S = "+ s +" \t a =" + a + "\' " );
System.out.print("s.length()=" + s.length()+"\t
a.length = " + a.length );
for (int i = 0; i < s.length(); i++)
System.out.print("S. charAt("+i +") = " + s.charAt(i)
+ "\t a [ " + i + "] =" + a[i]);
}
}
The output is
s = “ABCDEFG” a =”ABCDEFG”
s.length() = 7 a. length = 7
s.charAt(0) = A a[0] = A
s.chartAt(1) = B a[1] = B
. .
. .
. .
s.chartAt(6) = G a[6] = G
Note that
Arrays are zero-based indexing, i.e., the first element has
index 0.
s and a are reference variables.
s refers to a string object while a refers to a char[ ] object
Array objects have a public field named length which stores
the number of elements in the array. So the expression a.length
is analogous to the invocation of s.length( ).
146
Java for Beginners
An array of length n has index numbers from 0 to n-1.
We can initialize an array explicitly with an initialization list :
like this:
int [ ] c;
c = new int [4];
c[0] = 44;
c[1] = 88;
c[2] = 55;
c[3] = 33;
34 23 24
24 56 13
15 10 19
For example,
147
To assign a value to a location in the array:
a[0][2] = 50;
The snippet uses two nested for loops. The first i-loop moves round
the rows while the inner j-loop moves round the columns of the
array. As you have been taught while learning nested for loop
control structure, the j-loop moves faster than the i-loop. This means
that for each row i, the columns would heve to be filled first before
going to the next row. The row length is specified as a.length while
the column length is specified as a[i].length. Why the a[i].length for
the column number? This is because each row of a two-dimensional
array is an array itself with its own length. As i increases, it denotes
the next row to operate on.
E30:
import javax.swing.*;
import java.text.DecimalFormat; // to format our output
class array2D {
public static void main(String[ ] args) {
148
Java for Beginners
float[ ][ ] score; //declaring a 2-dimensional array
int r = Integer.parseInt(JOptionPane.showInputDialog
("Enter number of rows for the 2-dimensional array"));
int c= Integer.parseInt(JOptionPane.showInputDialog
("Enter number of columns for the 2-dimensional array"));
149
} //Ending outermost loop to process another row of data
150
Java for Beginners
Note:
(i) We use i<r and i<c in the for loops, instead of <= to avoid
array out-of-bound-exception, i.e. We don’t want to go
beyond the array’s dimension, since java array indexing
starts from zero. Again, we try to use the conventional
means of accessing array, not using the array.length method.
(ii) To do any arithmetic computation inside a string, we need to
put the expression inside a bracket within the string. For
instance, we have (i+1) inside the string of showInputDialog
and that of the output. Can you guess the reason why we use
(i + 1) and (j + 1) instead of ordinary i and j in the
showInputDialog?
(iii) Note the effect of the DecimalFormat method. It is a
powerful method from the Text class which can be used to
format our output to some number of decimal places in Java.
(iv) The two-dimensional array used in this program is assumed
to contain scores of some students in rows in some courses
done in columns.
Student1 45 67 90 76 45
Student2 60 69 59 40 47
Student3 79 58 60 32 57
Student4 56 34 70 36 49
151
Practical Exercise:
(i) Try to copy and execute the program and state your
observations.
(ii) How would you modify the program above to compute
the average for each column, that is, average score per
course?
E27:
class test {
public Static void main (String args[]) {
int [ ][ ] a = new int [7][9];
System.out.println (“a. length = ” + a.length);
System.out.println (“a[0].lenth = ” + a[0].length;
}
}
Output
a.length = 7
a[0].length = 9
152
Java for Beginners
E31:
class test2 {
public static void main (String args[]) {
int [ ][ ] a = { { 77, 33, 88},
{11, 55, 22, 99},
{66, 44}
};
for (int i = 0; i < a.length; i++) {
for (int j = 0; j< a[i].length; j++)
System.out.print (“\t” + a[i][j]);
System.out.println();
}
}
}
The output is
77 33 88
11 55 22 99
66 44
Note: The use of nested for loops, which is the standard way to
process 2-dimensional arrays. The outside loop is controlled by the
row index i, and the inside loop is controlled by the column index j.
The row index i increments until it reaches a.length, which is 3 in
this example. For each value of i, the column index j increments
until it reaches a[i].length, which in this example is 3 when i=0, 4
when i = 1 and 2 when I = 2.
153
number i and a[i] would represent page number i. The number of
characters on line j on page i would be a[i][j].length and the number
of lines on page i would be a[I].length. So, iteration of the first loop
would process page [i], iteration j of the second loop would process
line a[i][j] and the iteration k of the third loop would process
character a[i][j][k].
import javax.swing.*;
import java.text.DecimalFormat;
154
Java for Beginners
String result="";
int studnum, coursenum, i,j,cunit=0;
String studNum, courseNum, courseUnit;
try{
studNum=JOptionPane.showInputDialog(
"Enter the number of Students");
courseNum=JOptionPane.showInputDialog(
"Enter the number of Courses Offered");
studnum=Integer.parseInt(studNum);
coursenum=Integer.parseInt(courseNum);
for(i=0;i<coursenum;i++) {
courseUnit=JOptionPane.showInputDialog(
"Enter the Course Unit for Course "+(i+1));
unitAry[i]=Integer.parseInt(courseUnit);
cunit+=unitAry[i];
}
for(i=0;i<studnum;i++) {
nameAry[i] = JOptionPane.showInputDialog(
"Enter the name of Student"+(i+1));
CWGPary[i] = 0;
for(j=0;j<coursenum;j++) {
String scoreStr = JOptionPane.showInputDialog(
"Enter Student "+(i+1)+"'s Score for Course "+
(j+1)+"\n\nBetween the range 0-100");
155
scoreAry[i][j] = Integer.parseInt(scoreStr);
{
if (scoreAry[i] [j] >100)
GPary[i] [j]= 0;
else if (scoreAry[i] [j]>=70)
GPary[i] [j]=7;
else if (scoreAry[i] [j]>=65)
GPary[i] [j]=6;
else if (scoreAry[i] [j]>=60)
GPary[i] [j]=5;
else if (scoreAry[i] [j]>=55)
GPary[i] [j]=4;
else if (scoreAry[i] [j]>=50)
GPary[i] [j]=3;
else if (scoreAry[i] [j]>=45)
GPary[i] [j]=2;
else if (scoreAry[i] [j]>=40)
GPary[i] [j]=1;
else
GPary[i] [j]=0;
}
WGPary[i] [j] = GPary[i] [j]*unitAry[j];
CWGPary[i] +=WGPary[i] [j];
}
}
// PRESENTING THE RESULT TO THE USER
for(i=0;i<studnum;i++) {
result += "STATEMENT OF RESULT FOR : "+ nameAry[i] + "\n"+
"\nCourse\tCourse Unit\tScore\tGP\tWGP" +"\n";
for(j=0;j<coursenum;j++){
result += "\nCourse " + (j+1) + "\t" + unitAry[j] + "\t"
+ scoreAry[i] [j] + "\t" + GPary[i] [j] + "\t" + WGPary[i] [j];
}
CGPA=(double)CWGPary[i]/cunit;
result += "\n\nThe CGPA is "+onedigit.format(CGPA)+
"\n\n\n";
g}
156
Java for Beginners
output.setEditable(false);
output.setText(result);
JOptionPane.showMessageDialog(null,scrollbar,
"THIS IS THE STUDENTS STATEMENT OF RESULT",
JOptionPane.INFORMATION_MESSAGE);
}
catch(NumberFormatException nfe){
JOptionPane.showMessageDialog(null,"Wrong data type
input", "ERROR IN INPUT FORMAT",
JOptionPane.ERROR_MESSAGE);
}
System.exit(0);
}
}
Part output screen shots for this program are shown below
157
Exercise: Modify program E32 so as to print out the results in form
of real academic transcripts.
158
Java for Beginners
E33: This code is on Matrix Operations
import javax.swing.*;
/* This program accepts data into two 2-dimensional arrays which
represents any two matrices and then computes the sum, difference, product
and transpose of the matrices. All conditions for these operations on
matrices are tested appropriately by the program */
159
}
}
160
Java for Beginners
for (int j = 0; j < matX[i].length; j++) {
matSub[i][j] = matX[i][j] - matY[i][j];
System.out.print(matSub[i][j] + " ");
}
System.out.println( );
}
System.out.println();
// Ends matrices subtraction
} // Ends else statement
// Validates conditions for matrices multiplication…
if (cno == rno ) {
//Begin multiplication of the matrices
System.out.println("The product of the matrices X and Y is :");
System.out.println();
double matMult [ ][ ] = new double[3][3];
for (int i = 0; i < matX.length; i++) {
for (int j = 0; j < matX[i].length; j++) {
matMult [i][j] = 0;
for (int k = 0; k < matX.length; k++) {
matMult[i][j] += matX[i][k] * matY[k][j];
} // Ends innermost for loop
System.out.print(matMult[i][j] + " ");
} // Ends middle for loop
System.out.println();
} // Ends outermost first for loop
// Ends multiplication of matrices
} // Ends the if .. condition
else
System.out.println("This matrices cannot be multiplied together");
161
matTransp [i][j] = matX[j][i];
System.out.print(matTransp[i][j] + " ");
}
System.out.println();
}
// Ends transposing of matrix X
System.out.println();
System.out.println("Bye- bye to the user" );
} // ends method-main
} // ends class
Sample Output:
162
Java for Beginners
163
E34:
import javax.swing.*;
import java.util.*;
class array {
public static void main(String[ ] args) {
int n = Integer.parseInt(JOptionPane.showInputDialog("Enter the size
of the array"));
System.out.println( );
// Sorting the array using a predefined sort procedure
Arrays.sort(a);
System.out.println( );
System.exit(0);
}
}
Sample Output
164
Java for Beginners
Practical Exercise
The following simple line of code would create a vector for you:
This means the vector will support 25 elements. But vectors can be
expanded! Therefore, for the vector to accept more data, we will
specify the factor of expansion. So we could declare the vector like
this:
165
This vector has an initial size of 25 elements and expands in
increments of 5 elements when more than 25 elements are added to
it. That means the vector jumps to 30 elements in size, and then 35,
and so on.
Just like in arrays, we use the square brackets (“[ ]”) to achieve this
operation in vectors.
v.add(“Akinola”);
v.add(“S. O.”);
v.add(“Ibadan”);
The following code will retrieve the last element added to the vector
v:
String s = (String)v.lastElement();
So, s will be assigned ‘Ibadan’ at the end of the operation. Note the
casting into String (the keyword String is put into bracket) for the
vector. This is because a vector is designed to work with the object
class.
166
Java for Beginners
4.9.5 Retrieving elements at a particular index from
a Vector
String s1 = (String)v.get(0);
String s2 = (String)v.get(2);
v.add(1, “Solomon”);
v.add(0, “Olalekan”);
v.remove (3);
Olalekan
Solomon
Akinola
S. O.
Ibadan
167
Olalekan
Solomon
Akinola
Ibadan
v.removeElement(”S. O.”);
v.set(1, “Olasunkanmi”);
Use the following code to clear all the elements from the vector v.
v.clear();
168
Java for Beginners
int i = v.indexOf(“Akinola”);
Tutorial Questions
e d c b a
f
g h i
169
3. Write a program to compute the average values of data for
each region from the data above assuming the data are
stored in a two-dimensional array.
(X – X)(Y – Y)
Rc =
(X – X)2 (Y – Y)2
170
Java for Beginners
171
5
Java Methods
(Subprograms)
5.0 Introduction
Y = Math.sqrt(x);
Y = Integer.parseInt(x);
172
Java for Beginners
Math.sqrt and Integer.parseInt are the method names and x is the
argument in the above arithmetic expressions.
173
Note:
(i) To promote software reusability, each method should be limited
to performing a single, well-defined task, and the name of the
method should express that task effectively.
(ii) A method should usually be no longer than one printed page.
Better yet, a method should usually be no longer than half a
printed page. Regardless of how long a method is, it should
perform one task well. Small methods promote software
reusability.
174
Java for Beginners
To use any of the above-predefined methods, we need to append
Math as subscript to them. For instance, we could write xSqrt =
Math.sqrt(x-y);
175
list is empty (i.e., the name of the method is followed by an empty
set of parentheses). Parameters are sometimes called formal
parameters.
There are three ways of returning control to the statement that calls a
method.
If the method does not return a result, control returns when
the program flow reaches the method’s ending right brace;
Or when the statement
176
Java for Beginners
return;
is executed; and
If the method returns a result, the statement
return expression;
evaluates the expression, then returns the
resulting value to the caller.
Output
C:\j2sdk1.4.2_04\bin>java TestCube
0 0
1 1
2 8
3 27
4 64
5 125
177
5.3.1 Where Can We Place Our Methods?
Methods could be placed at the end of the main method as was done
in Example 1 above. That is, after we might have written all the
codes for the main(String[ ] args) method.
import javax.swing.*;
class sumMeanMax {
178
Java for Beginners
// The main method
Sample Output:
179
Note: Methods can call another method if it will need the method.
An example is illustrated in the method mean above, repeated below:
Also, a local variable has its scope only within the method that
declares it. An attempt to reference add, which is declared in the
mean method in another method will produce an error. Refer to
Section 2.9 for further knowledge on this.
Exercise: Rewrite the Maxim method for any three numbers using
the Math.max method.
E37: This program calculates the square, square root, cube, cube
root of numbers.
JOptionPane.showMessageDialog(null,scroller,
"CALCULATION", JOptionPane.INFORMATION_MESSAGE);
180
Java for Beginners
System.exit(0);
}//END MAIN
181
Exercise: Modify the above program to bring out the result in a
good formatted output, possibly up to two decimal places tabulated.
import javax.swing.JOptionPane;
class factorial {
// The Factorial Method
static long fac(int n) {
if (n <= 1)
return 1;
long f = 1;
for (int i = n; i >= 2; i--)
f = f*i;
return f;
}
// Method Main
public static void main(String[ ] args) {
int n = Integer.parseInt(JOptionPane.showInputDialog ("Enter
the value of n"));
long fact = fac(n); // fact declared as long precision data
JOptionPane.showMessageDialog(null, "Factorial of "
+ n + " = " + fact, "Result",
JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
182
Java for Beginners
Exercise: Extend the above program to compute the combination of
n and r, (nCr).
swap(score);
183
E39: The program below passes an array into a method and
computes the mean value in the array
import javax.swing.*;
class arrayMethod {
//Main program
public static void main (String[ ] args) {
// declaring the length of the array
int n = Integer.parseInt(JOptionPane.showInputDialog("Enter the
length of the array"));
int[ ] a = new int[n];
System.out.println("\n");
184
Java for Beginners
}
}
Sample Output:
185
while(array[highest] > pointer) highest--;
if(lowest < highest) {
interchange(array,lowest,highest);
lowest++;
highest--;
}
}
interchange(array,first,highest);
return highest;
}
public static void qsort(int[]array1, int first, int last){
int pointerIndex;
if (first < last) {
pointerIndex = split(array1, first, last);
quicksort(array1, first , pointerIndex-1);
quicksort(array1, pointerIndex+1, last);
}
}
public static void main(String[ ] args) {
long initialTime,finalTime; // Getting time for sorting
String result = " ";
int array[ ] = {38,55,75,26,29,1,34,65,53,3,34,35,54,11};
int size = array.length;
result += "Original content of array \n";
for (int index = 0; index != array.length; index++) {
result += array[index] + " ";
}
initialTime = System.currentTimeMillis();
quicksort(array,0,size-1);
finalTime = System.currentTimeMillis();
result+="\n\n sorted array\n";
for (int index = 0; index != array.length; index++){
result += array[index] + " ";
}
result+="\n time taking for sorting "+(initialTime –
finalTime)+" milliseconds";
JOptionPane.showMessageDialog(null,result,"result",JOptionPane
.INFORMATION_MESSAGE);
System.exit(0);
186
Java for Beginners
}
}
The next figure illustrates the output obtained from running the
program.
187
Since the values of random numbers we need in most applications
would be in integers, then, we need to type-cast the values returned
by the generator. We also need to specify the initial and final values
of numbers we want.
(int)(Math.random( ) * 6)
import javax.swing.*;
public class RandomDie {
public static void main(String[ ] args) {
String output = " "; // for appending results
for (int i = 1; i <= 20; i++) {
//Generates random integers from 1 to 6
188
Java for Beginners
int value = 1 +(int)(Math.random() * 6);
output += value + " "; //append value to output
// if i is divisible by 5, append new line to output
if (i % 5 == 0)
output += "\n";
} //end for-loop
JOptionPane.showMessageDialog(null, output, "20 Random numbers from
1 to 6", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
} // end main method
} //end class
Output:
Practical Exercise: Copy this code into your editor, compile and
execute this program.
189
there is no remainder that equals zero; therefore 23 is prime.
Examine critically the program below that generates a random
integer in the range 2 to 100 and then tests it for primality.
E42:
import java.util.Random;
public class prime {
public static void main(String[ ] args) {
Random random = new Random();
float x = random.nextFloat();
System.out.println("x = " + x);
int n = (int)Math.ceil(100*x);
for (int d = 2; d < n; d++) {
if (n % d == 0) {
System.out.println(n + " is not prime.");
return;
}
}
System.out.println(n + " is prime.");
}
}
C:\j2sdk1.4.2_04\bin>java prime
x = 0.7044986
71 is prime.
C:\j2sdk1.4.2_04\bin>java prime
x = 0.6379936
64 is not prime.
If a method would only receive data but will not return any value to
any other method, that method is void in nature. And if a method has
a void return type, control returns at the method-ending right brace
or by executing the statement:
return;
190
Java for Beginners
Consider the Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, 21, ….
The series begins with 0 and 1 and has the property that each
subsequent Fibonacci number is the sum of the previous two
Fibonacci numbers. The ratio of successive Fibonacci numbers
converges on a constant value 1.618, a number called the golden
ratio or golden mean. The Fibonacci model equation is given as:
Fibonacci(0) = 0
Fibonacci(1) = 1
Fibonacci(n) = Fibonacci(n – 1) + Fibonacci(n – 2)
191
public static void main(String[ ] args) {
int n = Integer.parseInt(JOptionPane.showInputDialog
("Enter the terminating point for n: "));
}
}
Output:
Fib[0] = 0
Fib[1] = 1
Fib[2] = 1
Fib[3] = 2
Fib[4] = 3
Fib[5] = 5
Fib[6] = 8
Fib[7] = 13
Fib[8] = 21
Fib[9] = 34
Note that the method fibn is just called at the main method without
assigning it to any variable or object; since it is not going to return a
value to anywhere.
192
Java for Beginners
193
System.out.println("\n");
Sample Output…
194
Java for Beginners
problem, it divides the problem into two conceptual pieces: a piece
that the method knows how to solve (the base case) and a piece that
the method does not know how to solve. The latter piece must
resemble the original problem but be a slightly simpler or slightly
smaller version of it. Because this new problem looks like the
original problem, the method calls a fresh copy of itself to work on
the small problem. This procedure is called a recursive call or
recursion step. The recursion step must include a return statement
because its result will be combined with the portion of the problem
the method knew how to solve to form a result that will passed back
to the original caller.
The recursion step executes while the original call has not finished
executing. As a matter of fact, there could be many recursion calls,
as the method divides each new subproblem into two conceptual
pieces.
195
Comparing Recursion and Iteration
196
Java for Beginners
Tutorial Questions
E45:
package util;
import java.util.Arrays;
197
if (lcm % Math.abs(numbers[i]) == 0) {
count++;
continue;
} else {
break;
}
}
if (count == (numbers.length - 1)) {
lcmFound = true; break;
}
count = 0; //resetting count in case another go is required
lm = largest * ++mult;
} while (lcmFound == false);
return lcm;
}
198
Java for Beginners
Strings Manipulation
In Java
6.0 Introduction
The simplest type of string in Java is an object of the string class and
cannot be changed.
{
String alphabet = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
int StringLength = alphabet.length();
System.out.println(“Length of the English Alphabets is ” +
StringLength);
}
199
Note the length method used in this case as different from that of the
array. Length method in strings has the opening and closing brackets
as suffix, length( ), i.e., it is a method without any argument passed
into it.
The hash code gives the unique integer value for a string.
The number or code has no meaning other than serving as a
numeric label for the object. Hash values are used as storage
locators when the objects are stored in tables. Although each
string object has one and only one hash code, the same
number may be the hash code for more than one object. This
operation is commonly used in compiler construction.
200
Java for Beginners
substrings from strings. Two arguments are normally passed
into this method, the lower and upper indices. To get this
method clear, we have to find the difference between the
two indices, say 8 – 4 = 4 as in the example below. This now
means that we are extracting a total of 4 characters starting
from the lower index (4) upwards.
For example:
String a1 = “I am coming ”;
String b = “to you soon”;
String c1 = a1 + b;
String c2 = a1.concat(b);
201
(8) Searching for Characters in a String: We can search
for a particular character in a string. Also, we can look for
other positions or indexes of the character in the string.
Consider the example below:
202
Java for Beginners
E46:
public class TextConversion {
public static void main (String[ ] args) {
String today = "Feb 18, 2009";
String todaysDayString = today.substring(4,6);
int todaysDayInt = Integer.parseInt(todaysDayString);
int nextWeeksDayInt = todaysDayInt + 7;
String nextWeek = today.substring(0,4) + nextWeeksDayInt +
today.substring(6);
System.out.println("Today’s date is" + today);
System.out.println("Today’s day is" + todaysDayInt);
System.out.println("Next week’s day is " +
nextWeeksDayInt);
System.out.println("Next week’s date is " + nextWeek);
}
}
The Output:
203
11. Comparing Strings Using the Methods equals,
equalIgnoreCase, compareTo and regionMatches
if (s1.equals(“akinola”))
if (s3.equalsIgnoreCase(s4))
the condition will be true since the cases of the letters does not
matter in “Happy Day” and “happy day” strings. This method is
ideal for sorting strings.
204
Java for Beginners
Method compareTo returns zero (0) if the strings are equal, a
negative number if the string that invokes compareTo is less than the
string that is passed as an argument and a positive number if
otherwise. That is, the invoking string is greater than the argument.
The method uses a lexicographical comparison to compare the
numeric values of corresponding characters in each string. For
instance, the code:
205
for (int i = 0; i< sArray.length; i++) {
for (int j = (i + 1); j < sArray.length; j++) {
int k = sArray[i].compareTo(sArray[j]);
// compareTo( ) returns a negative, zero or positive integer
// if compareTo( ) returns a positive integer, swap the
// elements position
if (k > 0) {
String temp = sArray[i];
sArray[i] = sArray[j];
sArray[j] = temp;
} //end if
} // next j
} //next i
206
Java for Beginners
invokes the method. The second argument is a comparison string.
The third is the starting index in the comparison string and the last is
the number of characters to compare between the two strings. The
method only returns true only if the specified number of characters
are lexicographically equal. For example,
Note that this method is case sensitive. In this case, the else path will
be followed. However, if we want to ignore cases, then the code
would be written as follows:
E48:
public class str{
public static void main(String[ ] args) {
207
for (int k = 0; k< strings.length; k++)
if (strings[k].startsWith("Ak"))
output += strings[k] + " starts with Ak\n";
// test method startsWith starting from a position
for (int k = 0; k < strings.length; k++)
if (strings[k].startsWith("ol", 5 ))
output += strings[k] + " starts with ol at position
5 \n";
// test method endsWith
for (int k = 0; k < strings.length; k++)
if (strings[k].endsWith("la"))
output += strings[k] + " ends with la\n" ;
System.out.print(output);
}
}
Output
C:\j2sdk1.4.2_04\bin>java str
Akin starts with Ak
Akinola starts with Ak
Akintola starts with Ak
Akinsola starts with Ak
Akintola starts with ol at position 5
Akinsola starts with ol at position 5
Akinola ends with la
Akintola ends with la
Akinsola ends with la
208
Java for Beginners
E49:
public class sR {
public static void main(String[ ] args) {
String string = "My name is Akinola";
for (int i = string.length( )-1; i>=0; i--)
System.out.print(string.charAt(i));
}
}
Output
C:\j2sdk1.4.2_04\bin>java sR
alonikA si eman yM
String s1 = “ Akinola “;
String s2 = s1.trim()
// no more spaces before and after Akinola
209
16. String Tokenizer: StringTokenizer class is a class from
package java.util, which breaks a string into its component
tokens. Tokens are individual words and punctuations, each
of which conveys meaning to a reader of a sentence. Tokens
are separated from one another by delimiters, such as space,
tab, new line and carriage return. This class would be useful
in compiler’s tokenization. Compilers breaks up statements
into individual pieces like keywords, identifiers, operators
and other elements of a programming language. The
following program illustrates string tokenization in Java.
E50:
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
210
Java for Beginners
} // end anonymous inner class
); // end call to addActionListener
container.add(input);
output = new JTextArea(10,20);
output.setEditable(false);
container.add(new JScrollPane(output));
setSize(275,240); // set the window size
setVisible(true); // show the window
}
// execute application
public static void main(String [] args) {
tokens application = new tokens();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
} //END CLASS TOKENS
Sample Output:
211
E51: As another example, consider this small efficient code:
import java.util.*;
import javax.swing.*;
class Tokenizer{
public static void main (String[ ] args){
String str = JOptionPane.showInputDialog("Enter the
string");
StringTokenizer tokens = new StringTokenizer(str);
System.out.println(tokens.countTokens()+"Tokens");
String [ ] words = new String[tokens.countTokens()];
while (tokens.hasMoreTokens()){
System.out.println(tokens.nextToken());
}
}
}
Output
212
Java for Beginners
17. String Splitting
// The program accepts a string, converts the string into a string array Using
//the split method prints the words / tokens in the string and finally checks
for how many times 'the' occurs in the string
213
}
System.out.println("\nTotal number oof times 'the' occurs in the string is " +
count);
System.exit(0);
}
}
Sample Output
214
Java for Beginners
In the above code, space was used to separate the tokens in the
string. Sometimes we may want to use a comma separated string in
which comma (,) will be used to separate the tokens in the string.
We only need to change the split( ) argument to comma, such as
The sorting code is re-run here but with a comma separated tokens.
Only the output is shown here.
E53:
public class TextAppending {
public static void main (String[ ] args) {
StringBuffer buf = new StringBuffer(10);
buf.append(“It was”);
System.out.println(“Initial string is:“ + buf);
buf.append(“the best”);
215
System.out.println(“Final string is: “ + buf);
}
}
Output:
Initial string is: It was
Final string is: It was the best
buf.SetCharAt(1,”s”);
System.out.println(“Replaced statement is:“ + buf);
i j
216
Java for Beginners
Here is a palindrome program that checks if a string is spelt same
way forwards and backwards:
E54:
import javax.swing.JOptionPane;
class palind {
public static void main(String[ ] args) {
String a =
JOptionPane.showInputDialog("This program
checks if a string is a palindrome, \n Enter any string
of your choice: ");
boolean stop = false;
int i = 0, j = a.length()-1;
217
Sample Output
218
Java for Beginners
import javax.swing.*;
class palindrome{
public static void main(String[ ]args){
String str = JOptionPane.showInputDialog("Enter sting
to check");
int lengthstr = str.length();
String reverse = "";
for (int i=lengthstr-1;i >= 0 ;i-- ){
reverse += str.charAt(i);
}
if (str.equalsIgnoreCase(reverse)) {
JOptionPane.showMessageDialog(null,"String
"+str+" is a palindrome");
}
219
else {
JOptionPane.showMessageDialog(null,"String "+str+"
is not palindrome");
}
}
}
TUTORIAL QUESTIONS
220
Java for Beginners
E56:
// Finding the average of two numbers
221
// java packages needed to be imported…………
import java.awt.*;
import javax.swing.*;
public class AverageApplet extends JApplet {
// Initializing sum and average with global scope
Now, let us explain this program and how it could be compiled and
run.
222
Java for Beginners
223
paint defines the method’s parameter list, which specifies the
data that the method requires to perform its task. We pass data
to a method through a method call (also known as invoking a
method or sending a message). The first argument to
drawstring is a string to draw. The last two arguments in the
list – 25 and 25 – are the x-y coordinates (or position) at which
the bottom-left corner of the string should appear. Drawing
methods from class Graphics require coordinates to specify
where to draw. Coordinates are measured from the upper-left
corner of the applet in pixels. The figure below illustrates the
java coordinates system.
(0,0) +x
x – axis
(x,y)
+y
y – axis
224
Java for Beginners
7.2 To Compile and Execute the Applet…
o Type the above code into a Notepad editor and save with
AverageApplet.htm in the same directory/folder where the
AverageApplet.class is saved.
o Exit
o Open the folder that contains the html file and double click
the file; in order to run it on an explorer (Netscape or
Microsoft Internet Explorer). Or open this file from the File
menu of the Explorer.
o The appletviewer is an ideal place to test an applet and
ensure that it executes properly. To execute AverageApplet
in the applet viewer,, open a command window, change to
the directory containing your applet and HTML document,
then type
225
appletviewer AverageApplet.html
E57:
import java.awt.Graphics;
import javax.swing.JApplet;
public class welcome extends JApplet {
// draw lines and a string on applet's background
public void paint(Graphics g) {
// call superclass version of method paint
super.paint(g);
// draw horizontal line from (15, 10) to (210, 10)
g.drawLine(15,10,210,10);
// draw another line
g.drawLine(15, 30, 210, 30);
// draw string between lines at location (25, 25)
g.drawString("You are welcome to Java World", 25, 25);
} //end method paint
226
Java for Beginners
} // end class welcome
Tutorial Exercises
227
8
Introduction to Object-Based
Programming
8.0 Introduction
A java program has one or more files that contain java classes, one
of which is public, containing a method named main(). For instance,
public static void main(String[ ] args) {
Statements;
}
javac <filename>.java;
228
Java for Beginners
<filename> is the name of the class that contains the main( ) method
to be executed while <filename>.java is the name of the file that
contains that class.
Just as Java type specifies the range of values e.g. (-32767 to 32767
for short) that variables of that type can have, a java class specifies
the range of values that objects of that class can have.
229
When a base class is extended, the new class has all the properties
and methods of its parent. We then choose whether to modify or
simply keep any method of the parents or supply new methods that
apply to the child class only. This concept of extending a base class
is called ‘inheritance’.
230
Java for Beginners
The classes do not (and often cannot) stand alone: they are the
building blocks for constructing or building stand-alone programs.
class Account {
// instance variables or class fields
String custName;
double balance;
// constructor
public Account(String name, double bal) {
custName = name;
balance = bal;
}
// method to compute new balance after deposit
public void deposit(double dep) {
balance += dep;
}
// method to get balance
public double getBalance( ) {
return balance;
}
// method to get the customer’s name
public String getName( ) {
return custName;
231
}
232
Java for Beginners
233
In this case public means that any method in any class that has
access to an instance of the Account class can call the method.
String custName;
double balance;
234
Java for Beginners
The constructor in our Account class is:
We could see that the new method is always used together with a
constructor to create an object of the class. This forces us to set the
initial state of our objects either explicitly or implicitly. An object
created without a correct initialization is useless and occasionally
dangerous. It can cause a general memory protection fault (GPF), i.e.
memory corruption.
235
Every class has at least one constructor to instantiate it. For a class
without one, the compiler will automatically declare one with no
arguments. This is called a default constructor. A default constructor
has no arguments. Java provides this type of constructor if we design
a class with no constructor. The default constructor sets all the
instance variables to their default values. All numeric data contained
in the instance fields would be zeroed out, all booleans would be
false and all object variables would point to null.
We must not introduce local variables with the same names as the
instance fields. For example, the following constructor will not set
the balance.
236
Java for Beginners
Again we must be careful in all of our methods that we don’t use
variable names that equal the names for instance fields.
sets a new value for the balance instance field in the object that
executes this method. That is, increasing it by value of dep.
Note: This method does not return a value. For example, the call
Acc.deposit(1000);
237
Any method that will get argument data from outside object
referencing the class will be declared as void, meaning that it will
not return a value outside. The data values passed into these type of
methods are normally used to manipulate the instantiating fields, or
class variables.
In order to make use of this class in programs, the Account class will
be called or referenced like we have in arrays:
Compared to an array:
int array[ ] = new int(5);
acc is a new object we are creating from the Account class. The
parameters (“Akinola S. O.”, 500) are the initial data we are sending
to the class to instantiate the class.
We could reference any of the methods of the class via the object we
create from it. For example, acc.getName() means we are
referencing the method, getName from the class, which will in turn
return the name of the account holder, Akinola S. O., passed as
instantiating data to the class.
E59:
//The Rectangle class
class Rectangle {
// instance variables
private double width;
private double height;
// constructor
public Rectangle (double h, double w) {
height = h;
width = w;
238
Java for Beginners
}
// method to return the area of the rectangle
public double area( ) {
return height * width;
}
// method to return the height of the rectangle
public double getHeight( ) {
return height;
}
// method to return the width of the rectangle
public double getWidth( ) {
return width;
}
// method to return the perimeter of the rectangle
public double perimeter() {
return 2 * (height * width);
}
}
height = myRectangle.getHeight( );
width = myRectangle.getWidth( );
area = myRectangle.area( );
perimeter = myRectangle.perimeter( );
239
Sample Output:
class Person {
//instance variables
private String familyName = “I don’t have a name yet”;
private String givenName = “No name here either!”;
private int yearOfBirth;
//method to return the family name
public String getFamilyName( ) {
return familyName;
}
240
Java for Beginners
241
theLecturer.setYearOfBirth(1990);
year = theLecturer.getYearOfBirth();
System.out.println(“The Lecturer’s year of birth is “ + year);
}
}
(i) When we are creating the new object theLecturer from the
class Person, we did not pass any instantiating value into the
invocation.
242
Java for Beginners
//instance variables
private String familyName = “I don’t have a name yet”;
private String givenName = “No name here either!”;
private int yearOfBirth;
The first two fields are initialized while the third is not. But
by default, yearOfBirth being of integer data type will be
automatically set to zero as we mentioned before that all
numeric fields will be set zero by default constructor.
(ii) The class has some other methods, which are used to give
initial values to the class fields. For example,
temp = theLecturer.getFamilyName( );
System.out.println(“The Lecturer’s family name is “ + temp);
theLecturer.setFamilyName(“Akinola”);
243
temp = theLecturer.getFamilyName( );
System.out.println(“The Lecturer’s family name is “ + temp);
Once an object has completed the work for which it was created, it is
garbage-collected and its resources are recycled for use by other
objects. This may be likened to garbage collection with pointers in
C, C++ and Pascal languages.
objectReferenceName.primitiveVariableName
objectReferenceName.objectMemberName.
244
Java for Beginners
‘this’ reference is implicitly used to refer to both the instance
variables and methods of an object. Java uses ‘this’ keyword that
the proper object is referenced when a method of a class references
another member of that class for a specific object of that class. With
this, each object has access to a reference to itself - called the “this
reference”. For example,
class Arith {
private int a, b;
// constructor
public Arith (int a, int b) {
this.a = a;
this.b = b;
}
The ‘this’ keyword also has another meaning. If the first statement
of a constructor has the form this(…), then the constructor calls
another constructor of the same class. For example,
245
name = n,
accountNumber = a;
}
…
…
…
}
E61:
import javax.swing.JOptionPane;
class sales {
// class fields
private int q;
private double p;
// using default constructor
// method to return the Initial pay before discount
public double ip( ) { // ip means initial pay value
return p * q;
}
246
Java for Beginners
public double d( ) {
double disc; // A local variable declared
if (q >= 20)
disc = 10.0/100.0 * ip(); //ip() method called
else if (q>= 10)
disc = 5.0/100.0 * ip( );
else if (q >=6)
disc = 2.0/100.0 * ip( );
else if (q >= 1)
disc = 0.5/100.0 * ip( );
else
disc = 0;
return disc;
} // end method d( )
247
// using a string variable ‘out’ to capture the outputs
String out = "Deatails of your transactions with us \n ";
out += "Quantity bought:" + q + "\nUnit price:"+p + "\n";
out += "Purchase Price Before Discount: " + market.ip();
out += "\nDiscount Given: " + market.d();
out += "\nPurchase Price After Discount: " + market.np();
out += "\n\n\n Thanks for patronizing us, call again";
248
Java for Beginners
//Constructor
public quadratic(float a, float b, float c) {
this.a = a;
this.b = b;
this.c = c;
}
249
return (-b + Math.sqrt(d()));
}
250
Java for Beginners
\nRoot2 %.2f= ", quad.r1() , quad.r2());
System.out.println();
System.exit(0);
}// end method main
} // end class quadratic
Sample outputs
251
8.11 Access Modifiers
These specify where the declared entity can be used. The entity can
be a class, field, constructor, or method.
The following table summarizes the modifiers that can appear in the
declarations of class fields, local variables, constructors and
methods.
252
Java for Beginners
Modifier Class Constructor Field Local Method
Variables
The class Accessible Accessible Accessible
public is from all from all from all class
accessible classes classes --
from all
other class.
It has no
abstract The class Not body and
cannot be Applicable -- -- belong to an
instantiated abstract class
No It must be
final subclasses initialized It must be
be can -- and initialized No subclass
declared cannot be and can override
changed cannot be it.
e.g. changed
final int x
= 2;
It is It is It is
accessible accessible accessible
protected Not only from only from only from
applicable within its within its ___ within its
own class own class own class
and its and its and its
subclasses subclasses subclasses
It is It is It is
Not accessible accessible accessible
private applicable only from only from ___ only from
within its within its within its
own class own class own class
Only one It is bound to
value of the class
the field itself instead
static ___ ___ exist for ___ of an
all instance of
instances that class
of the
class
Its body is
implemented
native ___ ___ __ ___ in another
programming
language
253
8.12 Constructor Overloading
We can have more than one constructor in a class with the same
signature or name. Since all constructors in the same class must have
the same name (viz the name of the class itself), there must be some
other way for the compiler to be able to distinguish them. The only
other way is for them to have distinct parameter list. The rule is that
the sequence of parameter types must be different for each
overloaded constructor or method. The example below illustrates
further.
public Rectangle(Point p) {
origin = p;
}
255
System.out.println(“Y position of rect_two: “ + rect_two.origin.y);
After creating the objects, the program manipulates the objects and
displays some information about them. Here’s the output from the
program:
From the above program, you realize that each constructor let’s you
provide initial values for different aspects of the rectangle: the
origin, width and the height, all three or none. The java platform
differentiates the constructors, based on the number and the type of
arguments. For instance when the java compiler encounters the
following code:
The call initializes the rectangle’s origin variable to the point object
referred to by origin_one. The code also sets width to 100 and height
256
Java for Beginners
to 200. Multiple references can refer to the same object as in this
case of the point object.
X 23
Origin_one
Y 94
Origin
A Point object
Width 23
Height 94
E64.
import javax.swing.*;
class dem {
257
int k =
Integer.parseInt(JOptionPane.showInputDialog
("Enter a number"));
System.out.println("The square of " + k + " = "+ "
" + dem.value(k));
System.exit(0);
}
}
258
Java for Beginners
Tutorial Questions
259
9
Java Packages
9.0 Introduction
When a package is written, its name must be put at the top of our
source file, before the code that defines the classes in the package,
e.g. package corejava;
If we don’t put a package statement in the source file, then java adds
the classes in that source file to what is called the “default package”,
which has no package path.
260
Java for Beginners
9.2 Creating packages
Example:
package com.csc232.pack; //second step
public class sample extends object // first step
private - - -
private - - -
// constructor
public sample() {
-
-
-
}
// Other methods
public string toString ( ) {
-
-
-
}
}
261
}
}
262
Java for Beginners
csc232 and csc232 directory contains pack. In the pack directory, we
can find the sample.class.
Note: The package directory names before part of the class name
when the class is compiled. The class name in this example is
actually com.csc232.pack.sample after the class is compiled.
E65:
package com.example; //second step
import javax.swing.*;
public class pack { // the class must be made public
// private class fields
private float a;
private float b;
// class constructor
public pack (float n1, float n2) {
this.a = n1;
this.b = n2;
}
263
} // end main of tester program
} // end class
E66:
import javax.swing.*;
import com.example.pack;
class sample {
public static void main(String[ ] args) {
float a = Float.parseFloat( JOptionPane.showInputDialog("Enter
the first data"));
float b = Float.parseFloat(JOptionPane.showInputDialog("Enter
the second data"));
//creating a new object mpy of the pack class
pack mpy = new pack(a,b);
float product = mpy.prod();
JOptionPane.showMessageDialog(null, "The product of
the two numbers is" + product +"\n\nBye...");
System.exit(0);
}
264
Java for Beginners
265
Several classes could be packaged together using the same package
name, but with different class names. The needed class name should
however be imported into the program.
For step 4, once the class is compiled and stored in its package, the
class can be imported into programs. We use the ‘import’ keyword.
For example,
import com.example.pack;
specifies that class pack should be imported for use in the program.
266
Java for Beginners
Note:
We can import all classes in a package using the wildcard *; this has
no negative effect on compile time or code size. However, if two
packages each having classes with the same name, then we can’t
import them both.
Tutorial Question
267
10
Introduction to the
Concept of Inheritance
10.0 Introduction
268
Java for Beginners
When creating a new class, instead of writing completely new
instance variables and instance methods, the programmer can
designate that the new class is to inherit the instance variables and
methods of a previously defined “Superclass”. The new class is the
“Subclass”, which can become a superclass for some future
subclass.
269
superclass ‘private’ members only through ‘public’, ‘protected and
package access methods provided in the superclass and inherited into
the subclass.
One problem with inheritance is that a sub class can inherit methods
that it does not need or should not have; but this could be
‘overridden’ (redefined) in the subclass with an appropriate
implementation. However, someday, most software may be
constructed from “standardized reusable components” just as
hardware is often constructed today. This will help meet the
challenges of developing the ever more powerful software we will
need in the future.
Superclass Subclasses
Quadrilateral Rectangle, square, parallelograms,
Rhombus, Trapezium. (For instance a
rectangle is a quadrilateral”).
Shape Circle, Triangle, Rectangle
Student Graduate, Undergraduate
Loan Car loan, mortgage loan, Agric Loan
Staff Academic, Non-academic, Junior,
Senior.
Account Current, Savings, Special.
Example
270
Java for Beginners
be preserved. This means there is an obvious “is-a” relationship
between manager and Employee. Every manager is an employee. ‘is-
a’ is the hallmark of inheritance.
Note: In the class below, we still need to write the Day class before
it could compile and run successfully.
class Employee {
public Employee (String n, double s, Day d) {
name = n;
salary = s;
hireDay = d;
}
// Inheritance code
271
// Add 0.5% bonus for every year of service
Analysis
(i) The keyword “extends” in the statement.
The reason for this line is that every constructor of a subclass must
also invoke a constructor for the data fields of the superclass. If the
subclass constructor does not call a superclass constructor explicitly,
272
Java for Beginners
then the superclass uses its default (no-argument) constructor. If the
superclass has no default constructor and the subclass constructor
does not call another superclass constructor explicitly, then the Java
compiler reports an error.
Note:
(1) The subclass constructor must explicitly use the ‘super’
keyword with the appropriate parameters so as to call the
constructor it wants.
(ii) The Java compiler insists that the call using ‘super’ must be
the first statement in the constructor for the subclass.
(iii) Subclasses can have more instance fields than the parent
class. For instance secretaryName is an instance field n the
subclass initialized to empty in the subclass manager. If not
initialized, it would have been set to Null by default.
(iv) Many of the methods in the Employee (parent) class are not
repeated in the Manager class. The Manager class is free to
use those methods automatically since it inherits from the
employee class. However, we need to note the case
of redefinition of the raiseSalary method, because, as we
said previously, we want this method to work differently for
managers and (ordinary) employees. The need to redefine
methods is one of the main reasons to use inheritance.
(v) Because of the use of ‘super’ in the line
E67:
class Rectangle {
float l;
float b;
//constructor
public Rectangle(float length,float breadth) {
l=length;
b=breadth;
}
274
Java for Beginners
oprism.volume());
Rectangle r = new Rectangle(10,5);
System.out.println("The Area of the Rectangle =
"+r.area());
}
The Output
Tutorial Question
275
11
All along, we have been using the keyboard and monitor to input
data into our programs and output the results of computations
respectively from our programs. We now turn our attention to the
use of files. A file stores data permanently unlike variables and
arrays, which loose data as soon as the programs that use them
terminates. Java programs can read data as input from files kept in
the secondary storage of computers such as harddisk or flash, and
directs output results to another file in the storage.
Data items collected about a particular entity form the fields. For
instance, data items about a student could be name, matric, sex, age,
ume_score, etc. The combination of all these fields forms a record.
Thus, a record is a group of related fields. Each of these fields has a
type associated with it. Name is a string data type, while matric and
ume_score are of type int.
…. …. …. ….
276
Java for Beginners
The combination of all these records forms a file. Thus, a file is a
group of related records.
Java views each file as a sequential stream of bytes. The end of file
marker is usually provided by the Operating System. In some cases,
the end-of-file indication occurs as an exception, and in other cases,
the indication is a return value from a method invoked on a stream-
processing object.
277
Each of these standard stream objects could be redirected to different
location. The System.in enables the program to read from a different
source while System.out and System.err enable output to be sent into
some other locations, such as a file on disk. The SetIn, SetOut and
SetErr methods from the Class System provide these capabilities.
278
Java for Beginners
A FilterInputStream filters an InputStream as
FilterOutputStream filters OutputStream. Filtering in this
case could be buffering, monitoring line numbers or
aggregating data bytes into meaningful primitive type units.
A printStream subclass of FilterOutputStream performs text
output to the specified stream. Systemout and System.err are
PrintStream objects.
Reading data as raw bytes is fast but crude. Usually, programs read
data as aggregates of bytes in form of an int, a float, a double, etc.
Classes DataInputStream and RandomAccessFile from the interface
DataInput provides methods readLine (for byte arrays), readBoolean,
readByte, readChar, readInt, readDouble, readFloat, readFully (for
byte arrays), readLong, readShort, readUnsignedByte,
readUnsignedShort, readUTF (for strings) and SkipBytes for reading
the primitive types. Classes DataOutputStream (a subclass of
FilterOutputStream) and RandomAccessFile each implements the
Interface DataOutput to write primitive type values such as byte or
int. interface DataOutput contins methods such as write (for byte and
byte arrays), writeBoolean, WriteDouble, writeFloat, writeChars (for
Unicode strings), writeLong, writeSjhort, writeUTF, writeBytes, and
writeChar.
279
Classes BufferedReader and BufferedWriter enable efficient
buffering for character-based streams.
Classes CharArrayReader and CharArrayWriter read and
write respectively, a stream of characters to a character
array.
A LineNumberReader is a buffered character stream that
keeps track of line numbers (i.e. a new line, a return or a
carriage-return-line-feed combination).
Class FileReader and FileWriter read characters from and
write characters to a file.
A PrintWriter writes characters to a stream.
StringReader and StrigWriter read and write characters
respectively.
We firstly create an input data file named “data.dat” and saved in the
same folder as our program, i.e. the bin subfolder of the java toolkit.
Each record in the file contains the following fields: Surname,
Othernames, Matric No., and three scores in some courses. Each
field is separated by a space. Figure below shows the screen shot of
the input file.
280
Java for Beginners
The program listing E68 next page shows the program that uses the
input file while the figure below it shows the ouput file created by
the program itself in the same bin folder.
E68:
1. import java.io.*;
2. import java.util.*;
3. import javax.swing.*;
4. // sequential file demo
5. public class seqData {
6. public static void main(String[ ] arguments) {
7. try { // try1
8. Scanner input = new Scanner(new File( "data.dat" ));
9. int count = 0; // for counting records
10. String out = "Results of processing the data \n\n ";
11. out += "Rec. No. \tSurname \tOtherNames \tMatric
12. No.\tScore Total\tMean Score\n\n";
13. // read all the records
14. while(input.hasNext( )) {
15. count++;
16. // Assign all the records’ fields to their identifiers
17. String name1 = input.next( );
18. String name2 = input.next( );
19. int matric = input.nextInt( );
20. int score1 = input.nextInt( );
21. int score2 = input.nextInt( );
22. double score3 = input.nextDouble( );
//summing data
23. double sum = score1 + score2 + score3;
24. double average = sum/3.0; // the mean
25. out += count +"\t\t"+ name1 +"\t\t" + name2 +"\t\t"
26. + matric +"\t\t"+ sum +"\t\t"+ average +"\t\t"
27. + "\n";
28. // writing to an output file
29. try { // try2 to operate output file
30. //Creating the output file
31. File file = new File("OutputFile.txt");
32. PrintWriter output = new PrintWriter(file);
33. output.write(out); // write all the output
281
34. output.close(); //Close the output file
35. }//end try2
36.
37. catch(Exception exception){ //catch for try2
38. JOptionPane.showMessageDialog(null,"Cannot write to
39. file!","Error",JOptionPane.ERROR_MESSAGE);
40. }//end catch for try2
41. }//end while
42. } catch(Exception exception){ //catch for try1
43. JOptionPane.showMessageDialog(null,"Cannot read from
44. file!","Error",JOptionPane.ERROR_MESSAGE);
45. }//end catch for try1
46. //Notifying the user of the end of processing…
47. JOptionPane.showMessageDialog(null,"Data has been
written to file!","Writing Complete",
48. JOptionPane.INFORMATION_MESSAGE);
49. } // end method main()
50.} //end class seqData
282
Java for Beginners
283
This line combines two functions: creating the new file object. We
pass a File object to the constructor, which specifies that the Scanner
object will read from the file "data.dat" located in the directory from
which the application executes (bin). If the file cannot be found, a
FileNotFoundException occurs. The exception is handled in lines 42
and “Cannot read from file” is generated in line 43-44. We could
specify the complete path of the file to specify where it could be
located; but it is advisable to save the file in the bin sub-folder of the
java toolkit to avoid File input error.
Line 17 – 22.
16. // Assign all the records’ fields to their identifiers
17. String name1 = input.next( );
18. String name2 = input.next( );
19. int matric = input.nextInt( );
20. int score1 = input.nextInt( );
21. int score2 = input.nextInt( );
22. double score3 = input.nextDouble( );
284
Java for Beginners
Line 25 – 27:
25. out += count +"\t\t"+ name1 +"\t\t" + name2 +"\t\t"
26. + matric +"\t\t"+ sum +"\t\t"+ average +"\t\t"
27. + "\n";
These lines are used to ‘append’ the results of summation and mean
to the out string, which is going to be printed later.
Lines 29 – 40:
29. try { // try2 to operate output file
30. //Creating the output file
31. File file = new File("OutputFile.txt");
32. PrintWriter output = new PrintWriter(file);
33. output.write(out); // write all the output
34. output.close(); //Close the output file
35. }//end try2
36.
37. catch(Exception exception){ //catch for try2
38. JOptionPane.showMessageDialog(null,"Cannot write to
39. file!","Error",JOptionPane.ERROR_MESSAGE);
40. }//end catch for try2
These lines are for opening and closing the output file. However,
the program will automatically open the output file and gives it the
name we specify as parameter for the File constructor,
"OutputFile.txt". All files opened must be closed, why? Can you
suggest an answer for this? In the program, we did not close the
input file. Can you suggest an appropriate position where the close
should be put?
The catch statements are the necessary error routines that should be
appended to the try statements in case there are errors in reading and
writing to files. Note in particular how these statements are arranged
to match the two try blocks.
285
written to file!","Writing Complete",
48. JOptionPane.INFORMATION_MESSAGE);
These statements inform the user of the program that the data has
been processed.
Method Description
boolean canRead( ) Returns true if a file is readable, false otherwise
Boolean canWrite( ) Returns true if a file is writable, false otherwise
boolean exists( ) Returns true if the name specified as the
argument to the File constructor is a file or
directory in the specified path; false otherwise
boolean isFile( ) Returns true if the name specified as the
argument to the File Constructor is a file, false
otherwise
boolean isDirectory( ) Returns true if the name specified as the
argument to the File Constructor is a directory,
false otherwise
boolean isAbsolute( ) Returns true if the arguments specified to the
File Constructor indicate an absolute path to a
file or directory; false otherwise.
String getAbsolutePath( Returns a string with the absolute path of the
) file or directory.
String getName() Returns a string with the name of the file or
directory
String getPath( ) Returns a string with the path of the file or
directory
Long length( ) Returns the length of the file, in bytes. Returns
0 if the File object is a directory
Long lastModified( ) Returns a platform representation of the time at
which the file or directory was last modified.
String[ ] list( ) Returns an array of strings representing the
contents of a directory. Returns null if the file
object is not a directory.
286
Java for Beginners
Exercises
1. Copy the code line by line into your editor. Compile and run
the code and report your observations. You must have
created the input data file before you execute the program.
The line numbers in the program are not part of the program.
They are there for explanation purpose only.
287
12
JDBC helps you to write java applications that manage these three
programming activities:
1. Connection con =
2. DriverManager.getConnection
3. ( "jdbc:myDriver:wombat",
4. "myLogin","myPassword");
288
Java for Beginners
5. Statement stmt =
6. con.createStatement();
7. ResultSet rs =
8. stmt.executeQuery("SELECT a, b, c FROM
9. Table1");
10. while (rs.next()) {
11. int x = rs.getInt("a");
12. String s = rs.getString("b");
13. float f = rs.getFloat("c");
14. }
The JDBC API is part of the Java platform, which includes the
Java™ Standard Edition (Java™ SE ) and the Java™ Enterprise
Edition (Java™ EE). The JDBC 4.0 API is divided into two
289
packages: java.sql and javax.sql. Both packages are included in the
Java SE and Java EE platforms.
The JDBC driver test suite helps you to determine that JDBC drivers
will run your program. These tests are not comprehensive or
exhaustive, but they do exercise many of the important features in
the JDBC API.
4. JDBC-ODBC Bridge
The Java Software bridge provides JDBC access via ODBC drivers.
Note that you need to load ODBC binary code onto each client
machine that uses this driver. As a result, the ODBC driver is most
appropriate on a corporate network where client installations are not
a major problem, or for application server code written in Java in a
three-tier architecture. A driver is a java interface that includes a
method that is used to obtain database connections.
290
Java for Beginners
o Type 1: Drivers that implement the JDBC API as a mapping to
another data access API, such as ODBC (Open Database
Connectivity). Drivers of this type are generally dependent on a
native library, which limits their portability. The JDBC-ODBC
Bridge driver is an example of a Type 1 driver.
o Type 2: Drivers that are written partly in the Java programming
language and partly in native code. These drivers use a native
client library specific to the data source to which they connect.
Again, because of the native code, their portability is limited.
Oracle's OCI (Oracle Call Interface) client-side driver is an
example of a Type 2 driver.
o Type 3: Drivers that use a pure Java client and communicate
with a middleware server using a database-independent protocol.
The middleware server then communicates the client's requests
to the data source.
o Type 4: Drivers that are pure Java and implement the network
protocol for a specific data source. The client connects directly
to the data source.
Check which driver type comes with your DBMS. Java DB comes
with two Type 4 drivers, an Embedded driver and a Network Client
Driver. MySQL Connector/J is a Type 4 driver.
291
Figure 12.1: Two-tier Architecture for Data Access.
292
Java for Beginners
Until recently, the middle tier has often been written in languages
such as C or C++, which offer fast performance. However, with the
introduction of optimizing compilers that translate Java bytecode
into efficient machine-specific code and technologies such as
Enterprise JavaBeans™, the Java platform is fast becoming the
standard platform for middle-tier development. This is a big plus,
making it possible to take advantage of Java's robustness,
multithreading, and security features.
293
12.2 A Relational Database Overview
Integrity Rules
Relational tables follow certain integrity rules to ensure that the data
they contain stay accurate and are always accessible. First, the rows
in a relational table should all be distinct. If there are duplicate rows,
there can be problems resolving which of two possible selections is
the correct one. For most DBMSs, the user can specify that duplicate
rows are not allowed, and if that is done, the DBMS will prevent the
addition of any rows that duplicate an existing row.
294
Java for Beginners
it would no longer be a complete identifier. This rule is referred to as
entity integrity.
SQL
keyword Description
SELECT Retrieves data from one or more tables.
FROM Tables involved in the query. Required in every
SELECT.
WHERE Criteria for selection that determine the rows to be
retrieved, deleted or updated. Optional in a SQL
query or a SQL statement.
GROUP BY Criteria for grouping rows. Optional in a SELECT
query.
ORDER BY Criteria for ordering rows. Optional in a SELECT
query.
INNER Merge rows from multiple tables.
JOIN
INSERT Insert rows into a specified table.
UPDATE Update rows in a specified table.
DELETE Delete rows from a specified table.
SELECT Statements
SQL is a language designed to be used with relational databases.
There is a set of basic SQL commands that is considered standard
and is used by all RDBMSs. For example, all RDBMSs use the
SELECT statement.
296
Java for Beginners
RDBMS returns rows of the column entries that satisfy the stated
requirements. A SELECT statement such as the following will fetch
the first and last names of employees who have company cars:
The result set (the set of rows that satisfy the requirement of not
having null in the Matric_Number column) follows. The first name
and last name are printed for each row that satisfies the requirement
because the SELECT statement (the first line) specifies the columns
First_Name and Last_Name. The FROM clause (the second line)
gives the table from which the columns will be selected.
First_name Last_Name
Akinola Solomon
Abel John
Hammed F.
John Solomon
The following code produces a result set that includes the whole
table because it asks for all of the columns in the table Employees
with no restrictions (no WHERE clause). Note that SELECT *
means "SELECT all columns."
SELECT *
FROM Students
WHERE Clauses
297
FROM Students
WHERE Last_Name LIKE Jo%'
The code fragment below has a WHERE clause that uses the equal
sign (=) to compare numbers. It selects the first and last name of the
student who is assigned car 12.
The next code fragment selects the first and last names of students
whose Matric_number is greater than 10005:
298
Java for Beginners
and last names of students whose Matric_number is less than 10100
and who do not have a car.
Joins
The following code asks for the first and last names of Students who
have cars and for the make, model, and year of those cars. Note that
the FROM clause lists both Students and Cars because the requested
data is contained in both tables. Using the table name and a dot (.)
before the column name indicates which table contains the column.
This returns a result set that will look similar to the following:
SQL commands are divided into categories, the two main ones being
Data Manipulation Language (DML) commands and Data Definition
Language (DDL) commands. DML commands deal with data, either
retrieving it or modifying it to keep it up-to-date. DDL commands
create or change tables and other database objects such as views and
indexes.
300
Java for Beginners
to include in the result set. The vast majority of the SQL
commands used in applications are SELECT statements.
INSERT — adds new rows to a table. INSERT is used to
populate a newly created table or to add a new row (or rows)
to an already-existing table.
DELETE — removes a specified row or set of rows from a
table
UPDATE — changes an existing value in a column or
group of columns in a table
301
Result Sets and Cursors
The rows that satisfy the conditions of a query are called the result
set. The number of rows returned in a result set can be zero, one, or
many. A user can access the data in a result set one row at a time,
and a cursor provides the means to do that. A cursor can be thought
of as a pointer into a file that contains the rows of the result set, and
that pointer has the ability to keep track of which row is currently
being accessed. A cursor allows a user to process each row of a
result set from top to bottom and consequently may be used for
iterative processing. Most DBMSs create a cursor automatically
when a result set is generated.
Earlier JDBC API versions added new capabilities for a result set's
cursor, allowing it to move both forward and backward and also
allowing it to move to a specified row or to a row whose position is
relative to another row.
Transactions
302
Java for Beginners
A lock is a mechanism that prohibits two transactions from
manipulating the same data at the same time. For example, a table
lock prevents a table from being dropped if there is an uncommitted
transaction on that table. In some DBMSs, a table lock also locks all
of the rows in a table. A row lock prevents two transactions from
modifying the same row, or it prevents one transaction from
selecting a row while another transaction is still modifying it.
Stored Procedures
import java.sql.*;
public class UpdateCar {
public static void UpdateCarNum(int carNo, int empNo)
throws SQLException {
Connection con = null;
PreparedStatement pstmt = null;
try {
303
con = DriverManager.getConnection(
"jdbc:default:connection");
Metadata
Databases store user data, and they also store information about the
database itself. Most DBMSs have a set of system tables, which list
tables in the database, column names in each table, primary keys,
foreign keys, stored procedures, and so forth. Each DBMS has its
own functions for getting information about table layouts and
database features. JDBC provides the interface DatabaseMetaData,
which a driver writer must implement so that its methods return
information about the driver and/or DBMS for which the driver is
written. For example, a large number of methods return whether or
not the driver supports a particular functionality. This interface gives
users and tools a standardized way to get metadata. In general,
developers writing tools and drivers are the ones most likely to be
concerned with metadata.
304
Java for Beginners
Example Code 1: Retrieving Data from a Database Table
Save the database name as Stud in the BIN subfolder of the Java
toolkit.
The first task in a JDBC program is to load the driver (or drivers)
that will be used to connect to a data source. A driver is loaded with
the class.forName(String) method. Class, part of the java.lang
package, can be used to load classes into the Java interpreter. The
forName(String) method loads the class named by the
305
specified string. A ClassNotFoundException can be thrown by
this method.
Class.forName(“sun.jdbc.odbc.jdbcOdbcDriver”);
After this driver has been loaded, you can establish a connection to
the data source by using the DriverManager class in the java.sql
package.
The last two items are needed only if the data source is secured with
a username and a password. If not, these arguments can be null
strings (“”). The name of the data source is preceded by the text
jdbc:odbc: when using the JDBC-ODBC bridge, which indicates the
type of database connectivity in use.
306
Java for Beginners
After a connection is made, one can reuse it each time he wants to
retrieve or store information from that connection’s data source.
Statement st = con.createStatement();
Note that the String argument should be an SQL query that follows
the syntax of that language.
The above query retrieves all the fields in the Table Student from the
Stud database and the records are sorted according to the Gendar
field because of the ORDER BY clause in the query. So all the
females would come before the males in the query result. You need
to acquaint yourself with SQL queries before you can effectively use
them in your program.
307
When a ResultSet is returned from executeQuery( ), it is positioned
at the first record that has been retrieved. The following methods of
ResultSet can be used to pull information from the current record:
getDate(String) – Returns the Date value stored in the
specified field name (Using the Date class in the java.sql
package, not java.util.Date).
getDouble(String) – Returns the double value stored in the
specified field name.
getFloat(String) – Returns the float value stored in the
specified field name.
getInt(String) – Returns the int value stored in the specified
field name.
getLong(String) – Returns the long value stored in the
specified field name.
getString(String) - Returns the string value stored in the
specified field name.
308
Java for Beginners
When we are finished using a connection to a data source, we close
it by calling the connection’s close( ) method with no arguments.
An example program to illustrate all the above features is shown
below.
Student
Matno Surname FirstName MiddleName Age Gender
100 Chukwu Ann Mary 23 F
104 Michael Janet Tommy 21 F
123 Akinola Olalekan Solomon 20 M
345 John Josephine Eunice 23 F
456 Samson Jonathan Azikwe 50 M
789 Usman Momodu Karim 30 M
1. import java.sql.*;
2. public class database {
3. public static void main(String[ ] args) {
4. try {
5. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
6. Connection con = DriverManager.getConnection
7. ("jdbc:odbc:Studs","","");
8. Statement st = con.createStatement();
9. ResultSet rs = st.executeQuery("SELECT * " + "FROM Student
10. " + "WHERE Matno < 400 " + “ORDER BY Gendar”);
11. System.out.println("Matno \tSurname \tFirst Name \tMiddle
12. Name \tAge \tGendar\n");
13. while (rs.next( )) {
14. System.out.println(rs.getInt(1) + "\t" + rs.getString(2) +
15. "\t\t" + rs.getString(3) + "\t" + rs.getString(4) + "\t\t" +
16. rs.getInt(5) + "\t" + rs.getString(6));
17. } // end while
309
18. st.close( );
19. } catch (SQLException s) {
20. System.out.println("SQL error: " + s.toString() + s.getErrorCode( ) +
21. " " + s.getSQLState( ));
22. } catch (Exception e) {
23. System.out.println("Error: " + e.toString() + e.getMessage( ));
24. }
25. }
26. }
‘
Practical Exercise
Copy the above code into an editor, modify the code such that the
output is directed to a file, compile and finally execute with a
Microsoft Access Database set up initially.
12.3 ResultSet
310
Java for Beginners
Update Sensitivity
311
known as “changes by others” to distinguish them from changes
made to the data using an updatable ResultSet’s updateXXX()
methods.
If you call a getXXX() method to read data from the current row, a
sensitive ResultSet will return the data stored in the underlying
database even if the data was changed by another user after the
ResultSet was created. However, an insensitive ResultSet doesn’t
detect such changes and may return outdated information.
312
Java for Beginners
TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, or
TYPE_SCROLL_SENSITIVE.
12.4 PreparedStatement
313
stmt.executeUpdate(
"UPDATE MYTABLE SET FNAME = 'Jordan' WHERE CUSTID =
456");
stmt.executeUpdate(
"UPDATE MYTABLE SET FNAME = 'Jeffery' WHERE CUSTID =
789");
314
Java for Beginners
This approach is much more efficient because the statement is
compiled only once, but it’s executed several times. Note that the
substitution field index values are one-based instead of zero-based,
meaning that the first question mark corresponds to field 1, the
second to field 2, and so on.
The example program below add more data into the Student table:
1. import java.sql.*;
2. import java.util.*;
3. class database2 {
4. public static void main(String[ ] args) {
5. Scanner input = new Scanner(System.in);
6. try {
7. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
8. Connection con = DriverManager.getConnection
9. ("jdbc:odbc:Studs","","");
10.
11. PreparedStatement st = con.prepareStatement("INSERT INTO " +
12. "Student(Matno, Surname, FirstName, MiddleName, Age,
13. Gendar )" + "VALUES(?, ?, ?, ?, ?, ?)");
14. L1: //Label for a case when data is not correct
15. while (true) { // to continuously add records
16.
17. System.out.println("Enter the new matric number (e.g. 234: " );
18. String a = input.next( );
19. st.setString(1, a);
20.
21. System.out.println("Enter the new Surname: " );
22. String b = input.next( );
23. st.setString(2, b);
24.
25. System.out.println("Enter the new First name: " );
26. String c = input.next( );
315
27. st.setString(3, c);
28.
29. System.out.println("Enter the new Middle name: " );
30. String d = input.next( );
31. st.setString(4, d);
32.
33. System.out.println("Enter the new Age: " );
34. String e = input.next( );
35. st.setString(5, e);
36.
37. System.out.println("Enter the new Gendar: " );
38. String f = input.next();
39. st.setString(6, f);
40
41. // Check if there is no error in the data captured
42. System.out.println(“No Mistakes, add records to the
43. databse (Y/N)?”);
44. String reply1 = input.next( );
45. if (reply1.equalsIgnoreCase(“n”))
46. break L1; //Move to label L1 if no problem
47.
48. //update the database table
49.
50. st.executeUpdate( );
51.
52. System.out.println("Add more records (Y/N)?");
53. String reply = input.next( );
54. if (reply.equalsIgnoreCase("n"))
55. break; // go out of loop to close database
56. } // loop for more record update
57. con.close( ); // close database connection
58. } catch (SQLException s) {
59. System.out.println("SQL error: " + s.toString( ) +
60. s.getErrorCode( ) + " " + s.getSQLState( ));
61. } catch (ClassNotFoundException cnfe) {
62. System.out.println("Error: " + cnfe.getMessage( ));
63. }
64. } // end method main
65. } // end class database2
316
Java for Beginners
Student
Matno Surname FirstName MiddleName Age Gendar
1 Bamgbade Joseph Adeolu 41 M
2 Mohammed Abdulkareem Sheu 27 M
4 Ado Bayero Audu 67 M
56 Ajala Olaoluwa Omooluwa 45 m
317
Student
Matno Surname FirstName MiddleName Age Gendar
100 Chukwu Ann Mary 23 F
104 Michael Janet Tommy 21 F
106 Balogun Adeolu Ibukun 21 M
111 Augustine Nnena Abigael 34 F
123 Akinola Olalekan Solomon 20 M
124 Michael Sandra mary 24 F
333 Amodu Usman Muhammed 25 M
345 John Josephine Eunice 23 F
456 Samson Jonathan Azikwe 50 M
675 Kazeem Bright James 54 M
789 Usman Momodu Karim 30 M
318
Java for Beginners
It is easier to send Microsoft Access strings and let the database
program converts them automatically into the correct format as in
Matno and Age which are integer data in the database, but string are
used for them in the program above (Lines 17 – 19 and 33 – 35 ).
After the prepared statement has been prepared and all the
placeholders are filled, the statement’s executeUpdate( ) method is
called (Line 50). This either adds the quote data to the database or
throws an SQL error.
50. st.executeUpdate( );
The while (true) loop assists the user of the program to add more
records into the database at a go. Note lines 41 – 46, the lines check
the data to be inserted into the database for correctness.
If the user has made a mistake in entering one of the data, the entire
record will not be inserted into the database. This however could be
painful especially if a large data entry is involved. How can you
validate the data as they are being entered so that not all the data will
be discarded at once?
319
After a successful insertion of a record or not, the program still asks
the user if he wants to insert more records. This is achived in Lines
52 – 56. if the reply is yes, the user is asked to enter his new record
fields.
The default behaviour of resultsets permits one trip through the set
using its next( ) method to retrieve each record. By changing how
statements and prepared statements are created, one can produce
resultsets that support these additional methods:
These actions are possible when the resultset’s policies have been
specified as arguments to a database connection’s createStatement( )
and prepareStatement( ) methods.
Statement st = con.CreateStatement (
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY,
320
Java for Beginners
ResultSet.CLOSE_CURSORS_AT_COMMIT);
Sometimes you need to use two or more tables to get the data you
want. A join is a database operation that relates two or more tables
by means of values that they share in common. In our example
database, the tables STUDENT and STUDENT_COUSE both have the
column Matno, which can be used to join them.
You need some way to distinguish to which Matno column you are
referring. This is done by preceding the column name with the table
name, as in "Student.Matno" to indicate that you mean the
column Matno in the table Student. The example program below
illustrates the concept of Join. Learn more of SQL in a database
textbook in order to get the logic of joins in databases.
import java.sql.*;
public class database3 {
public static void main(String[ ] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection
("jdbc:odbc:Studs","","");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT
Student_Course.Matno, Student_Course.CosCode,
Session, Score " + "FROM Student, Course, Student_Course
" + "WHERE Student.Matno = Student_Course.matno
and Course.CosCode = Student_Course.CosCode");
System.out.println("Matno \tCourse Code \t Session \tScore\n");
321
while (rs.next( )) {
System.out.println(rs.getInt(1) + "\t" + rs.getString(2) + "\t\t"
+ rs.getString(3) + "\t\t" + rs.getString(4) );
} // end while
st.close();
} catch (SQLException s) {
System.out.println("SQL error: " + s.toString( ) +
s.getErrorCode( ) + " " + s.getSQLState( ));
} catch (Exception e) {
System.out.println("Error: " + e.toString( ) +
e.getMessage( ));
}
}
}
322
Java for Beginners
E72: Searching for a record
1. import java.sql.*;
2. import java.util.*;
3. public class database4 {
4. public static void main(String[ ] args) {
5. // searching for a record
6. Scanner input = new Scanner(System.in);
7. boolean found = true;
8. try {
9. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
10. Connection con = DriverManager.getConnection
11. ("jdbc:odbc:Studs","","");
12. L1: while (true){
13. System.out.println("Enter the Student's matric number: ");
14. String mat = input.next( ); // get matric no of the student
15.
16. // prepare the query statement
17 PreparedStatement st = con.prepareStatement("SELECT
18. * " + "FROM Student " + "WHERE Matno = ? ");
19.
20. // Set the place holder ? with a value
21. st.setString(1, mat);
22.
23. // Execute the query
24. ResultSet rs = st.executeQuery();
25.
26. boolean g = rs.next( ); // Set next record pointer to g
27. while (true) {
28. if (g != false) {
29.
30. System.out.println("\nMatno \tSurname \t Age
31. \tGendar\n"); // Heading Titles
32.
33. // Printing record found
34. System.out.println(rs.getString("Matno") + "\t"
35. + rs.getString("Surname") + "\t\t" + rs.get
36. String("Age") + "\t" + rs.getString("Gendar") );
37.
38. break L1;
39.
40. } else {
323
41. System.out.println("The record you search for is
42. not found \nDo you want to try again (Y/N)?");
43. String reply = input.next();
44. if (reply.equalsIgnoreCase("y"))
45. continue L1;
46. else
47. System.exit(0);
48. System.out.println("Good Bye");
49. }// end outer else
50. st.close( );
51. }// end inner while
52.
53. } // end L1 while
54.
55. } catch (SQLException s) {
56. System.out.println("SQL error: " + s.toString( ) +
57. s.getErrorCode() + " " + s.getSQLState( ));
58. } catch (Exception e) {
59. System.out.println("Error: " + e.toString() + e.getMessage( ));
60. }
61. System.out.println( );
62. } // End method main
63. } // End class database4
Sample Outputs:
324
Java for Beginners
325
matric number. This is achieved with lines Lines 44 – 45 with the
use of continue with label statement.
44. if (reply.equalsIgnoreCase("y"))
45. continue L1;
Tutorial Question
326
Java for Beginners
13
327
Make sure you specify the class name -not the class file
name - to the interpreter.
Unset the CLASSPATH environment variable, if it's set.
If your classes are in packages, make sure that they appear
in the correct subdirectory as outlined in Managing Source
and Class Files.
Make sure you're invoking the interpreter from the directory
in which the .class file is located.
Did you forget to use break after each case statement in a switch
statement?
Did you use the assignment operator = when you really wanted
to use the comparison operator ==?
Are the termination conditions on your loops correct? Make sure
you're not terminating loops one iteration too early or too late.
That is, make sure you are using < or <= and > or >= as
appropriate for your situation.
328
Java for Beginners
Are you having trouble with encapsulation, inheritance, or other
object-oriented programming and design concepts? Review the
information in Object-Oriented Programming Concepts in
Chapter 1.
Are you using the correct conditional operator? Make sure you
understand && and || and are using them appropriately.
329
13.2 Managing Source and Class Files
You put the source code for a class or an interface in a text file
whose name is the simple name of the class or the interface and
whose extension is .java. Then you put the source file in a directory
whose name reflects the name of the package to which the class or
the interface belongs. For example, the source code for the
Rectangle class would be in a file named Rectangle.java, and the file
would be in a directory named graphics. The graphics directory
might be anywhere on the file system. The figure below shows how
this works.
The qualified name of the package member and the path name to the
file are parallel, assuming the UNIX file name separator slash (/):
330
Java for Beginners
package that contained a Rectangle.java source file, it would be
contained in a series of subdirectories, as shown below.
331
By doing this, you can give the classes directory to other
programmers without revealing your sources.
Why all the bother about directories and file names? You need to
manage your source and class files in this manner so that the
compiler and the interpreter can find all the classes and interfaces
your program uses. When the compiler encounters a new class as its
compiling your program, it must be able to find the class so as to
resolve names, do type checking, and so on. Similarly, when the
interpreter encounters a new class as its running your program, it
must be able to find the class to invoke its methods, and so on. Both
the compiler and the interpreter search for classes in each directory
or ZIP file listed in your class path.
332
Java for Beginners
By default, the compiler and the interpreter search the current
directory and the ZIP file containing the Java platform class files. In
other words, the current directory and the Java platform class files
are automatically in your class path. Most, if not all, classes can be
found in these two locations. So it’s likely that you don't have to
worry about your class path. In some cases, however, you might
have to set your class path.
333
LABORATORY PRACTICALS
INSTRUCTIONS:
(i) On finishing with your programs, copy the codes and
screen shots and paste them in Microsoft Word, one
question at a time, then save the Word file as your
Matriculation Number. The Word file should be saved
on the desktop of your computer.
(ii) Your name, Matriculation number and other information
must form the initial documentations at the top of your
programs.
* * * * *
*
* * *
* * * *
Task
Your task is to assist John in implementing a program that
will accomplish the following objectives with his “worst
array structure”:
334
Java for Beginners
(i) Create and populate data into the ragged array. The
data must be integer numeric. Do not use initialized
array. The array must by dynamic.
(ii) Compute the average data in the array
(iii) Compute the total number of data entered into the
array
(iv) Print out the array in the ragged way it is.
(v) Zero out all the elements in the first and last rows of
the array
(v) To send the original string data from its source, the
encrypted substrings A and B are concatenated with A
coming after B.
335
(vi) At the receiving end, Steps (ii) and (iii) are repeated on the
sent encrypted string, in order to decrypt it. All the
encoding numbers in Step (iv) are converted to their
respective characters in the received string.
Task
(i) Implement a java class named Encrypt for the Akinola’s
encrypting algorithm.
(ii) Methods to be included in your class should be the
following, however, you are free to add more relevant
methods:
Method to return the encrypted string to
be sent on the network;
Method to return the decrypted string at
the final destination.
(iii) Implement a tester program for the class.
336
Java for Beginners
(iv) The maximum and minimum score in the
examination and the data of the students in these
categories;
(v) Data and total number of students that fail the test;
(vi) Data and total number of students in the marginal
score levels (between 48 and 49 inclusive) for
possible consideration in the second batch; and
(vii) Data and total number of students in the following
score categories:
A. 0 – 20
B. 21 – 40
C. 41 – 49
D. 50 – 80
Task
(i) Create a database named “data.dbf” in the bin sub-folder
of your java toolkit. The structure of the records in the
database table should follow the following sample
S/N Exam No. Name Sex Score
1 09/01 Akinola S. O. M 54
2 09/02 Dennis Kay M 78
3 09/59 Mohammed Ayisat F 48
…. …. … ….
Q4. Akinola Nig. Ltd has just employed you to computerize her
Salaries Section. Your analysis of the company shows that
every staff is given a monthly basic salary commensurate
with his/her job description. In addition, the following
allowances are given to the staff:
337
(i) 10% of Basic Salary as Housing Allowance.
(ii) 7½ % of Basic Salary as Transport Allowance.
(iii) If the grade level of a staff is above GL/07, the staff
is entitled to Entertainment Allowance of 2% of
his/her Basic Salary.
(iv) A staff that has spent up to 10 years in the company
is also given a 1.5% of his/her Basic Salary as “long
Serving Allowance”.
(v) Every staff is entitled to N500 Meal Subsidy
Allowance per month.
Task
(i) Set up database table having the following record
structure:
338
Java for Beginners
List of References
339
Index
Abstract
Abstraction
Access modifiers
Action
Algorithm
Analysis
AND
API
Applets
Appletviewer
Argument
Arrays
Art
Assembly language
Assignment
Bitwise
Blocks
Boolean
Bottom up approach
Break
Bufferedreader
Call
Casts
Char
Classes
Comments
Compareto
Compile
Compile-time errors
Concatenation
Conditional
Constructor
Continue
Control
Create
Criteria
Cycle
Database
Dates
340
Java for Beginners
Delete
Design
Dimensional
Do loop
Double
Dynamic binding
Elements
Else
Else
Encapsulation
Endswith
Equals
Error
Escape
Even
Exception
Exclusive
Exit
Expressions
Extends
Factorial
Fibonacci
Field
Final
Flags
Float
Flowcharts
For loop
Formatter
Formatting
Global
Good
Graphics
Hash Code
High level languages
HTML
If
IgnoreCase
Import
Index
Information hiding
341
Inheritance
Input
Inputstreamreader
Insert
Instanceof’
Integer
Interfaces
Iteration
Java
JDBC
Joins
JOptionPane
JTextArea
Languages
Last
Length
Life
Literals
Logic
Logical
Long
Loosely typed languages
Low level
Machine language
Math
Matrix
Message
Message passing
Metadata
Method
Multi-threaded
Nested
New
Null
Object
Odbc
Odd
Operator
Or operator
Output
Overloading
342
Java for Beginners
Package
Palindrome
Parameters
Parseint
Pascal
Plain
Platform independent
Point
Polymorphism
Precedence
Precision
Preparedstatement
Prime
Primitive
Prin
Printf
Println
Procedure oriented programming
Process
Program design
Programming
Programming environment
Programming style
Programs
Public
Quadratic
Random
Readline
Recursion
Relational
Resultset
Return
Reusability
Reversing
Run - time errors
Scanner
Science
Scope
Select
Semantic
Shift
343
ShowInputDialog
ShowMessageDialog
Sort
Split
SQL
StartsWith
Statements
Static
Stored procedures
String
Stringbuffer
Strongly typed languages
Structured programming
Substrings
Sun
Swing
Switch
Syntax
System
Ternary
This
Time
Tokenizer
Toolkit
Top down approach
Transactions
Trimming
Tutorial
Update
Util
Variable
Vectors
Weakly typed languages
While
Window
344
Java for Beginners
The Book
Java for Beginners is a book that covers the foundations of object-
oriented programming principles. It is written in a lively, easily
understood style with over seventy implemented examples to
facilitate the understanding of all the concepts of Object Oriented
Programming with Java. File and database (JDBC) handling were
not left out in the book.
The Author
‘Lekan Akinola is a lecturer of Computer
Science at the Nigeria’s premier university
- University of Ibadan, Ibadan, Nigeria. He
has been teaching Computer programming
for more than 10 years both at
undergraduate and postgraduate levels. He
has Final Diploma (HND) in
Physics/Electronics, B.Sc. Degree in
Computer Science, Master Degree in
Information Science and PhD Degree in
Computer Science, all from the University
of Ibadan, Nigeria. The author is reachable on +234-805-6666-117
and solom202@yahoo.co.uk.
345