100% found this document useful (1 vote)
306 views

Akinola Java Book

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
306 views

Akinola Java Book

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 345

Java Companion for Beginners

 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

Solomon Olalekan Akinola


Java Companion
for
Beginners
First Edition

Solomon Olalekan Akinola (PhD)


Lecturer,
Department of Computer Science
University of Ibadan
Ibadan, Nigeria

2
Java for Beginners

Copyright ©

Published by
First Edition:

All rights reserved.

No part of this book may be reproduced in any form, by Photostat,


microfilm, xerography, or any other means or incorporated into any
information retrieval system, electronic or mechanical, without the
written permission of the copyright owner.

ISBN

3
Preface

This book is a product of ten years teaching experience of Computer


Programming Techniques by the author at various Universities in
Nigeria at undergraduate and postgraduate levels. The book actually
took ten years of manuscript preparations. Every year, additions
were made as students suggested and as newer topics were taught,
coupled with local examples.

The first chapter of the book covers the basic principles of


programming, ranging from the meaning of programming to
program design principles. The concept of Object Oriented
Programming (OOP) is discussed in the chapter.

Chapter Two introduces the reader to java programming while


Chapter Three discusses the control structures being supported by
Java language. Arrays and vectors are the topics covered in Chapter
Four. In Chapter Five, how Java handles subprograms (methods) are
discussed. Strings manipulations in Java are covered in Chapter Six
while Applets are explained in Chapter Seven. Chapters Eight, Nine
and Ten are dedicated to the basic concepts of object-based
programming such as classes and objects, packages and inheritance.
Chapter Eleven is specially devoted to sequential file handling in
Java, while in Chapter Twelve, Java database connectivity (JDBC) is
treated.

Finally, solving common coding problems in Java is explained in


Chapter Thirteen.

All the programs cited in this book were all implemented by the
author and the codes are available on demand.

The author welcomes suggestions, criticisms and corrections on this


book.
Akinola. S. Olalekan (PhD)
Solom202@yahoo.co.uk
+2348056666117

4
Java for Beginners
Acknowledgements

I would like to acknowledge the contributions of all my students


from the University of Ibadan, Lead City University, Ibadan,
Achievers University, Owo and National Open University (NOUN),
Ibadan centre both at undergraduate and postgraduate levels for their
positive contributions to the publication of this book. Your
suggestions, corrections and additions to the previous manuals of
this book over the period of 2001 to 2011 have highly contributed to
the success of this book.

The mentoring of my able Professor and Head of Department of


Computer Science, University of Ibadan (Prof. Adenike Oyinlola
Osofisan) is highly appreciated.

I would like to put on record, the special contributions of Messer’s.


Afolabi Victor, Adekunle Olusola and Samuel Akinyele, my former
students at the University of Ibadan, Ibadan. Your contributions are
specially appreciated.

I thank all the staff of my department at the University of Ibadan,


Nigeria most especially my colleagues in academics for your
comments and critics of the book while in the making.

My final sincere appreciation goes to my wife – Kemi and my


children – Esther, Marvellous, Eunice and Christianah for their
patience and continuing supports to make this task complete with
pleasure.

5
Dedication

With love and deep sense of appreciation, this work is dedicated to


the Almighty God

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 …………………………………………………

1: Fundamental of Principles of programming


1.0 Introduction ……………………………………………
1.1 What is Programming? ……………………………….
1.2 Is Programming an Art or a Science or Both? ……….
1.4 Steps of Programming ………………………………..
1.5 Good Programming Style …………………………….
1.6 Errors in Programming ……………………………….
1.7 Programming languages ………………………………
1.8 Categories of Programming Languages ………………
1.9 Structured Programming Paradigm ………………….
1.9.1 Approaches to Structured Program Design ………..
1.10 Criteria for Judging a Program ………………………
1.11 A Look At Procedure-Oriented Programming ……..
1.12 Object-Oriented Programming Paradigm …………..
1.13 Basic Concepts of Object-Oriented Programming ….
1.14 Benefits of Oop ……………………………………..

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 ……………………………..

3: Control Flow Statements


3.0 Introduction ……………………………………………
3.1 The if/else Statements …………………………………
3.2 The switch Statement ………………………………….
3.3 The for Statement ……………………………………..
3.4 The while and do-while Statements ……………………
3.5 Exception Handling Statements ……………………….
3.6 Handling Errors with Exceptions ………………………
3.7 What’s an Exception and Why Do I Care? …………….
3.8 Your First Encounter with Java Exceptions ……………
3.9 Throwing Exceptions …………………………………..
3.10 Runtime Exceptions – The Controversy ……………….
3.11 Branching Statements …………………………………..
3.12 The return Statement…………………………………….

4: Java Arrays and Vectors


4.0 Introduction …………………………………………….
4.1 Types of Arrays …………………………………………
4.2 Creating a One-dimensional Array ……………………..
4.3 Reading in Data into a One-dimensional Array …………
4.4 Summing all the Data in a One-dimensional Array ……..
4.5 Reversing the elements of an array ………………………
4.6 Character Arrays ………………………………………..
4.7 Two-dimensional Arrays ……………………………….
4.8 Sorting an Array ……………………………………….
4.9 Java Vectors ……………………………………………

5: Java Methods (Subprograms)


5.0 Introduction …………………………………………….
5.1 Advantages of Using Methods in Programs ……………
5.2 The Math-Class Methods ………………………………
5.3 Writing Your Own Methods …………………………..
5.3.1 Where Can We Place Our Methods? ………..
5.3.2 Passing Arrays into Methods ……………….
5.4 Random Number Generation …………………………

8
Java for Beginners
5.5 Void Methods ………………………………………..
5.6 Recursive Methods ………………………………….

6: Strings Manipulation In Java


6.0 Introduction ………………………………………….
6.1 The String Class …………………………………….
6.2 Operations on Strings ………………………………

7: Introduction to Java Applets


7.0 Introduction …………………………………………
7.1 Creating an Applet …………………………………
7.2 To Compile and Execute the Applet……………….
7.3 Applet Resources on the Web ……………………..

8: Introduction to Object-Based Programming


8.0 Introduction ……………………………………….
8.1 Java Classes ………………………………………
8.2 Relationships between classes: …………………..
8.3 Building Your Own Classes ……………………..
8.4 Properties of Constructors ……………………….
8.5 Caution about Constructor ……………………….
8.6 The methods of the Account Class ………………
8.7 Using the Class …………………………………..
8.8 Classes without Explicit Constructor …………….
8.9 The Life Cycle of an Object …………………….
8.10 The Scope of a Class …………………………….
8.11 Access Modifiers …………………………………
8.12 Constructor Overloading ………………………..
8.13 Writing Classes without Constructors and private fields

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? …………………………………

11: Java File Handling


11.0 Introduction ………………………………………….
11.1 Java Perception of Files ……………………………..
11.2 Processing Sequential Access Data File …………….

12: Introduction to Java Database Connectivity (JDBC)


12.0 Introduction ………………………………………….
12.1 The Basics ……………………………………………
12.2 A Relational Database Overview ………………….
12.3 ResultSet …………………………………………….
12.4 PreparedStatement …………………………………
12.5 Moving Through Resultsets …………………………
12.6 Dealing With Multiple Tables (Joins) ………………..
12.7 Database Search ……………………………………….

13: Solving Common Coding Problems


13.0 Introduction ………………………………………..
13.1 The Problems ………………………………………
13.2 Managing Source and Class Files ………………….

Laboratory Practicals ………………………………

References …………………………………………….

Index……………………………………………………

10
Java for Beginners

1
Fundamental Principles
of Programming
1.0 Introduction

In this chapter, the basic principles of programming shall be


discussed. We start by defining the word ‘programming’ and then
the various tools needed for writing programs are discussed. Steps of
programming as well as programming tools were also discussed.
Good programming styles were not left out in this chapter. Features
of procedure - and object - oriented programming paradigms are
discussed at the end of this chapter. At the end of this chapter, you
should be able to:
1. explain the meaning of programming;
2. distinguish between a computer programmer and computer
operator;
3. design an algorithm to solve some common scientific
problems; and
4. understand the paradigms of procedure - and object –
oriented programming techniques.

1.1 What is Programming?

Before we define the term programming, let us firstly define the


term program. A program is a set or sequence of instructions written
and compiled in a specific programming language given to a
computer to perform a specific task. Therefore programming is the
art and science of creating (developing) computer programs. A
software is made up of several independent programs working

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.

1.3 Is Programming an Art or a Science or Both?

Programming is on the one hand an artistic or creative endeavour,


and on the other hand, a scientific endeavour.

As a scientist, the programmer begins with a clearly defined set of


principles, or axioms of programming. He or she then applies them
systematically to a problem, in such a way that at any stage in the
process the (mathematical) correctness of the program can be
routinely demonstrated.

As an artist, the programmer begins with an understanding of the


medium or application area. The art of programming seems therefore
to be the development of creative solutions to problems, so that the
overall quality of activity within that application area will be
enhanced.

These two philosophies of programming have some implications.


The art of programming demands a variety of “tools” or a
“programming environment” within which the total process of
program development can take place. The science philosophy
demands a language, which supports the axiomatic proof of program
behaviour. Nevertheless, good programming must necessarily
combine both an artistic spirit and a methodology based on scientific
principles.

1.3 Programming Environment

The programming environment includes all the facilities and tools,


which a programmer requires in the design, development, testing,
implementation and maintenance of a system of programs. Thus,
text editors, compilers, interpreters, diagnostic tools, optimizers,

12
Java for Beginners
measurement tools and other aids comprise a complete programming
environment.

Apart from the tools mentioned as comprising the programming


environment, the following are additional tools needed in programming:
1. A previous knowledge of the pros and cons of programming
languages syntax and semantics;
2. Logical reasoning ability; and
3. Algorithms and flow charts.
For a programmer to be successful, he must have a good reasoning ability
and previous knowledge of any suitable language that must be used in
solving a problem; because any problem that cannot be used by human,
computer too cannot solve it. The common maxim in programming is
“garbage in garbage out”.

 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:

1. Oval Shape for start or stop Start


2. Parallelogram for Input and output
Read Data

3. Rectangle for process I = I + 1

4. Diamond shape for Decision taking

I < = 10 Yes

No

5. Arrow for Flow or direction

13
6. Small Circle for connecting two parts of the flowchart
together
A

Even though the flowcharts are no more recommended as part of


programming tools nowadays, it is still a starting point for new
programmers. We shall see the usage of flowchart very soon.

 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.

As an illustration, suppose we want to add some numbers together


continuously until when we encounter any negative data, which shall
terminate the addition. In addition, we also want to report the total
number of valid data added so far before the program halts.

The algorithm:

1. Set up a counter, count = 0


2. Initialize an accumulator, sum = 0
3. Read in data, d
4. If (d  0) then
Sum = sum + d
Count = count + 1
Goto 3

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

In order to develop a good program, the following steps are to be


followed:

Step 1. Analysis and understanding of the problem to be


solved. This involves the following subtasks:
(i) Having a basic understanding of the problem. As
we have said earlier, problems that we human being
cannot solve, computer too cannot solve it. The
problem we are solving should be well understood
before we can write a meaningful functional program
for it.
(ii) Identification and designing of input data. All the
data (variables) to be used in the program must be
well analysed. What type(s) they are, in which format
are they going to be, from which medium (keyboard,
files in disks, etc) will they come from, etc. By types,
we mean whether they are whole numbers (called
integers), numbers with decimal points, for example
3.6 (called Real), characters or texts. The data input
could come from the keyboard, a file or some signals
from other electronic systems.
(iii) Identification of any suitable solution model. If it is
mathematics-based, is there any model formula for
solving the problem? For instance, we have a formula
for solving quadratic equations. Can you remember
the ‘almighty formula’? We shall soon come to it.
(iv) Identification and designing of outputs. We have to
decide on their type(s), in which format they are going
to be, from which medium (monitor, printer, files in
disks, etc) will they be directed to, etc.

Step 2. Designing of algorithm for the problem. A suitable


algorithm is designed for the problem in question, such as
was done in section 1.3.

16
Java for Beginners

Step 3. Testing the correctness of the algorithm. The algorithm


developed has to be desk-checked or dry-run line by line to
make sure it solves the problem accurately.

Step 4. Translating the algorithm into a suitable programming


language. The tested algorithm is now coded with a suitable
programming language.

Step 5. Testing and executing the program. The program


developed is compiled and executed. The program must be
tested with different kinds of data, valid and invalid to make
sure that it can work properly in all data input conditions.

Step 6. Documenting the program. Documentation is very


essential in programming. We have two types – internal and
external. Internal documentation involves putting comments
and white spaces in our program source codes. They are
there to introduce the functionality of the program as well as
to introduce the different sections of the code for readability
and maintenance of the code. External documentation are in
form of a manual for operating and maintaining the program
by any user of the program. The user will specify the
functionality of the program, inputs and their formats,
expected outputs and their formats, operating instructions
for the program, etc. To maintain any code, the
documentation on the code will have to be consulted first.

Many of us have the idea of coding programs directly on the


computer editor without passing through the paper-work stage
(Algorithm). It is a wrong practice! We need to design and test the
algorithm for the problem we have at hand before going to the
coding stage so as to ascertain the feasibility and correctness of the
problem.

17
1.6 Good Programming Style

The following programming styles, not exhaustive, are advised to be


followed when writing programs:

1. Choose appropriate names for your variables. The names


you use for your variables should be meaningful and suggest
clearly the purpose of the variable. They should
communicate what the variable is meant for at least. For
example, Area_of_Rect suggests that the variable is for the
area of a rectangle. For a program to work properly, it is of
utmost importance to know exactly what each variable
represents, and to know exactly what each subprograms
must be included with their names chosen with care to
identify their meanings clearly.
2. Special care must be given to the choice of names for
procedures, functions, constants and all variables and types
used in different parts of your program. Keep the names
simple for variables used only briefly and locally. A single
letter is often a good choice for the variables controlling a
loop but would be a poor choice for a subroutine or function.
3. Avoid choosing attractive names whose meaning has little or
nothing to do with the problem. The statements, ‘If TV in
hock Do study’, ‘If not sleepy then play else nap’; may be
funny but they are bad programming styles.
4. Avoid choosing names that are too close to each other in
spelling or otherwise easy to confuse, for example, Num1,
Num2, Num3.
5. Be careful in the use of the letter i (small letter i), l (small
ell), O (capital O) and 0 (zero).
6. Choose appropriate data types for your variables. All
variables must be associated with types such as Integer,
Real, Character or Logical. The type of a variable indicates
how it will be physically stored in memory and what type of
data to be logically assigned to it during the execution of the
program in which it is declared.

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.

1.6 Errors in Programming

There is no way we could be one hundred percent perfect in


programming; errors (bugs) are bound to occur and removed
(debugged) in our programs. The following common errors exist in
programming:

1. Syntax error: This occurs when the grammatical rules


of the programming language we are using is not
followed. For instance, if we misspell a keyword, or we
don’t put semi-colon at the appropriate places, syntax
errors occur.
2. Semantic error: Semantics have to do with attaching
meanings to our program statements. This error occurs if
the compiler cannot attach meaning to a program
statement. For instance, if we are trying to assign a
floating-point value to an integer location, or we are
trying to divide a value by zero.
3. Logic Error: This is usually made by programmers.
The program will definitely compile and run very well
but the output we get from it will be erroneous. For

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.

1.7 Programming languages

To be executable, a program must be written in the binary machine


code recognised by the processor. Machine code programming is
difficult and prone to error. Furthermore, since each type of
processor has its own machine code, a program written for one type
of processor is not executable by any other.

1.7.1 High level languages

Today, most programs are written in high level languages, which


resemble English and are therefore easier to use than machine code,
but which have a limited, specialised vocabulary and a simple syntax
free from ambiguity.

High level language instructions are not executable. Instead, a high


level language source program is read as input by a program called
a compiler, which checks its syntax and, if it is free from errors,

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).

Although it is in machine code, the object program is incomplete


because it includes references to subprograms which it requires for
such common tasks as reading input, producing output and
computing mathematical functions. These subprograms are grouped
together in libraries which are available for use by all object
programs. To create an executable program, the object program must
be linked to the subprogram libraries it requires. The executable
program may then be loaded into memory and run. For instance, the
steps required to compile, link and run a FORTRAN program are
illustrated by the Figure below.

Object
Source Compile Program Executable Run
Program Link Program
(Machine
Code)

Library
Subprograms

Compiling, linking and running a FORTRAN program

1.9 Categories of Programming Languages

Basically, we have many categories of programming languages such


as imperative versus non-imperative, functional versus non-
functional, object versus procedural, scientific versus non-scientific
languages, etc. A more generic categorization is as follows:
(a) High Level Languages: These programming languages are
English-like, user-friendly, non-machine dependent and take
less effort and time in coding. Examples are the common

21
programming languages found around such as COBOL,
C++, C, Java, FORTRAN, etc.

(b) Assembly language: These languages are in form of


mnemonics (symbolic codes). They are more or less
English-like but they are full of abbreviations. User-
friendliness is somehow low compared to the high level
languages. Assembly languages are in between the high
level and machine languages. They are machine dependent
in the sense that one has to be familiar with the instruction
sets of the computer before we can write an Assembly code
for it.

(c) Low Level / Machine Language: This is the native


language of the computer. Programming is done with
writing of sequences of 0s and 1s. Computer only
understands the high level (logic 1) and low level (logic 0)
signals. So, to program in machine language of the blessed
memory, one has to be conversant with bits representation of
characters and symbols to use. For example, Capital letter A,
whose ASCII codeword is 65 is encoded as 1000001 in
binary. To code A, the binary representation is encoded.
Machine languages are highly machine dependent. Machine
code for Motorola machines is different from that of
Pentium.

Other categorizations are:

(a) Strongly Typed languages: These are languages that


demand that their variables and constants must be declared
before they are used. One peculiarity of them is that they are
usually case sensitive. However, case sensitivity does not
warrant a language being strongly typed. Examples of
languages in this category are C, C++, Java, Pascal, etc.

(b) Weakly Typed languages: These languages have some


implicit way of declaring and using variables in them. There

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.

(c) Loosely Typed Languages: In these types of languages,


variables declared can assume any value depending on the
context of usage. The variables have multiple or dynamic
usages. In PHP, we can declare a variable $Name and be
assigned a value 3.4. This means that $Name is a floating-
point or real variable. At latter time, if we assign to it
“Akinola”, this assignment has changed its data type to a
string value. The same variable is used in different contexts.
In other words, the data types of variables depend on their
present assignments. These languages are highly case
sensitive.

1.10 Structured Programming Paradigm

Structured programming is an approach that breaks a program into


logical sections, called modules, in such a way as to minimize the
program’s complexity. In other words, modularity of programs’
source code is the essence of structured programming. A structured
program is classified as readable program. Structured
programming is a way of ensuring that subsidiary sections are
arranged in such a way that they can be worked on, truly
independently, that is, without reference to other parts of the
program. Each section can be tested and debugged as it is
completed; thus, considerably enhancing the chances of obtaining a
working program. In addition, if problems do occur, they can be

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:

(i) It has a label or name.


(ii) Perform only one specified task.
(iii) Complete the task satisfactorily before continuing.
(iv) Have only one entry point.
(v) Have only one exit point.
(vi) Be composed of the necessary program statements or
calls to other subsections, which perform various
subtasks and which themselves strictly satisfy these
conditions.
(vii) It should only call another module at a lower level than
itself.
(viii) Be independent.

1.10.1 Approaches to Structured Program Design

Program design takes a unique position in any software development


process. In program designing, we look for the mechanisms that best
implement a solution to the scientific / mathematical problem we are
solving. Program design is a necessary step in the software
development process because it allows a final refinement of the
ideas behind the system’s structure before construction of a working
system begins. The entire software development process is depicted
thus:

24
Java for Beginners
Process Action

Requirements Analysis (What is the problem?)

System Design (What is the solution?)

Program Design (What are the mechanisms that best


implement the solution?)

Program Implementation (How is the solution constructed?)

Testing (Is the problem solved?)

Delivery (Can the solution be used?)

Maintenance (Are enhancements needed?)

Program design is done in two steps. First, we translate the system


design into a set of specifications for the programmers, building into
the system design the characteristics of quality, modularity,
independence, efficient algorithm, appropriate data types and single-
entry-single-exit modules. Second, we evaluate each module to
make sure that its implementation is feasible, given the system’s
environment constraints.

Generally, program design performs two functions:


(i) Decision as to what data structures to use in
implementing a system is best handled by program
design.
(ii) It also provides more details about algorithms. For
example, system design specification may be that a
module is to sort a list; program design then identifies
what sorting algorithm to use for this task.

25
There are two approaches normally used to design a structured
program:

1. Top-down Approach

This is also called modular design and it encompasses the concept of


stepwise refinement. We examine and analyze the problem from the
highest or more general level to a more detailed level. This means
that a top down analysis examines all modules but first translate
higher levels to more concrete program specifications before
descending to lower levels. At any point, only data and control
information with structures necessary for a module are defined. The
details of the design at lower levels remain hidden. In this way, as
little codes as possible need to be written. This allows an error in the
design of the program to be corrected before too much time or work
has been spent on trying to implement it. The essential elements of
top-down design are:
 Design the program in levels or modules.
 It must be initial language-independent.
 Postponement of details to the lower level.
 Defining the interface with the lower level.
 Verification of each module as it is written.

Advantages of Modularity / Top-Down Design

(i) It enables one to concentrate on solving smaller, more


controllable problems in such a way that the solutions
probably will fit together to complete the entire
programming project.
(ii) A logical pathway through the program is identified
during the development process and relationships
between modules are defined as the modules are
separated rather than as an afterthought.
(iii) Parts of the program may be tested and changed without
affecting other parts.
(iv) The top-down modular technique makes it possible to
allocate parts of a large programming project to different

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.

However, coupling among modules usually increases, since more


control mechanisms are needed and since more data may be passed
or shared by modules. This increased coupling makes detecting and
correcting an error or changing a function latter in the life of the
system much more difficult. In addition, it is sometimes hard to
maintain the degree of information hiding originally designed into
the system. Consequently, bottom-up approach is employed only
when its advantages outweigh these disadvantages.

1.11 Criteria for Judging a Program

The following yardsticks are normally used to judge if a program is


good or not:
1. Problem Solvability: Does the program solve the problem
as requested, that is, according to the given specifications?
2. Workability: Does the program work under all conditions?

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?

1.11 A Look At Procedure-Oriented Programming

Conventional programming, using high-level languages such as


COBOL, FORTRAN and C, is commonly known as procedure-
oriented programming (POP). In the procedure-oriented approach,
the problem is viewed as a sequence of things to be done such as
reading, calculating and printing. A number of functions are written
to accomplish these tasks. The primary focus is on functions.
Procedure-oriented programming basically consists of writing a list
of instructions (or actions) for the computer to follow, and
organizing these instructions into groups known as functions. We
normally use a flowchart to organize these actions and represent the
flow of control from one action to another. While we concentrate
on the development of functions, very little attention is given to the
data that are being used by various functions. What happens to the
data? How are they affected by the functions that work on them?

In a multi-function program, many important data items are placed


as global so that they may be accessed by all the functions. Each
function may have its own local data. Global data are more
vulnerable to an inadvertent change by a function. In a large
program it is very difficult to identify what data is used by which
function. In case we need to revise an external data structure, we
also need to revise all functions that access the data. This provides
an opportunity for bugs to creep in.
Another serious drawback with the procedural approach is
that it does not model real world problems very well. This is because

28
Java for Beginners
functions are action-oriented and do not really correspond to the
elements of the problem.

Some characteristics exhibited by procedure-oriented programming


are:
 Emphasis is on doing things (algorithms)
 Large programs are divided into smaller programs known as
functions.
 Most of the functions share global data.
 Data move openly around the system from function to
function.
 Functions transform data from one form to another.
 Employs top-down approach in program design.

1.12 Object-Oriented Programming Paradigm

The major motivating factor in the invention of object-oriented


approach is to remove some of the flaws encountered in the
procedural approach. OOP treats data as a critical element in the
program development and does not allow it to flow freely around
the system. It ties data more closely to the functions that operate on
it, and protects it from accidental modification from outside
functions. OOP allows decomposition of a problem into a number of
entities called objects and then builds data and functions around
these objects. The organization of data and functions in object-
oriented programs is shown in Figure below. The data of an object
can be accessed only by the functions associated with that object.
However, functions of one object can access the functions of other
objects.
Object A Object B
Data Data
Communication

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.

Object-oriented programming is the most recent concept among


programming paradigms and still means different things to different
people. It is therefore important to have a working definition of
object-oriented programming before we proceed further. We define
“object-oriented programming as an approach that provides a way
of modularizing programs by creating partitioned memory area for
both data and functions that can be used as templates for creating
copies of such modules on demand.” Thus, an object is considered to
be a partitioned area of computer memory that stores data and set of
operations that can access the data. Since the memory partitions are
independent, the objects can be used in a variety of different
programs without modifications. There are many advantages to an
object-oriented approach to application development, but the two
most important are maintainability and robustness.

1.13 Basic Concepts of Object-Oriented Programming

It is necessary to understand some of the concepts used extensively


in object-oriented programming. These include:

30
Java for Beginners

1.13.1 Objects

An object is a bundle, a clump, a gathering together of items of


information that belong together, and functions that work on those
items of information. For example, a BankAccount object might
gather up a customer number, account number, and current balance--
these three pieces of information are required for all bank accounts.
Many languages provide a way to group related information together
into structures or records or whatever the language calls the feature.
However, where an object differs from these is in including
functions, or behavior, as well as information. Our BankAccount
object will have Deposit( ), Withdraw( ), and GetBalance( )
functions, for example.

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).

Software objects are modeled after real-world objects in that they


too have state and behaviour. A software object maintains its state in
one or more variables. A variable is an item of data named by an
identifier. A software object implements its behaviour with methods.
A method is a function (or subroutine or procedure) associated with
an object.

Therefore, an object is a software bundle of variables and


related methods.

31
Everything that the software object knows (state) and can do
(behaviour) is expressed by the variables and the methods within
that object.

When a program is executed, the objects interact by sending


messages to one another. For example, if ‘customer’ and ‘account’
are two objects in a program, then the customer object may send a
message to the account object requesting for the bank balance. This
information is passed along with the message as Parameters. Each
object contains data, and code to manipulate the data. Objects can
interact without having to know details of each other’s data or code.
It is sufficient to know the type of message accepted, and the type of
response returned by the objects. Although different authors
represent them differently.

1.13.2 Classes

We just mentioned that objects contain data, and code to manipulate


that data. The entire set of data and code of an object can be made a
user-defined data type with the help of a class. In fact, objects are
variables of the type class. Once a class has been defined, we can
create any number of objects belonging to that class. Each object is
associated with the data of type class with which they are created. A
class is thus a collection of objects of similar type. For example,
mango, apple and orange are member of the class fruit. Your bicycle
is just one of many bicycles in the world. Using object-oriented
technology, we say that your bicycle object is an instance of the
class of objects known as bicycles. However, despite the fact that
bicycles have some state and behaviour in common, each bicycle’s
state is independent of and can be different from that of other
bicycles. Classes are user-defined data types and behave like the
built-in types of a programming language. The syntax used to create
an object is no different than the syntax used to create an integer
object in C. If fruit has been defined as a class, then the statement:

Fruit mango;

32
Java for Beginners

will create an object mango belonging to the class fruit

In essence, “A class is a blueprint, or prototype, that defines the


variables and the methods common to all objects of a certain
kind”.

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.

1.13.3 Data Abstraction And Encapsulation

The wrapping up of data [variables or state] and functions [methods]


into a single unit (called class) is known as encapsulation. Data
encapsulation is the most striking feature of a class. The data is not
accessible to the outside world, and only those functions, which are
wrapped in the class, can access it. These functions provide the
interface between the object’s data and the program. This insulation
of the data from the direct access by the program is called data
hiding or information hiding. Encapsulating related variables and
methods [functions] into a neat software bundle is a simple yet
powerful idea that provides two primary benefits to software
developers:
(1) Modularity: The source code for an object can be written and
maintained independently of the source code for other objects.
Also, an object can be easily passed around in the system.
(2) Information hiding: an object has a public interface that
other objects can use to communicate with it. The object can
maintain private information and methods/functions that can

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.

Abstraction refers to the act of representing essential features


without including the background details or explanations. Classes
use the concept of abstraction and are defined as a list of abstract
attributes such as size, weight and cost, and functions to operate on
these attributes. They encapsulate all the essential properties of the
objects that are to be created. The attributes are sometimes called
data members because they hold information. The functions that
operate on these data are sometimes called methods or member
functions.

Since the classes use the concept of data abstraction, they are known
as Abstract Data Types (ADT).

1.13.4 Inheritance

Inheritance is the process by which objects of one class acquire the


properties of another class. It supports the concept of hierarchical
classification. For example, the bird ‘Robin’ is a part of the class
‘flying bird’, which is again a part of the class ‘ bird’. The principle
behind this sort of division is that each derived class shares common
characteristics with the class from which it is derived.

In OOP, the concept of inheritance provides the ideal of reusability.


This means that we can add additional features to an existing class
without modifying it. This is possible by deriving a new class from
the existing one. The new class will have the combined features of
both the classes. The real appeal and power of the inheritance
mechanism is that it allows the programmer to reuse a class that is
almost, but not exactly, what he wants, and to tailor the class in such
a way that it does not introduce any undesirable side-effects into the
rest of the classes.

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

Polymorphism is another important OOP concept. Polymorphism, a


Greek term, means the ability to take more than one form. An
operation may exhibit different behaviours in different instances.
The behaviour depends upon the types of data used in the operation.
For example, consider the operation of addition (+). For two
numbers, the operation will generate a sum. If the operands are
strings, then the operation would produce a third string by
concatenation. The process of making an operator to exhibit
different behaviours in different instances is known as operator
overloading.

Polymorphism plays an important role in allowing objects having


different internal structures to share the same external interface. This
means that a general class of operations may be accessed in the same
manner even though specific actions associated with each operation
may differ. Polymorphism is extensively used in implementing
inheritance.

1.13.6 Dynamic Binding

Binding refers to the linking of a procedure call to the code to be


executed in response to the call. Dynamic binding (also known as
late binding) means that the code associated with a given procedure
call is not known until the time of the call at run - time. It is
associated with polymorphism and inheritance. A function call
associated a polymorphic reference depends on the dynamic type of
that reference.

35
1.13.7 Message Passing

An object-oriented program consists of a set of objects that


communicate with each other. The process of programming in an
object-oriented language, therefore, involves the following basic
steps:
1. Creating classes that define objects and their behaviour,
2. Creating objects from class definitions, and
3. Establishing communication among objects.
The concept of message passing makes it easier to talk about
building systems that directly model or simulate their real-world
counterparts. Message passing involves specifying the name of the
object, the name of the function /method and the information to be
sent. E.g. employee.salary(name);

1.14 Benefits of Oop

 Through inheritance, we can eliminate redundant code and


extend the use of existing classes.
 We can build programs from the standard working modules that
communicate with one another, rather than having to start
writing the code from scratch. This leads to saving of
development time and high productivity.
 The principle of data hiding helps the programmer to build
secure programs that cannot be invaded by code in other parts of
the program.
 It is possible to have multiple instances of an object to co-exist
without any interference.
 It is possible to map objects in the problem domain to those in
the program.
 It is easy to partition the work in a project based on objects.
 The data-centered design approach enables us to capture more
details of a model in implementable form.
 Object-oriented systems can be easily upgraded from small to
large systems.

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.

The promising areas for OOP application include Real-time


systems, Simulation and Modelling, Object-oriented Databases,
Hypertext, Hypermedia, AI, Expert Systems, Neural Networks,
Decision support systems CAM and CAD systems.

1.15 Writing and testing programs

This section contains some general principles which should be


observed in writing and testing programs. An attempt has been made
to demonstrate them in the examples in the subsequent chapters.

1. Plan your programs

Do not attempt to write your programs straight away. Write an


outline showing the main steps in sequence. Use indentation to
indicate the logical structure.

2. Develop in stages

The steps defined in 1. can initially be quite broad and general.


Revise your outline as often as required, breaking down each main
step into a sequence of simpler steps. Repeat this process until your
steps correspond to program statements.

3. Define variables and arrays

While developing your program as above, think about the main


variables and arrays you will require to represent the information.
Choose names which suggest their usage and write down each name
with its type and dimensions (if an array) and a note of what it

37
represents. Always use IMPLICIT NONE statement to force
explicit typing of variables and arrays.

4. Modularise

Use functions and subroutines not only to avoid repetitive coding


but, more importantly, to keep your program simple and its structure
clear by putting the details of clearly defined computations in
separate units.

5. Provide for exceptions

Your program should be designed to cope with invalid data by


printing informative error messages rather than simply failing, e.g.
due to attempted division by zero. This applies especially if your
program will be used by others.

6. Clarity

When writing your program code, use indentation to clarify its


logical structure and include explanatory comments freely.

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

1. Explain the following concepts with reference to Java


programming language:
(i) Portability
(ii) Coding effort
(iii) Pedagogy
(iv) Internet application support
(v) Data types and data structures
(vi) Efficiency (in terms of translation and execution)
(vii) Code size
(viii) Modularity
(ix) Platform independence
(x) GUI support

2. a. Give five principles of a good programming style


b. “To see it right set it right”. Discuss this assertion
with reference to good programming style.
c. Give five differences between Java programming
language and any typical procedural language of your
choice.

3. Define the following object-oriented technique concepts


(i) Object oriented programming
(ii) Abstraction
(iii) Encapsulation
(iv) Method
(v) Message
4. Assuming you want to write a program to compute the sum and
average of any two numbers, state all the steps you will take
starting from the analysis stage.

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++ ;

b. for (k = 0.1; k != 1.0; k += 0.1);


printf(“%f8.2”, k);

c. int sum(int n) {
if (n = 0)
return 0;
else
n + sum(n – 1);
}

d. double [ ] array = new array[8];

40
Java for Beginners

2
Java Fundamentals
2.0 Introduction

In this chapter, the basic principles of writing and executing program


codes in Java language are discussed. We begin introducing you to
writing codes in the language

Java is an Object Oriented programming language with a relatively


simple grammar. Java omits rarely used, poorly understood,
confusing features of C++ such as header files, pointer arithmetic,
structures, unions, operator overloading, and templates. Java also
adds new features like automatic garbage collection. All methods,
fields and constructors are local to classes—that is, there is no global
data. Java supports static methods and fields, exception handling,
inheritance, and control structures such as while loops, for loops and
if/else statements.

The following are the fundamental features of Java programming


language:

1. Simplicity: the designers of the language were trying to


develop a language that a programmer could learn
quickly. They eliminated some constructs in C and C++
that are complex such as pointers.
2. Object Oriented: Everything is an object in java. The
focus is on the data and the methods that operate on the

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.

2.1 Creating and Running a Java Program.

If you do not have access to Windows-based integrated package for


running java programs, then use the command window as follows:
 Open Notepad by clicking Start, programs, Accessories, and
Notepad.
 Type the Java source code.
 Save the file [<filename>.java], possibly in the same
directory with java compiler, i.e. the bin directory.
 Open a Dos command window, navigate to the folder that
contains the java program using the DIR command; i.e. Cd
j2sdk1.4.1_02\bin
 Compile the program by typing javac <filename>.java
 If compiled successfully, a new file with the extension .class
would show on the current directory. Check this with the
DIR command. This is the byte code file that the JVM (Java

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>).

Nowadays, we have some integrated packages for editing and


running java programs. For example, we have Java Net Beans,
JCreator, JBuilder, Oracle JDeveloper, and many more. They are
windows-like, just like Visual C++. Some of them contain both the
editor and compiler together for editing and running java
applications. Many of them are downloadable free from the Internet.

To use JCreator, download and install it from the Internet. The


interface looks like the one below:

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

A simple Java code looks like this:

public class Welcome {


public static void main(String[ ] args) {
System.out.println(“Welcome to Java world”) ;
} //End main method
} // End class Welcome

Note: Java is case–sensitive. Capital letters must be capitals e.g.


String, System.

Let’s try to analyze the above simple java program.

(a) The first line declares a class named Welcome.

public class Welcome {

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.

public static void main(String[ ] args) {

Every class must have a method or function that will be used to


manipulate the data in the class. the default name given to that
method is main. The method main has some descriptors associated

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.

(c) The third line contains the single executable statement.

System.out.println(“Welcome to Java world”) ;

The message put in quotes would be printed out as they are


written. The word println is the name of the method that tells
the system how to do the printing, which means, after the
message is printed, the cursor should move to the next line.
Note the parenthesis and the semi colon usage. The semi
colon is a terminator for each executable line.

(d) The two closing braces, } mark the end of the program. The
first closes the main method and the other closes the class.

2.2.1 print( ) and println( ) methods

Both print( ) and println( ) are standard output functions that print
data to the monitor screen. The statement:

46
Java for Beginners

System.out. print (a, b, c)

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.

However, if we had used System.out.println( a, b, c), the values of


the data items would also be printed on a single line but after all the
printings, the cursor will move to the next line for other printing
commands. The two work like WRITE( ) and WRITELN( ) in
PASCAL programming language. For example, given the following
data and the subsequent code segment:

a = 2;
b = 4;
c = 6;
d= 8;

System.out.print(a, b); // Line 1


System.out.print(c); // Line 2
System.out.println( ); // Line 3
System.out.println(d); // Line 4

The code will produce the following outputs:

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

Comments are very good in programs. They enhances easy


comprehension/readability of the codes, section by section and the
are veritable tool for future program maintenance. Anybody can pick
the code in the future and with the help of the comment lines,
modify, upgrade or correct the program for some errors. Java
embraces both C and C++ styles of comments.

The C comment style is a multi-line style. It is used when we have


several lines of comments to be inserted into our programs. Take for
example,

/* Program written by …..


Matric No…. Version 1.0 Date ……

*/

One major problem of the C comment style is that we must ensure


that the closing sysmbol (*/) is inserted at the end of the entire
comment lines; else the compiler will assume that all other lines
below the opening symbol (/*) are all comments!

The C++ Style comment could be used as an in-line comment,


inserted at the end of an executable statement like:

X = X – 4 // subtracting 4 from X

Or as a free-standing comment like:

// Program written by ……..

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.

2.4 Inputting Data into Java Programs

A wrong kind of input received by a program may crash the


program. Such a run-time error is called an “exception”, which java
provides special mechanisms for handling. Simply, we append the
clause “throws IOException” to the declaration of the main( )
method.

2.4.1 String Data Input

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.

2.4.2 Numeric Data Input

Every object used in a Java program must be declared before it is


used. For Example, String myName. The declaration may optionally
include an initialization such as

String myName = input.readLine( );

Numeric variables are declared thus:

long m; //m is a 64-bit integer


double x; // x is a 64-bit floating-point (decimal) number

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:

//Computing your Year of Birth


import java.io.*;
public class YearOfBirth {
public static void main(String[ ] args) throws IOException {
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(reader);
System.out.print(“Enter your age: “);
// data entered is captured into ‘text’ variable

String text = input.readLine();


// parsing ‘text’ to int

int age = new Integer(text).intValue();


System.out.print(“Enter this year’s value e.g. 2007: “);
String cyear = input.readLine();
int currentYr = new Integer(cyear).intValue();
int year = currentYr – age;
System.out.println(“You are ” + age + ” years old now”);
System.out.println(“ So you were probably born in ” + year);
}
}

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:

int age = Integer.parseInt(text).

Other variations are Double.parseDouble, and Float.parseFloat.

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

Alternatively, instead of using the InputStreamReader we could use


the Scanner, which can also be used in the DOS mode like the
previous examples. However, Scanner facilities are only available in
Java 1.5 and above. InputStreamReader, BufferedReader and
Scanner are java file handling facilities. We shall study more on
them later in the chapter dedicated to files. The following example
code computes the average of any three numbers. Note the reading
of each of the data types – float, int, double and string in the code.

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

2.6 Using the Swing Facility

As another example, the program below illustrates the use of


swings facility in java, a form of windows-based programming. Run
this program and report your observations:

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!

(ii) The lines:


number1= Integer.parseInt(firstNumber);
number2= Integer.parseInt(secondNumber);

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);

can be written as follows:

int number1 = nteger.parseInt(JOptionPane.showInputDialog("Enter


first Number"));

As java is highly case sensitive, note that int against number1


to declare it is with small i, while all the I’s on right hand side
of the assignment statement are all capitals. Other variations
are
float a = Float.parseFloat(JOptionPane.showInputDialog( “ ” ));
double b = Double.parseDouble(JOptionPane.showInputDialog( “ ” ));

(iii) The showMessageDialog method has four parameters to be


passed into it: null, user’s output, title of the message dialog
and the type of icon to be attached to the message box whether
error, information or any other. Each of these parameters is
separated by commas. Check this with the example above.
We are particular about the last three. All the output that the
user wants the message box to print out including prompting
messages are specified in the user’s output parameter. The

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.

2.7 Java Variables and Objects

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:

1. It must be a legal identifier. An identifier is an


unlimited series of Unicode characters that begins
with a letter.
2. It must not be a keyword, a boolean literal (true or
false), or the reserved word null.
3. It must be unique within its scope. A variable may
have the same name as a variable whose declaration
appears in a different scope. In some situations, a
variable may share the same name as another
variable if it is declared within a nested block of

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.

By Convention: Variable names begin with a lowercase letter, and


class names begin with an uppercase letter. If a variable name
consists of more than one word, the words are joined together, and
each word after the first begins with an uppercase letter, like this:
isVisible. The underscore character (_) is acceptable anywhere in a
name, but by convention is used only to separate words in
constants (because constants are all caps by convention and thus
cannot be case-delimited).

2.8 Scope of Variables

A variable's scope is the region of a program within which the


variable can be referred to by its simple name. Secondarily, scope
also determines when the system creates and destroys memory for
the variable. Scope is distinct from visibility, which applies only to
member variables and determines whether the variable can be used
from outside of the class within which it is declared. Visibility is set
with an access modifier.

The location of the variable declaration within your program


establishes its scope and places it into one of these four categories:

 member variable
 local variable
 method parameter
 exception-handler parameter

58
Java for Beginners

A member variable (or global variable) is a member of a class or


an object. It is declared within a class but outside of any method or
constructor. A member variable's scope is the entire declaration of
the class. However, the declaration of a member needs to appear
before it is used when the use is in a member initialization
expression.

You declare local variables within a block of code. In general, the


scope of a local variable extends from its declaration to the end of
the code block in which it was declared.

Parameters are formal arguments to methods or constructors and


are used to pass values into methods and constructors. The scope of
a parameter is the entire method or constructor for which it is a
parameter.

Exception-handler parameters are similar to parameters but are


arguments to an exception handler rather than to a method or a
constructor. The scope of an exception-handler parameter is the code

59
block between { and } that follow a catch statement. We shall deal
with this topic later.

Consider the following code sample:

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.

2.9 Variable Initialization

Local variables and member variables can be initialized with an


assignment statement when they're declared. The data type of the
variable must match the data type of the value assigned to it.
Parameters and exception-handler parameters cannot be initialized
in this way. The value for a parameter is set by the caller.

2.10 Final Variables / Java Constants

You can declare a variable in any scope to be final. The value of a


final variable cannot change after it has been initialized. Such
variables are similar to constants in other programming languages.

To declare a final variable, use the final keyword in the variable


declaration before the type:

final int aFinalVar = 0;

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.

2.11 Data Types:

Every variable must have a data type. A variable’s data type


determines the values that the variable can contain and the
operations that can be performed on it. For example, declaring a
variable to be int var means that var is an integer data type. Integers
can contain only integral (whole numbers) values (both positive and
negative) and we can perform arithmetic operations, such as
addition, on integer variables.

Java programming has two categories of data types: primitive and


reference. A variable of primitive type contains a single value of
the appropriate size and format for its type: a number, a character,
or a Boolean value.The table below lists all of the primitive data
types along with their sizes and formats:

Keyword Description Size/Format

(Integers: numbers without decimal places, eg. 45, 456)

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

(Real numbers: numbers with decimal places, e.g. 3.21)

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.

We can put a literal primitive value directly in our codes. For


example, if we need to assign the literal integer value 4 to an integer
variable we can write this:

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.

Other examples of literal values are:


178 int
456L Long
34.876 double
23.786D double
56.89F float
‘s’ char
true Boolean

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

An operator performs a function on one, two, or three operands. An


operator that requires one operand (Op) is called a unary operator.
For example, ++ is a unary operator that increments the value of its
operand by 1. An operator that requires two operands is a binary
operator. For example, = is a binary operator that assigns the value
from its right hand operand to its left-hand operand. And finally, a
ternary operator is one that requires three operands. The java
programming language has one ternary operator, ?:, which is a short-
hand if – else statement. In addition to performing the operation, an
operator returns a value. The return value and its type depend on the
operator and the type of its operand. For example, the arithmetic
operators, which perform basic arithmetic operations such as
addition and subtraction, return numbers – the result of the
arithmetic operation. The data type returned by an arithmetic
operator depends on the type of its operands: if we add two integers,
we get an integer back. An operation is said to evaluate to its result.
Below are the java-supported operators.

2.12.1 Arithmetic Operators

These operators are used in arithmetic computations in java


programming environment. These are:

Operator Use Description

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;

Op— Decrements op by 1; evaluates to the


--
e.g i--; value of op before it was decremented

64
Java for Beginners

--Op Decrements op by 1; evaluates to the


--
e.g –i; value of op after it was decremented

+ a+b Add a and b together

- a–b Subtract b from a

/ a/b Divides a into b

* a*b Product of a and b

% a%b Remainder when a is divided by b

What happens when we have combinations of different data types in


one single expression? It needs be noted that when an integer and a
floating-point number are used as operands to a single arithmetic
operation, the result is floating point. The integer is implicitly
converted to a floating-point number before the operation takes
place. This is called data coercion. For instance, if we have the
following statement:

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

Neither operand is a float or a double (integer


long
arithmetic); at least one operand is a long.

65
Neither operand is a float or a double (integer
int
arithmetic); neither operand is a long.

double At least one operand is a double.

At least one operand is a float; neither operand is a


float
double.

In addition to the binary forms of + and -, each of these operators


has unary versions that perform the following operations:

Operator Use Description

Promotes op to int if it is a byte, short or a


+ +op
char.

- -op Arithmetically negates op.

2.12.2 Assignment Operators

We use the basic assignment operator, =, to assign one value to


another. In ordinary arithmetic, we are permitted to write a + b = c –
d, but this is not allowed in programming. The expression at the left
hand side (a+b) is regarded as a memory location to which we are
assigning the result computed at the right hand side to. Java also
provides several short-cut assignment operators that allow us to
perform arithmetic, shift, or bitwise operation and an assignment
operation, all with one operator. The table below gives the major
assignment operators in java.

66
Java for Beginners

Oper- Example
Use Equivalent to
ator

+= Op1 += op2 op1 = op1 + op2 a = a + b  a += b

-= Op1 -= op2 op1 = op1 - op2 a = a + b  a += b

*= Op1 *= op2 op1 = op1 * op2 a = a * b  a *= b

/= Op1 /= op2 op1 = op1 / op2 a = a / b  a /= b

%= Op1 %= op2 op1 = op1 % op2 a = a % b  a %= b

&= Op1 &= op2 op1 = op1 & op2 We shall study

|= Op1 |= op2 op1 = op1 | op2 these operators

^= Op1 ^= op2 op1 = op1 ^ op2 in the latter

<<= Op1 <<= op2 op1 = op1 << op2 sections

>>= Op1 >>= op2 op1 = op1 >> op2

Op1 >>>= op1 = op1 >>>


>>>=
op2 op2

Examples: Arithmetic and Assignment Operators


A = x; // Assignment operator
n += 22; // n = n + 22
++n; // Increment Operator i.e. n = n + 1
n/a // Quotient (Division) operator
int y = n % b ; // Remainder Operator, divides n by b and
//assign the remainder to y

Note that +=, ++ and others are to be written together without any
space in between them.

67
2.12.3 Relational and Conditional Operators:

A relational operator compares two values and determines the


relationship between them. For example, != returns true if the two
operands are unequal.

The table below gives the examples of relational operators.

Operator Use Returns true if

> op1 > op2 op1 is greater than op2 e.g. if (a > b)

>= op1 >= op2 op1 is greater than or equal to op2

< op1 < op2 op1 is less than op2 e.g. if (a < b)

<= op1 <= op2 op1 is less than or equal to op2

== op1 == op2 op1 and op2 are equal e.g. if (a == b)

!= op1 != op2 op1 and op2 are not equal

Relational operators often are used with conditional / logical


operators to construct more complex decision-making expressions.

Java supports six conditional/logical operators – five binary and one


unary – as shown in the following table:

Operator Use Returns true if

op1 AND op2 are both true,


&& op1 && op2 conditionally evaluates op2. E.g.
if ((a < b) && (c > a)

either op1 OR op2 is true,


|| op1 || op2 conditionally evaluates op2. E.g
if ((a < b) || (c > a)

68
Java for Beginners

! ! op op is false . E.g. if !(a < b)

op1 and op2 are both true, always


& op1 & op2
evaluates op1 and op2

either op1 or op2 is true, always


| op1 | op2
evaluates op1 and op2

if op1 and op2 are different - that is,


^ op1 ^ op2 if one or the other of the operands is
true but not both

E6: This program makes use of the different comparison operators

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

// read first number from user as a string


firstNumber = JOptionPane.showInputDialog( "Enter the first
integer" );

// read second number from user as a string


secondNumber = JOptionPane.showInputDialog("Enter the second
integer");

//convert numbers from type string to type int


number1 = Integer.parseInt( firstNumber );
number2 = Integer.parseInt(secondNumber );

//initialize result to empty String


result="";

69
if ( number1 == number2)
result = result + number1 + "==" + number2;

if ( number1 != number2 )
result = result + number1 + "!=" + number2;

if ( number1 < number2 )


result = result + "\n"+ number1 + "<" + number2;
if ( number1 > number2 )
result = result + "\n" + number1 + ">"+ number2;
if (number1 <= number2 )
result = result + "\n" + number1 + "<=" + number2;
if (number1 >= number2 )
result = result + "\n" + number1 +"<=" + number2;

// Display results
JOptionPane.showInputDialog(null, result, "Comparison Result",
JOptionPane.INFORMATION_MESSAGE);
System.exit( 0 ); //terminate application
}
}

Output:

70
Java for Beginners

2.13 The Math Class

The math class provides an extensive set of mathematical methods in


the form of a static class library for manipulating the different
mathematical expressions such as e, , sin, cos, etc. Note that the
trigonometric ratios, sin, cos and tan are implemented in radian
measure and not degree. You need to write your own code to
convert the angles given in degrees to radians. Note that -rad
= 1800

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 **/

public class MathApp {


public static void main(String args []) {
System.out.println("Math.E = " + Math.E);
System.out.println("Math.PI = "+Math.PI);
System.out.println("Math.abs(-1234) =
"+Math.abs(- 1234));
System.out.println("Math.cos(Math.PI/4) =
"+Math.cos(Math.PI/4));
System.out.println("Math.sin(Math.PI/2) = "
+Math.sin(Math.PI/2));
System.out.println("Math.tan(Math.PI/4) =
"+Math.tan(Math.PI/4));
System.out.println("Math.log(1) = "+Math.log(1));
System.out.println("Math.exp(Math.PI) = "+Math.exp(Math.PI));

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

E8: Program to illustrate different arithmetic operators


public class Arith
{ public static void main(String[ ] args)
{ int m =25;
int n = 7;
System.out.println(“m = “ + m);
System.out.println(“n = “ + n);
int sum = m + n;
System.out.println(“m + n = “ + sum);
int difference = m-n;

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

2.14 Shift and Logical operators

A shift operator performs bit manipulation on data by shifting the


bits of its first operand right or left. The table below summarizes the
shift operators available in Java programming.

Operator Use Operation

Shifts bits of op1 right by


>> Op1 >> op2
distance op2

Shifts bits op1 left by


<< Op1 << op2
distance op2

Shifts bits of op1 right by


>>> Op1>>>op2
distance op2 (unsigned)

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 binary representation of the number 13 is 1101. The result of the


shift operation is 1101 shifted by one position –110, or 6 in decimal.
The left-hand bits are filled with 0s as needed.

The following table shows the four operators the java programming
language provides to perform bitwise functions on their operands:

Operator Use Operation

& Op1 & op2 Bitwise AND

| Op1 | op2 Bitwise OR

^ Op1 ^ op2 Bitwise XOR

~ ~op2 Bitwise Complement

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

Op1 Op2 Result

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

For the inclusive OR operation, if either of the two bits is 1, the


result is 1. The following table shows the results of this operation:

Op1 Op2 Result

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.

Check the table below:

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.

2.15 Other Operators

2.15.1 The ternary operator / Shortcut for if-


else statement ?:

op1 ? op2 : op3

The ?: operator returns op2 if op1 is true or returns op3 if op1 is


false.

2.15.2 The [ ] Operator

We use square brackets to declare arrays, to create arrays and to


access a particular element in an array. For example, to declare an
array that can hold ten floating point numbers, we write:

float [ ] floatArray = new float [10];

To access the 7th element of the array, we write

floatArray[6];

76
Java for Beginners
Note that array indices begin at 0 in java.

2.15.3 The . (Dot) Operator

The dot (.) operator accesses instance members of an object or class


members of a class. We shall more of this under the topic classes
and inheritance.

2.15.4 The ( ) Operator

When declaring or calling a method, we list the method’s arguments


between ( and ). We can also specify an empty argument list by
using ( ) with nothing between them.

2.15.5 The (type) Operator

Casts (or “converts”) a value to the specified type. Example:

double sum = (double) (num/a);

The statements converts the value evaluated from (num/a) to a


double value.

2.15.6 The ‘new’ Operator

We use the operator to create a new object or a new array.

2.15.7 The ‘instanceOf’ Operator

The InstanceOf operator tests whether its first operand is an instance


of its second.

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

A. Given the following code snippet:


int i = 10;
int n = i ++ %5;

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.

B. What is the value of i after the following snippet executes?


int i = 8;
i >>= 2;
Answer: i = 2
c. What is the value of i after the following snippet
executes?
int i = 17;
i >> = 1;

Answer: i = 8

78
Java for Beginners
2.16 Expressions

Variables and operators are the basic building blocks of programs.


We combine literals, variables and operators to form expressions –
segment of code that perform computations and return values.
Certain expressions can be made into statements – complete units of
execution. By grouping statements together with curly braces { and
}, we create blocks of code.

Among other things, expressions are used to compute and to assign


values to variables and to help control the execution flow of a
program. The job of an expression is two-fold: to perform the
computation indicated by the elements of the expression and to
return a value that is the result of the computation.

Therefore, an expression is a series of variables, operators and


method calls (constructed according to the syntax of the language)
that evaluates to a single value. An expression can be arithmetic or
logical. We have to specify how we want an arithmetic expression to
be evaluated by using balanced parentheses ( and ). For example,

x + y / 100 is ambiguous but


(x + y) / 100 is unambiguous and recommended.

If we don’t explicitly indicate the order in which we want the


operations in a compound expression to be performed, the order is
determined by the precedence assigned to the operators in use within
the expression. Operators with a higher precedence get evaluated
first. For example, the division operator has a higher precedence
than does the addition operator. Thus, the two following statements
are equivalent:

x + y / 100
x + (y / 100) // Unambiguous, recommended

79
2.17 Operators’ Order of Precedence

The following table shows the precedence assigned to the operators


in Java. The operators in this table are listed in precedence order: the
higher in the table an operator appears, the higher its precedence.
Operators with higher precedence are evaluated before operators
with a relatively lower precedence. Operators on the same line have
equal precedence.

Postfix operators [ ], ., (params), expr++, expr--

Unary operators ++expr, --expr, +expr, -expr, ~, !

Creation or cast new, (type)expr

Multiplicative *, ?, %

Additive +, -

Shift <<, >>, >>>

Relational <, >, <=, >=, instanceOf

Equality ==, !=

Bitwise AND &

Bitwise exclusive OR ^

Bitwise inclusive OR |

Logical AND &&

Logical OR ||

Conditional ?:

=, +=, -=, *=, /=, %=, ^=, |=, <<=,


Assignment
>>=, >>>=

80
Java for Beginners

All binary operators except for the assignment operators are


evaluated in left-to-right order. Assignment operators are evaluated
right to left.

2.18 Statements

Statements are roughly equivalent to sentences in natural languages.


A statement forms a complete unit of execution. The following types
of expressions can be made into a statement by terminating the
expression with a semicolon (;):
 Assignment expressions
 Any use of ++ or --
 Method calls
 Object creation expressions
These kinds of statements are called expression statements. Here are
some examples of expression statements:

aValue = 23.89; // assignment statement


aValue++; // increment statement
System.out.println(aValue);// method call statement
integer valueArray = new integer(4); // object creation

In addition to these kinds of expression statements, there are two


kinds of statements. A declaration statement declares a variable. For
example,

double aValue = 34.9; // declaration statement

A control flow statement regulates the order in which statements get


executed. The for loop and if statement are examples.

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 Formatting Your Outputs

Sometimes we may want to format our outputs either to some


number of decimal places or to display the output in a particular base
value. Java borrows the C – Language way of formatting outputs.
Method printf formats and outputs data to the standard output
stream, System.out. Class Formatter formats and outputs data to a
specified destination, such as a string or a file output stream. This
aspect of this book is extracted from the book: Java: How to
Program, by Deitel and Deitel, 6th Edition.

Every call to printf supplies as the first argument a format string


that describes the output format. The format string may consist of
fixed text and format specifiers. Fixed text is output by printf just
as it would be output by System.out methods print or println. Each
format specifier is a placeholder for a value and specifies the type of
data to output. Format specifiers also may include optional
formatting information.

2.20.1 Integers

An integer is a whole number, such as 776, 0 or 52, that contains no


decimal point. Integer values are displayed in one of several formats.
The table below describes the integral conversion characters.

82
Java for Beginners

Integer conversion characters.


Conversion
character Description
D Display a decimal (base 10) integer.
O Display an octal (base 8) integer.
x or X Display a hexadecimal (base 16) integer. X causes
the digits 09 and the letters AF to be displayed and
x causes the digits 09 and af to be displayed.

The printf method has the form

printf( format-string, argument-list );

where format-string describes the output format, and argument-list


contains the values that correspond to each format specifier in
format-string. There can be many format specifiers in one format
string. Examine the code snippets below:

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 );

The Outputs below would be produced:


26
26
-26
32
1a
1A

83
2.20.2 Floating-Point Numbers

A floating-point value contains a decimal point, as in 33.5, 0.0


or -657.983. Floating-point values are displayed in one of
several formats. Table below describes the floating-point
conversions. The conversion character e and E displays
floating-point values in computerized scientific notation (also
called exponential notation). Exponential notation is the
computer equivalent of the scientific notation used in
mathematics. For example, the value 150.4582 is represented in
scientific notation in mathematics as 1.504582 x 102

Floating-point Conversion Characters.

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.

Conversion character g (or G) prints in either e (E) or f format,


depending on the floating-point value. For example, the values
0.0000875, 87500000.0, 8.75, 87.50 and 875.0 are printed as
8.750000e-05, 8.750000e+07, 8.750000, 87.500000 and 875.000000
with the conversion character g. The value 0.0000875 uses e
notation because the magnitude is less than 10-3. The value
87500000.0 uses e notation because the magnitude is greater than
107. Code snippets below illustrate the use of these conversion
characters.

System.out.printf( “%e\n”, 12345678.9 );


System.out.printf(“%e\n”, +12345678.9 );
System.out.printf(“%e\n”, -12345678.9 );
System.out.printf(“%E\n”,12345678.9);
System.out.printf( “%f\n”, 12345678.9);
System.out.printf(“%g\n”, 12345678.9);
System.out.printf(“G\n”, 12345678.9);

Outputs
1.234568e+07
1.234568e+07
-1.234568e+07
1.234568E+07
12345678.900000

85
1.23457e+07
1.23457E+07

2.20.3 Printing Strings and Characters

The c and s conversion characters are used to print individual


characters and strings, respectively. Conversion character s can also
print objects with the results of implicit calls to method toString.
Conversion character c and C requires a char argument.
Conversion character s and S can take a String or any Object (this
includes all subclasses of Object) as an argument. When an object is
passed to the conversion character s, the program implicitly uses the
object's toString method to obtain the String representation of the
object. When conversion characters C and S are used, the output is
displayed in uppercase letters. The program shown next displays
characters, strings and objects with conversion characters c and s.
Note that autoboxing occurs at line 10 when an int constant is
assigned to an Integer object. Line 15 associates an Integer object
argument to the conversion character s, which implicitly invokes the
toString method to get the integer value. Note that you can also
output an Integer object using the %d format specifier. In this case,
the int value in the Integer object will be unboxed and output.

8 char character = 'A'; // initialize char


9 String string = "This is also a string"; // String object
10 Integer integer = 1234; // initialize integer (autoboxing)
11
12 System.out.printf( “%c\n”, character);
13 System.out.printf(“%s\n”, “This is a string”);
14 System.out.printf(“%s\n”, “string” );
15 System.out.printf(“%S\n”, “string”);
16 System.out.printf(“%s\n”, integer); // implicit call to toString

Outputs
A
This is a string
This is also a string
THIS IS ALSO A STRING

86
Java for Beginners
1234

2.20.4 Printing Dates and Times

With the conversion character t or T, we can print dates and times


in various formats. Conversion character t or T is always followed
by a conversion suffix character that specifies the date and/or time
format. When conversion character T is used, the output is displayed
in uppercase letters. The table below lists the common conversion
suffix characters for formatting date and time compositions that
display both the date and the time. Next table 2 lists the common
conversion suffix characters for formatting dates. Table 3 lists the
common conversion suffix characters for formatting times. To view
the complete list of conversion suffix characters, visit the Web site
java.sun.com/j2se/5.0/docs/api/java/util/Formatter.html.

1. Date and time composition conversion suffix characters.

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.

2. Date formatting conversion suffix characters.

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).

3. Time formatting conversion suffix characters.

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).

Conversion character t requires the corresponding argument to be of


type long, Long, Calendar or Date (both in package java.util) objects
of each of these classes can represent dates and times. Class
Calendar is the preferred class for this purpose because some
constructors and methods in class Date are replaced by those in class
Calendar. From the code below, Line 10 invokes static method
getInstance of Calendar to obtain a calendar with the current date
and time. Lines 13-17, 20-22 and 25-26 use this Calendar object in
printf statements as the value to be formatted with conversion
character t. Note that lines 20-22 and 25-26 use the optional
argument index ("1$") to indicate that all format specifiers in the
format string use the first argument after the format string in the
argument list. Using the argument index eliminates the need to
repeatedly list the same argument.

9 // get current date and time


10 Calendar dateTime = Calendar.getInstance();
11
12 // printing with conversion characters for date/time compositions
13 System.out.printf(“%tc\n”, dateTime);
14 System.out.printf(“%tF\n”, dateTime);
15 System.out.printf(“%tD\n”, dateTime);
16 System.out.printf(“%tr\n”, dateTime);
17 System.out.printf(“%tT\n”, dateTime);
18

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

2.20.5 Other Conversion Characters

The remaining conversion characters are b, B, h, H, % and n. These


are described in the table below.

Other conversion specifiers

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).

8 Object test = null;


9 System.out.printf( “%b \n", false );
10 System.out.printf(“%b \n", true );
11 System.out.printf(“%b \n", "Test" );
12 System.out.printf(“%bB\n", test );
13 System.out.printf( "Hashcode of \"hello\" is %h\n", "hello" );
14 System.out.printf( "Hashcode of \"Hello\" is %h \n", "Hello" );
15 System.out.printf( "Hashcode of null is %H \n", test );
16 System.out.printf( "Printing a %% in a format string\n" );
17 System.out.printf( "Printing a new line %n next line starts here" );

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

The exact size of a field in which data is printed is specified by a


field width. If the field width is larger than the data being printed,
the data will be right justified within that field by default. The
programmer inserts an integer representing the field width between
the percent sign (%) and the conversion character (e.g., %4d) in the
format specifier. The code below prints two groups of five numbers
each, right justifying those numbers that contain fewer digits than
the field width. Note that the field width is increased to print values
wider than the field and that the minus sign for a negative value uses
one character position in the field. Also, if no field width is
specified, the data prints in exactly as many positions as it needs.
Field widths can be used with all format specifiers except the line
separator (%n).

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.

// Using precision for floating-point numbers and strings.


7 double f = 123.94536;
8 String s = "Happy Birthday";
9
10 System.out.printf( "Using precision for floating-point numbers\n" );
11 System.out.printf(“\t%.3f\n\t%.3e\n\t%.3g\n\n” , f, f, f);
12
13 System.out.printf( "Using precision for strings\n" );
14 System.out.printf(“\t%.11s\n”, s );

Outputs:

Using precision for floating-point numbers


123.945
1.239e+02
124
Using precision for strings
Happy Birth

94
Java for Beginners

2.19.7 Using Flags in the printf Format String

Various flags may be used with method printf to supplement its


output formatting capabilities. Seven flags are available for use in
format strings as in the next table.

Format string flags

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.

To use a flag in a format string, place the flag immediately to the


right of the percent sign. Several flags may be used in the same
format specifier. The snippet below demonstrates right justification
and left justification of a string, an integer, a character and a

95
floating-point number. Note that line 9 serves as a counting
mechanism for the screen output.

7. // Right justifying and left justifying values.


8 System.out.println( "Columns:" );
9,,,,System.out.println(
"0123456789012345678901234567890123456789\n" );
10 System.out.printf( "%10s%10d%10c%10f\n\n", "hello", 7, 'a', 1.23 );
11 System.out.printf(“% -10s%-10d%-10c%-10f\n”, “hello”, 7, ‘a’,
1.23);

Columns:
0123456789012345678901234567890123456789

hello 7 a 1.230000

hello 7 a 1.230000

2.20.8 Printing numbers with and without the + flag.

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.

1 System.out.printf( "%d\t%d\n", 786, -786 );


2 System.out.printf( “%+d\t%+d\n”, 786, -786);

786 -786
+786 -786

// Using the # flag with conversion characters o and x.


8 int c = 31; // initialize c
9
10 System.out.printf(“%#o\n”, c );

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.

7 //Printing with the 0 (zero) flag fills in leading zeros.


8 System.out.printf(“%+09d\n”, 452 );
9 System.out.printf(“%09d\n”, 452 );
10 System.out.printf(“% 9d\n”, 452 );

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

The next snippet encloses negative numbers in parentheses using the


( flag. Note that the value 50 is not enclosed in parentheses in the
output because it is a positive number.

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)

2.20.9 Printing with Argument Indices

An argument index is an optional decimal integer followed by a $


sign that indicates the position of the argument in the argument list.
For example, lines 20-21 and 24-25 in the previous date code snippet
use argument index "1$" to indicate that all format specifiers use the
first argument in the argument list. Argument indices enable
programmers to reorder the output so that the arguments in the
argument list are not necessarily in the order of their corresponding
format specifiers. Argument indices also help avoid duplicating
arguments. The next code demonstrates how to print arguments in
the argument list in reverse order using the argument index.

7 //Reordering output with argument indices.


8 System.out.printf(
9 "Parameter list without reordering: %s %s %s %s\n",
10 "first", "second", "third", "fourth" );
11 System.out.printf(“Parameter list without reordering: %4$s
%3$s %2$s %1$s\n”, "first", "second", "third", "fourth" );

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

Most literal characters to be printed in a printf statement can simply


be included in the format string. However, there are several
"problem" characters, such as the quotation mark (") that delimits
the format string itself. Various control characters, such as newline
and tab, must be represented by escape sequences. An escape
sequence is represented by a backslash (\), followed by an escape
character. The table below lists the escape sequences and the actions
they cause.

Escape sequence Description


\' (single quote) Output the single quote (') character.
\" (double quote) Output the double quote (") character.
\\ (backslash) Output the backslash (\) character.
\b (backspace) Move the cursor back one position on the
current line.
\f (new page or form Move the cursor to the start of the next
feed) logical page.
\n (newline) Move the cursor to the beginning of the
next line.
\r (carriage return) Move the cursor to the beginning of the
current line.
\t (horizontal tab) Move the cursor to the next horizontal tab
position.

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.

2.20.11 Formatting Output with Class Formatter

So far, we have discussed displaying formatted output to the


standard output stream. What should we do if we want to send
formatted outputs to other output streams or devices, such as a
JTextArea or a file? The solution relies on class Formatter (in
package java.util), which provides the same formatting capabilities
as printf. Formatter is a utility class that enables programmers to
output formatted data to a specified destination, such as a file on
disk. By default, a Formatter creates a string in memory. The next
snippet demonstrates how to use a Formatter to build a formatted
string, which is then displayed in a message dialog.

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

Line 11 creates a Formatter object using the default constructor, so


this object will build a string in memory. Other constructors are
provided to allow you to specify the destination to which the
formatted data should be output. For details, see:

java.sun.com/j2se/5.0/ docs/api/java/util/Formatter.html.

Line 12 invokes method format to format the output. Like printf,


method format takes a format string and an argument list. The
difference is that printf sends the formatted output directly to the
standard output stream, while format sends the formatted output to
the destination specified by its constructor (a string in memory in
this program). Line 15 invokes the Formatter's toString method to
get the formatted data as a string, which is then displayed in a
message dialog.

String static Method format

Note that class String also provides a static convenience method


named format that enables you to create a string in memory without
the need to first create a Formatter object. Lines 11-12 and line 15 in
the above code could have been replaced by

String s = String.format( "%d = %#o = %#^x", 10, 10, 10 );


JOptionPane.showMessageDialog( null, s );

101
TUTORIAL QUESTIONS

1. (a) (i) What are primitive data types?


(ii) List five primitive data types that Java supports.

(b) (i) Itemize the rules of forming variables in Java


programming language.
(ii) Identify the illegal variables in the following list
with reasons:
-121, &ABD, AB12, AB12_ E2_5, Num1, a-
num, 2Num, swing, N, a_Num

(c) One of the reasons why Java is widely accepted as one of


the best programming languages of today is that “Java is
platform independent”. Explain the underlined statement
in not more than two lines.

2. (a) Write Java equivalent expressions for the


following arithmetic expressions.
(i) 2(L + b) + e-h
K2
n
(ii) r – Log(/2)

(iii) Sin2h – Cos2h


mxn

(b) Consider the initial value of i to be 10;


(i) With cogent reasons, what would be the value of i
and n on executing the code snippet below:
int i = 10;
int n = i++%5;

(ii) With cogent reasons, what would be the values of i


and j on executing the code snippet below:
int i = 10;
int j = ++i%5;

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);

If the values of x, y, and z are ‘You’, ‘are’ , and ‘too big’


respectively, show how the print out would look like.

3. (a) State the three principles that Java uses to


undertake automatic conversion of data types in
an arithmetic expression.
(b) Suppose x is a float type variable with value 5.0 and m, n
are integer variables with values 5 and 6 respectively.
What values will be stored in variables of the left side of
the following assignment statements:
(i) x = m/n*x;
(ii) n = m/n*x;
(iii) x = (float)(m/n*x);

4. Write a program to compute the area and perimeter of any


plane shape and format your outputs to only two decimal
places.

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.

Type of Control Meaning Control


Structures
Sequential control The program runs All the programs
from line one to the we have been
last line without writing before
branching or testing now are examples
for any condition of this structure
Selection/Branching One or more Simple if, If –
Conditions are tested. else, else if, goto,
Statements are nested if,
executed upon arithmetic if,
fulfilment of the Switch, break and
conditions. continue
structures.
Looping/Repetition/Iteration Statements are For, while and do-
repeatedly executed while loops
either on fulfilling a
condition or for some
number of times.

104
Java for Beginners

You can use control flow statements in your programs to


conditionally execute statements, to repeatedly execute a block of
statements, and to otherwise change the normal, sequential flow of
control. For example, in the following code snippet, the if statement
conditionally executes the System.out.println statement within the
braces, based on the return value of isUpperCase ( ).

Character.isUpperCase(aChar):
char c;
...
if (Character.isUpperCase(aChar)) {
System.out.println("The character " + aChar + "
is upper case.");
}

The Java programming language provides several control flow


statements, which are listed in the following table.

Statement Type Keyword

Looping / repetition while, do-while , for

Decision making /
if-else, switch-case
selection

Exception handling try-catch-finally, throw

Branching break, continue, label:, return

Note: Although goto is a reserved word, currently the Java


programming language does not support the goto statement.

3.1 The if/else Statements

The if statement enables your program to selectively execute other


statements, based on some criteria. For example, suppose that your

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);
}

This is the simplest version of the if statement: The block governed


by the if is executed if a condition is true.

Generally, the syntax of simple if statement can be written like this:

if (logical expression) {
statement(s)
}

The statement(s) will only be executed only if the logical


expression evaluates to true. If the expression is not rtue, the
control simply passes to the next statement following the
statement(s) block, { …. } and continues downwards from there.

As another example:

if (x < 50)
System.out.println(“The score is below cut off”);

What if we want to perform a different set of statements if the


expression is false? We use the else statement for that. Consider
another example. Suppose that your program needs to perform
different actions depending on whether the user clicks the OK button
or another button in an alert window. Your program could do this by
using an if statement along with an else statement:

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
}

The else block is executed if the ‘if’ part is false.

The next program segment illustrates this:

System.out.println(“Enter the grade: “);


String X = input.readLine();
int grade = Integer.parseInt(X);
if (grade >= 50)
System.out.println(“The grade is above cut off point “);
else
System.out.println(“Grade below cut off point “);

Another form of the else statement, else if, executes a


statement based on another expression. An if statement can
have any number of companion else if statements but only
one else. Following is a program, IfElse that assigns a grade
based on the value of a test score: an A for a score of 90% or
above, a B for a score of 80% or above, and so on:

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);
}
}

The output from this program is:

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.

As another example, consider the following code on quadratic


equation:

The general model for quadratic equations is ax2 + bx + c = 0, where


a, b and c are the variables that are used to determine the values of x;
called the roots of the equation. Using the formula method

-b  d
X =
2a
d = discriminant = b2 – 4ac

if d = 0, only one roots exists with value –b/2a


if d < 0, the roots are complex and if d >0, there are two real roots
and the formula stated above is used to compute the roots.

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);
}
}

The sample output is shown in the next figure

109
Ternary Operator ?:

The Java programming language supports an operator, ?:, that is a


compact version of an if statement. It is also called ternary operator.
The general syntax of this operator is
(exp)?a:b

This means if the expression in the bracket evaluates to true then


executes statement a else execute statement b. The statements a and
b can be simple ones or complex especially if they are for large
program codes.

Consider the program segment below:

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:

System.out.println("The character " + aChar + " is " +


(Character.isUpperCase(aChar) ? "upper" : "lower") +
"case.");

The ?: operator returns the string "upper" if the isUpperCase method


returns true. Otherwise, it returns the string "lower". The result is
concatenated with other parts of a message to be displayed.

Another example:

System.out.println(“Enter the grade: “);


String X = input.readLine();
int grade = Integer.parseInt(X);
System.out.println(“Grade is” + (grade >= 50)? + “above cut off “: “below
cut off”);

Can you guess what output will be printed out from the above
program segment if x were to be 47?

Using ?: makes sense here because the if statement is secondary to


the call to the println method. Once you get used to this construct, it
also makes the code easier to read.

3.2 The switch Statement

We use the switch statement to conditionally perform


statements based on an integer expression. Following is a sample
program, SwitchDemo that declares an integer named month whose
value supposedly represents the month in a date. The program
displays the name of the month, based on the value of month, using
the switch statement:

111
E12:

public class SwitchDemo {


public static void main(String[ ] args) {
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;
}
}
}

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

Deciding whether to use an if statement or a switch statement is a


judgment call. You can decide which to use, based on readability
and other factors. An if statement can be used to make decisions
based on ranges of values or conditions, whereas a switch statement

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);
}
}

The output from this program is:


Number of Days = 29

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;

case 2: System.out.println("You have chosen Square");


System.out.println("Enter its length");
l = input.nextFloat();
a = l * l;
p = 4.0 * l;
System.out.println("Area = "+ a +" Cm"+ "\nPerimeter =
"+ p + " Cm-square");
System.out.println();
break;

case 3: System.out.println("You have chosen Circle");


115
System.out.println("Enter its radius ");
float r = input.nextFloat();
a = Math.PI * r * r;
p = 2.0 * Math.PI * r;
System.out.printf("Area = %.2f Cm \nPerimeter = %.2f
Cm-square", a ,p);
System.out.println();
break;

case 4: System.out.println("You have chosen Parallelogram");


System.out.println("Enter its Height");
float h = input.nextFloat();
System.out.println("Enter one of its slanting parallel sides
");
l = input.nextFloat();
System.out.println("Enter its base");
b = input.nextFloat();
a = b * h;
p = (2.0 * l) + (2.0 * b);
System.out.println("Area = "+ a +" Cm"+ "\nPerimeter =
"+ p + " Cm-square");
System.out.println();
break;

case 5: System.out.println("You have chosen Triangle");


System.out.println("Enter its height");
h = input.nextFloat();
System.out.println("Enter first slanting height ");
float l1 = input.nextFloat();
System.out.println("Enter second slanting height");
float l2 = input.nextFloat();
System.out.println("Enter its base");
b = input.nextFloat();
a = 0.5 * b * h;
p = l1 + l2 + 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;

default: System.out.println("Wrong option chosen, Program


terminates... ");
System.out.println();
System.exit(0);
} //end switch

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 (initialization; termination/continuation criterion; increment) {


statements;
}

The initialization is an expression that initializes the loop. It is


executed once at the beginning of the loop. The
termination/continuation criterion determines when to terminate the
loop. It in essence gives the conditions to continuing the loop until
when the loop will terminate. This expression is evaluated at the top
of each iteration of the loop. When the expression evaluates to false,
the loop terminates. Finally, increment is an expression that gets
invoked after each iteration through the loop. All these components
are optional. In fact, to write an infinite loop, you omit all three
expressions:

for ( ; ; ) {

// infinite loop ...

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);
}
}

The output from this program is: Sum = 55

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();
}
}

Note: The increment is i += 2 or i = i + 2 and not i +2!

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.

Exercise: Can you modify the above program segment to compute


the sum of all even numbers from 1 to n?

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

JOptionPane.showMessageDialog(null, "Sum of " + count +


" data added is " + sum, "Results",

120
Java for Beginners
JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}

Here are some screen shots from the program:

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.

The general syntax for two nested for-loops is:

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.

As an exercise, implement a program to compute means of five


experiments’ data with each experiment repeated 3 times each.

3.4 The while and do-while Statements

We use a while statement to continually execute a block of


statements while a condition remains true. It is somehow regarded as
a pre-conditional testing control. The general syntax of the while
statement is:

while (expression) {
Statements;
}

First, the while statement evaluates expression, which must return a


boolean value. If the expression returns true, then the while
statement executes the statement(s) associated with it. The while
statement continues testing the expression and executing its block
until the expression returns false. In this wise, we say a while loop is
a pre-test looping mechanism, since it will first of all test the
condition before executing the loop. The control moves to the next
statement after the while statements’ block when the expression is
no more valid and execution continues from there downwards.

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);

The example program below, called whileDemo, also uses a while


statement to step through the characters of a string, appending each
character from the string to the end of a string buffer until it
encounters the letter g.

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

Answers: (i) 11 (ii) 0, Give reasons for these answers

126
Java for Beginners
3.4.2 Do-while

The Java programming language provides another statement that is


similar to the while statement-the do-while statement. It is often
regarded as a post-conditional testing control. The general syntax of
the do-while is:

do {
statement(s)
} while (expression);

Instead of evaluating the expression at the top of the loop, do-while


evaluates the expression at the bottom. Thus the statements
associated with a do-while are executed at least once. This structure
is post-conditional testing technique, just like Repeat-Until in some
languages like Pascal. Here's the previous program rewritten to use
do-while and renamed to DoWhileDemo:

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

Answers: (i) 11 (ii) 18 (iii) infinite looping. Explain the


reasons for these answers

128
Java for Beginners
3.5 Exception Handling Statements

The Java programming language provides a mechanism known as


exceptions to help programs report and handle errors. When an error
occurs, the program throws an exception. What does this mean? It
means that the normal flow of the program is interrupted and that the
runtime environment attempts to find an exception handler--a block
of code that can handle a particular type of error. The exception
handler can attempt to recover from the error or, if it determines that
the error is unrecoverable, provide a gentle exit from the program.
Three statements play a part in handling exceptions:
 The try statement identifies a block of statements within
which an exception might be thrown.
 The catch statement must be associated with a try
statement and identifies a block of statements that can
handle a particular type of exception. The statements are
executed if an exception of a particular type occurs
within the try block.
 The finally statement must be associated with a try
statement and identifies a block of statements that are
executed regardless of whether or not an error occurs
within the try block.
Here's the general form of these statements:

try {
statement(s)
} catch (exceptiontype name) {
statement(s)
} finally {
statement(s)
}

This has been a brief overview of the statements provided by the


Java programming language used in reporting and handling errors.
However, other factors and considerations, such as the difference
between runtime and checked exceptions and the hierarchy of
exceptions classes, which represent various types of exceptions, play
a role in using the exception mechanism.

129
3.6 Handling Errors with Exceptions

If there's a golden rule of programming it's this: Errors occur in


software programs. This we know. But what really matters is what
happens after the error occurs. How is the error handled? Who
handles it? Can the program recover, or should it just die?

3.7 What’s an Exception and Why Do I Care?

The Java language uses exceptions to provide error-handling


capabilities for its programs. An exception is an event that occurs
during the execution of a program that disrupts the normal flow of
instructions.

3.8 Your First Encounter with Java 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:

InputFile.java:11: Exception java.io.FileNotFoundException must be


caught, or it must be declared in the throws clause of this method.

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.

3.9 Throwing Exceptions

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

3.10 Runtime Exceptions – The Controversy

Although Java requires that methods catch or specify checked


exceptions, they do not have to catch or specify runtime exceptions,
that is, exceptions that occur within the Java runtime system.
Because catching or specifying an exception is extra work,
programmers may be tempted to write code that throws only runtime
exceptions and therefore doesn't have to catch or specify them. This
is "exception abuse" and is not recommended. The last section in this
lesson, explains why.

3.11 Branching Statements

The Java programming language supports three branching


statements:
 The break statement
 The continue statement
 The return statement
The break statement and the continue statement, which are covered
next, can be used with or without a label. A label is an identifier
placed before a statement. The label is followed by a colon (:):

statementName: someJavaStatement;

You'll see an example of a label within the context of a program in


the next section.

3.11.1 The break Statement

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

The unlabeled form of the break statement is used to terminate the


innermost switch, for, while, or do-while; the labeled form
terminates an outer statement, which is identified by the label
specified in the break statement. The following program,
BreakWithlabelDemo, is similar to the previous one, but it searches
for a value in a two-dimensional array. Two nested for loops traverse
the array. When the value is found, a labeled break terminates the
statement labeled search, which is the outer for loop:

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");
}

}
}

The output of this program is: Found 12 at 1, 0

This syntax can be a little confusing. The break statement terminates


the labeled statement; it does not transfer the flow of control to the
label. The flow of control transfers to the statement immediately
following the labeled (terminated) statement.

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;

for (int i = 0; i < max; i++) {


//interested only in p's
if (searchMe.charAt(i) != 'p')
continue;

//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");
}
}

Here is the output from this program: Found 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:

If i is divided by j and the remainder equals zero (0), this means i is


not prime. The continue L1; statement makes the control to jump out
of j – loop and go to for-loop labeled L1. The current iteration of i is
skipped; i is then incremented to the next value. This construct

136
Java for Beginners
works like GOTO statement found in other languages like
FORTRAN. But it only works with nested loops.

3.12 The return Statement

The last of Java's branching statements is the return statement. You


use return to exit from the current method. The flow of control
returns to the statement that follows the original method call. The
return statement has two forms: one that returns a value and one that
doesn't. To return a value, simply put the value (or an expression that
calculates the value) after the return keyword:

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

1. Study the program snippet below:


.
.
int numAdd = 0; //line1
int count = 1; //line2
System.out.print(‘Enter the first number’); //line3
num = input.readLn( ); //line4
int Num = Integer.parseInt(num); //line5
while num < = 0 //line6
numAdd + = num; //line7
count ++ //line8
System.out.println('Next Number?’) //line9
num = input.readLn( ); //line10
int Num = Integer.parseInt(num); //line11
} //line12
.
.

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.

(2) Give an example of a Java statement to illustrate each of


these control structures
(a) If Statement
(b) Switch Statement
(c) Continue Statement.

3. A man borrows N3000 from a bank at an interest rate of


1.5% per month. He pays N250 at the end of each month.
The amount he owes (AM) at the end of the each month is
calculated thus:
AM = P + (1.5 /100 * P) – 250
Where P = the Principal amount left to be paid.

Write a program that will print the amount he owes each


month and the number of months it will take him to pay all
the debt.

4. Write a program to add numbers from 1 to N together, such


that if the next number to be added is divided by 2 and the
remainder is not equal to zero, it should be added up, else it
should be discarded from the summation. The use of
continue statement is essential in this program.

5. The model equations for simultaneous equation in two


unknowns (x and y) are given by

138
Java for Beginners
ax + by = c ……………..eq.(1)
dx + ey = f ……………..eq.(2)

Write a program to compute the values of the unknowns (x


and y). NB: solve for x and y by substitution method. a, b, c,
d, e, and f are variable values that need to be input into the
program.

6. Write a program to compute the roots of any quadratic


equation whose model equation is ax2 + bx + c = 0, using the
formula method,
x = (-b  (b2 – 4ac))/(2a).

7. Suppose the initial values of x, y, and m are


15, 3 and 15 respectively; what is the output of each of the
program segments below: Justify your results.

(i) for (int j = x; j >= 0; j -= 5)


System.out.println(“ j = ” + j);

(ii) while (x < m) {


++x;
System.out.print(“x = ” + x);
}

(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++;

(ii) The following code is expected to sum 1 to 10:

139
float sum = 0;
for (int k = 1; k >=10; k ++)
sum = k;

(iii) for (k = 0.1; k<=10; k += 5)


System.out.print(k);

(iv) maximum = Math.max(a, b, Math.max(c,d));

(v) double array = new double[5];

(b) Write a java program that will accept any three


numbers and print out the numbers in a sorted order.

9. At Lever Brothers Nigeria Limited, each staff member is


given a monthly basic salary commensurate with his/her
salary grade level. In addition, each staff is given 10% of
basic salary as Transport allowance, 15.5% of basic as
Housing Allowance and N500 flat as meal subsidy. Also, if
a staff has spent over 10 years in the company, he/she is
given 2% of his basic salary as ‘long serving staff
allowance’. Write a java program to implement the above
pay-roll policy, assuming 50 staff numbers in all.

10. There were twenty experimental set-ups in a Chemistry


Laboratory. Each of the experiments was repeated four
times. Implement a program that captures the results from
the experiments and reports the mean values for each of the
experiments. Hint: Use Nested for loops.

11. The are n stores in a big marketing company. Each of the


stores has m departments. Each department has daily sales
per week. Write a program to compute the (i) total sales per
week for the company, (ii) total sales per week for each each
of the stores and (iii) total sales per week for each of the
departments.

140
Java for Beginners

Java Arrays and Vectors


4.0 Introduction

An array is a group of variables, all of the same data type that is


referred to by a single name. The values in the group occupy
contiguous locations in the computer memory. Each element in the
array is identified by the array name and a subscript pointing to the
particular location within the array.

We have two types of array – one (single) and multi-dimensional


arrays. Let us explain the term dimension before we go on to the
lecture properly. Dimension has to do with the number of objects or
entities a data is related to. For instance, if we say the score of a
particular student. In this case, the score data is related to only a
particular student. But if we now say the score of a particular student
in a particular course. Then, the same score data is related to a
student and course. This is two-dimension in this case. We could go
ahead to relate the same score to student, course and session, making
a three dimension of the score data. Another example is the rain
volume in a particular day. This is one dimension. Rain volume in a
particular day in a particular week. This is two-dimension. Now, rain
volume in a particular day, in a particular week, in a particular
month, (making three-dimension), in a particular year, making four-
dimension.

141
The following is a logical representation of a single dimensional
array in memory.

A(1) A(2) A(3) A(4) A(5)

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).

In Java, the elements are numbered with subscripts starting from 0,


and can be referenced by their number using the subscript operator
[ ].

For example, the following depicts the scores of 5 students in a test.

SCORE
20 40 10 50 30

Subscript 0 SCORE[1] SCORE[4]


SCORE[0]

The name of the Array is SCORE, 20 is stored at


subscript/index 0 and 30 is stored at subscript 4

4.1 Types of Arrays

1. One dimensional array – with a single row or column


2. Two dimensional Array – with more than one row and
column
3. Character Arrays
4. String arrays

142
Java for Beginners
4.2 Creating a One-dimensional Array

The general syntax for creating an array is:

element-type [ ] arrayName; // declares the array


arrayName = new element type[n] // allocates storage for n elements
As with single objects, both the declaration and allocation can be
combined in a single declaration with initialization as shown below:

element-type[ ] arrayName = new element-type[n]

element-type could be any of the primitive data type such as int,


float, double, char etc.

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];

4.3 Reading in Data into a One-dimensional


Array
for-loop is commonly used to achieve this. The following code
snippet reads in data into a one dimensional array:

for (int i = 0; i < arrayName.length; i++) {


float arrayName[i] = Float.parseFloat
(JOptionPane.showInputDialog(“Enter data for subscript
“+ (i+1) ));
}

Comments: when i is 0, the pointer is at location 0 of the array.


What would be printed on screen is Enter data for subscript 1.
Ideally it should be subscript 0, but we have done an arithmetic
operation in the string parameter in the JOptionPane, (i + 1). This is
only done at the level of the user of the program, who does not know

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.

4.4 Summing all the Data in a One-dimensional Array


The following code snippet sums all the data in a one-dimensional
array;
float sum = 0; //sum serves as an accumulator
for (int i = 0; i < arrayName.length; i++) {
sum += arrayName[i];
}

4.5 Reversing the elements of an array

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)));

// printing the original array a


System.out.println("Original array .....\n");
for (int l = 0; l < n; l++ )

144
Java for Beginners
System.out.print(a[l] + "\t");

System.out.println("\n");

// reversing the array a


int i = 0, j = n - 1;
while ((i != j)) {

int temp = a[i];


a[i] = a[j];
a[j] = temp;
i++;
j--;
if (j < i)
break;
}

// Printing the array in reverse order


System.out.println("Reversed array ..... \n");
for (int k = 0; k < n; k++ )
System.out.print(a[k] + "\t");

//Closing the program


System.out.println("\n");
System.exit(0);
}
}

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 = {44, 88, 55, 33};

This single line is equivalent to the following six lines

int [ ] c;
c = new int [4];
c[0] = 44;
c[1] = 88;
c[2] = 55;
c[3] = 33;

4.7 Two-dimensional Arrays


A two-dimensional array looks like a matrix as shown below:

34 23 24
24 56 13
15 10 19

The following are therefore the features of a two-dimensional array


 It uses 2 subscripts; [row][column]
 It has grid of rows and columns, with the 1st subscript locating
the row and the 2nd subscript locating the column.
 Java sees a two-dimensional array as a big array containing
small arrays. Each row forms an array of the whole array.

For example,

int [ ][ ] a = new int [7][9];

The above declares a two-dimensional array a of 7 rows and 9


columns. The row number is specified first followed by the column
number.

147
To assign a value to a location in the array:

a[0][2] = 50;

assigns 50 to the element in row 0 column 2, (1st row, 3rd column)

4.7.1 Reading Data into a Two-dimensional


Array

The following program snippet would achieve this:

for (int i = 0; i < a.length; i++) {


for (int j = 0; j < a[i].length; j++) {
System.out.println(“Enter data for subscript [ “ +
i + “,” + j + “]”);
String data = input.readLine();
float a[i][j] = Float.parseFloat(data);
}
}

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.

As an illustration, consider the following program

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

//Getting the number of rows and columns for the 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"));

// Giving the array the number of rows and columns

score = new float[r][c];


float sum = 0;

// Data capturing into the array


for (int i = 0; i < r; i++){ //Outer loop for rows
for (int j = 0; j < c; j++) { // Outer loop for columns
score[i][j] = Float.parseFloat(JOptionPane.
showInputDialog("Enter data for row" +
(i + 1) + "and column" + (j + 1)));
sum += score[i][j]; //Accumulating data into sum
} //Ending innermost for loop
}//Ending outermost for loop

// Computing the average score for the whole data


double mean = sum/(r*c);
String output = "Average for all students = " + mean + "\n";

// Computing the average score for each student


//Note the position of the initialized accumulator sum
for (int i = 0; i < r; i++) {
sum = 0;
for (int j = 0; j < c; j++) {
sum += score[i][j];
} //Ending innermost for loop for a row
double avg = sum/c;
// rounding up avg to 2 places of decimals
DecimalFormat twoDigits = new DecimalFormat("0.00");
AvgRnd = twoDigits.format(avg);
output += "Average for student" +(i+1)+ " = " +
AvgRnd + "\n";

149
} //Ending outermost loop to process another row of data

//Printing the final result


JOptionPane.showMessageDialog(null, output,
"Results…", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
} //Ending the main method
} // Ending the class array.

Sample Output Screen Shots:

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.

Course1 Course2 Course3 Course4 Course5

Student1 45 67 90 76 45
Student2 60 69 59 40 47
Student3 79 58 60 32 57
Student4 56 34 70 36 49

(v) In computing the average score of each student, the


accumulator sum is initialized to 0 and placed in between
the two for loops. Can you guess a reason for this? This is
done so that when the innermost for-loop is completed and
average for that row of data computed and reported, then the
accumulator will be re-initialized back to zero for the next
set of data for another student. Otherwise, the previous value
in the accumulator sum will be carried over to the next set of
iteration of the outermost for-loop.

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?

A two dimensional array is actually an array of arrays. Each row is a


separate array. Consider the program below, which illustrates this
point.

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

As an array, the object ‘a’ has length 7. That’s because it is really an


array of 7 rows. The first of these row arrays is a[0]; having length 9.
Each row has 9 elements. We can also initialize a 2-dimensional
array like a 1-dimensional array. The only difference is that since it
is an array of arrays; its initialization list has to be a list of
initialization lists. For example, consider the case of a ragged 2-
dimensional array below. Ragged because the lengths of its rows
vary.

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.

Processing 3-dimensional array is similar. Three nested for loops are


used:

for (int i = 0; i < a.length; i++){ // plane i


for (int j = 0; j < a[i].length; j++) { // row j
for (int k = 0; k < a[i][j].length; k++) { // column K.
// process a[i][j][k] element

The element is analogous to a single letter on a line on a page in a


book: a[i][j][k] would represent character number k on line number j
on page number i, a[i][j] would represent line number j on page

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].

Exercise: Multiplication of Matrices


Two matrices Amn and Bnp could be multiplied to produce the third
matrix Cmp. The ijth element of C is computed as follows:
Cij = ∑nk=1 Aik Bkj for i = 1, …., m and j = 1, . . , p

The following algorithm may be used to solve this problem:

for (i =1; i <= m; i++) {


for (j =1; j < = p; j++) {
C[i][j] = 0;
for (k =1; k < = n; k++) {
C[i][j] = C[i][j] + A[i][k] + C[k][j];
}
}
}

Exercise: Translate this algorithm into a java code.

E32: Computing CGPA for Students

//program to compute cgpa for a number of students

import javax.swing.*;
import java.text.DecimalFormat;

public class CGPA {


public static void main(String args[]){
// DECLARATION AND INITIALIZATIONS

DecimalFormat onedigit = new DecimalFormat("0.0");


JTextArea output = new JTextArea(22,50);
JScrollPane scrollbar = new JScrollPane(output);

154
Java for Beginners
String result="";
int studnum, coursenum, i,j,cunit=0;
String studNum, courseNum, courseUnit;

// GETTING THE REQUIRED DATA

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);

int unitAry[ ]=new int[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];
}

int scoreAry[ ] [ ]= new int[studnum] [coursenum];


int GPary[ ] [ ] = new int[studnum] [coursenum];
int WGPary[ ] [ ] = new int[studnum] [coursenum];
int CWGPary[ ] = new int[studnum];
String nameAry[ ] = new String[studnum];
double CGPA;

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);

//DETERMINING GP FOR EACH SCORE

{
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 */

public class matrix {


public static void main(String [ ] args){
// Dealing with Matrix X first…
String data = JOptionPane.showInputDialog ("Enter data for
row, r for the matrix X: ");
int rno = Integer.parseInt(data);
data = JOptionPane.showInputDialog ("Enter data for column,
c for the matrix X ");
int cno = Integer.parseInt(data);
double [ ][ ] matX = new double[rno][cno];
// Entering data for matrix X
for (int i = 0; i < rno; i++) {
for (int j = 0; j < cno; j++) {
String value = JOptionPane.showInputDialog ("Enter data for
matX[" +i+ ","+j+"]: ");
matX[i][j] = Double.parseDouble(value);
}
}

// Dealing with Matrix Y next…


data = JOptionPane.showInputDialog ("Enter data for row, r
for the matrix Y: ");
rno = Integer.parseInt(data);
data = JOptionPane.showInputDialog ("Enter data for column,
c for the matrix Y ");
cno = Integer.parseInt(data);
double [ ][ ] matY = new double[rno][cno];
// Entering data for matrix Y
for (int i = 0; i < rno; i++) {
for (int j = 0; j < cno; j++) {
String value = JOptionPane.showInputDialog ("Enter data for
matY[" +i+ ","+j+"]: ");
matY[i][j] = Double.parseDouble(value);

159
}
}

// Prints out Matrix X…


System.out.println("Given that matrix X = ");
for (int i = 0; i < rno; i++) {
for (int j = 0; j < cno; j++) {
System.out.print(matX[i][j] + " ");
}
System.out.println( );
}
// Prints out Matrix Y…
System.out.println(" and matrix Y = ");
for (int i = 0; i < rno; i++) {
for (int j = 0; j < cno; j++) {
System.out.print(matY[i][j] + " ");
}
System.out.println( );
}
System.out.println();
// validates the condition for matrix addition and subtraction
if (rno != cno)
System.out.println("Matrix addition not feasible");
else {
// begin addition of the matrices
double [ ] [ ] matAdd = new double [3][3];
System.out.println( "The addition of the matrices X and Y is :");
System.out.println();
for (int i = 0; i < matX.length; i++) {
for (int j = 0; j < matX[i].length; j++) {
matAdd[i][j] = matX[i][j] + matY[i][j];
System.out.print(matAdd[i][j] + " ");
}
System.out.println( );
}
System.out.println();
// Ends matrices addition, begin matrices subtraction
System.out.println( "The difference between matrices X and Y is :");
System.out.println();
double [ ] [ ] matSub = new double [3][3];
for (int i = 0; i < matX.length; i++) {

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

// prints error message for unsatisfied if condition

else
System.out.println("This matrices cannot be multiplied together");

// Transpose the matrix X

double matTransp [ ] [ ] = new double[rno][cno];


System.out.println("The transpose of matrix X is: " );
for (int i = 0; i < rno; i++) {
for (int j = 0; j < cno; j++) {

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:

Given that matrix X =


3.0 4.0 6.0
2.0 4.0 7.0
8.0 6.0 5.0
and matrix Y =

5.0 6.0 7.0


2.0 3.0 4.0
1.0 7.0 8.0

The addition of the matrices X and Y is :


8.0 10.0 13.0
4.0 7.0 11.0
9.0 13.0 13.0

162
Java for Beginners

The difference between matrices X and Y is :

-2.0 -2.0 -1.0


0.0 1.0 3.0
7.0 -1.0 -3.0

The product of the matrices X and Y is :

29.0 72.0 85.0


25.0 73.0 86.0
57.0 101.0 120.0

The transpose of matrix X is:


3.0 2.0 8.0
4.0 4.0 6.0
6.0 7.0 5.0

Bye- bye to the user

Exercise: Enhance the matrices program to include determinant,


adjoint and inverse of a matrix. Read up these matrices operation
from a Mathematics textbook.

4.8 Sorting an Array

Java provides a predefined sort method in its Application


Programming Interface (API).

The Arrays.sort(arrayName) method could be invoked on a one-


dimensional array in order to sort it in ascending order. Note that
java.util.* must be imported to your program before the method
could be used. Example program below illustrates the use of the
method.

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"));

int [ ] a = new int[n];

for (int i = 0; i < a.length; i++)


a[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter
data for column" + (i+1)));

//printing original array


System.out.println("Original array data ..\n");
for (int i = 0; i < a.length; i++)
System.out.print("\t" + a[i]);

System.out.println( );
// Sorting the array using a predefined sort procedure
Arrays.sort(a);

//Printing sorted array ..


System.out.println("Sorted array data ..\n");
for (int i = 0; i < a.length; i++)
System.out.print("\t" + a[i]);

System.out.println( );
System.exit(0);
}
}
Sample Output

164
Java for Beginners
Practical Exercise

The method, Arrays.sort(arrayName) can only sort an array in


ascending order, implement a program that will sort an array in
descending order using bubble sorting algorithm.

4.9 Java Vectors

Vectors are expandable and contractible array of objects. The size of


a vector can change at will by the programmer. Below are some of
the operations that can be performed on vectors:

4.9.1 Declaring a Vector

The following simple line of code would create a vector for you:

Vector v = new Vector();

Note that V in Vector is upper-case. This constructor creates a


default vector containing no elements. Two technical terms
commonly used with vectors are size and capacity. The size of a
vector is the number of elements currently stored into it. Whereas
the capacity of a vector is the amount of memory allocated to hold
elements, and it is always greater than or equal to the size.

To specify the capacity of a vector, we declare the vector as:

Vector v = new Vector(25);

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:

Vector v = new Vector(25,5);

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.

4.9.2 Accessing Elements in a Vector

Just like in arrays, we use the square brackets (“[ ]”) to achieve this
operation in vectors.

4.9.3 Adding Elements to the Vector

We use the add() method to add an element to a vector. For example,


the codes below shows how to add some strings to the vector v:

v.add(“Akinola”);
v.add(“S. O.”);
v.add(“Ibadan”);

4.9.4 Retrieving the Last Element From a Vector

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

The get( ) method helps us to do this:

String s1 = (String)v.get(0);
String s2 = (String)v.get(2);

Because vectors are zero-based in indexing, the first statement


retrieves “Akinola” and the second retrieves “Ibadan”.

4.9.6 Add and remove elements at a particular index

v.add(1, “Solomon”);
v.add(0, “Olalekan”);
v.remove (3);

The first statement inserts “Solomon” at index 1, between


“Akinola” and “S. O.” strings. The second statement inserts
“Olalekan” at index 0, which happens to be the beginning of the
vector. All existing elements will be moved up to accommodate the
new elements inserted in the appropriate positions.

The resulting vector will look like below:

 Olalekan
 Solomon
 Akinola
 S. O.
 Ibadan

The call to remove( ) at index 3 in line 3 will cause “S. O.” to be


removed from the vector. Therefore, the final list in the vector will
now be:

167
 Olalekan
 Solomon
 Akinola
 Ibadan

Removing the element based on the element itself rather than on an


index can be achieved via the statement below:

v.removeElement(”S. O.”);

4.9.7 Overwriting elements at a particular index in a


Vector

The following statement will change “Solomon” to


“Olasunkanmi” in the vector v using the set() method.

v.set(1, “Olasunkanmi”);

4.9.8 Deleting all elements from a Vector

Use the following code to clear all the elements from the vector v.

v.clear();

4.9.9 Searching for a Particular Element in a Vector

For instance, to check if “Ade” is in the vector list, we write

boolean isThere = v.contains(“Ade”);

To find the index of a particular element, we write

168
Java for Beginners
int i = v.indexOf(“Akinola”);

The indexOf returns the position of “Akinola” in the vector if it is


actually there, else it returns -1.

Tutorial Questions

1. Write a program segment to compute the average value of


all data stored in even positions (2, 4, 6, …) inside a one-
dimensional array, assuming data has been stored into the
array initially.

2. Write a Java program that reads integers from keyboard into


a two-dimensional irregular array shown below and write
them out in the order k, j, i, h, g, f, a, b, c, d, e.

e d c b a
f
g h i

Weather conditions in some regions in Nigeria were studied and


the following data were obtained:

RegionId State Temp. Rainfall Pressure


o
C (mm3) (bar)
SW01 Oyo 23.8 5.2 3.0
SW02 Ogun 28.5 6.8 5.9
SW03 Lagos 20.5 12.7 4.8
SW04 Ondo 23.7 10.6 2.8
SW05 Ekiti 26.6 7.8 2.9

Use this data to answer questions 3 and 4.

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.

4. Assuming the Rank Correlation Coefficient Rc


formula is given by

(X – X)(Y – Y)
Rc =
(X – X)2 (Y – Y)2

where Y and X are means

Write a program to compute Rc for temperature and rainfall


in the data given above.

5. (a) A linear search compares each element of an array with a


search key. Write a java code snippet that will return
“found” with the index of an element if found in the array
and “Not found” otherwise.
(b) Extend the program in 5(a) to compute the sum of all
data which are in even indexes (2, 4, 6…) in an array.

(c) Extend the program in 5(a) to reverse all the elements in


the array; such that element in the last index will now
occupy the first index in that order.

6. Consider the following code snippet:

int[ ] score = new int[10];


int sum = 0;
for (int i = 0; i < 10; i++) {
if (score[i] % 2 != 0)
sum += score[i];
}
System.out.println(“Sum added so far = “ +
sum);

170
Java for Beginners

(a) Summarize what the program is doing.


(b) Suppose the following data were supplied to the
program, 1, 3, 2, 5, 4, 8, 9, 10, 6, 7; what would
be the final output from the program?

171
5

Java Methods
(Subprograms)
5.0 Introduction

Methods are techniques employed for breaking large programs into


small functional modules. It is popularly called functions in some
languages. These modules in java are called methods and classes.
There are some built-in methods and classes such as mathematical
calculations, string manipulation, error checking, etc. Methods are
written to define specific tasks that may be used at any points in a
program.

A method is invoked by a method call. A method call is


characterized by its name and the information (arguments) that the
called method need to do its task. When the method call completes,
the method either returns a result to the calling method (or caller) or
simply returns control to the calling method. We can then infer from
this fact that the caller is not interested in the way the called method
will perform the job given to it and the called method can also call
another method to do some job for it. In the following assignment
statements;

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.

Methods in Java could be programmer-declared or prepackaged. The


prepackaged methods are available in the Java Application
Programming Interface Java API or Java Class Library. The java
API provides a rich collection of classes that contain methods for
performing common mathematical calculations, string
manipulations, character manipulations, input/output operations,
error checking and many other useful operations. Methods allow the
programmer to modularize a program by separating its task into self-
contained functional units. The actual statements implementing the
methods are written only once and are hidden from other methods.

5.1 Advantages of Using Methods in Programs

(1) Program manageability: Methods and classes


in java make program development more manageable.

(2) Software reusability: Using existing methods and classes as


building blocks to create new programs is one of the today’s
programming paradigms. We create programs from
standardized methods and classes rather than by building
customized codes. For example, in earlier programs, we did
not have to define how to convert strings to integers and
floating-point numbers; Java provides these capabilities in
class Integer (static method parseInt) and class Double (static
method parseDouble), respectively.

(3) Reduction in code repetition: Repeating codes in programs is


highly reduced using methods. Packaging code as a method
allows a program to execute that code from several locations in a
program simply by calling the method.

(4) Ease of program maintenance and debugging: Methods


make programs easier to debug and maintain.

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.

5.2 The Math-Class Methods

The table below summarizes some of the predefined methods in the


Math class:

Method Description Example


abs(x) Absolute value of x abs(23.7) = 23.7,
abs(-20.5) = 20.5
ceil(x) Rounds x to the smallest ceil(9.2) = 10.0
integer not less than x ceil(-9.8) = -9.0
cos(x) Cosine of x (x is in radians) cos(0.0) = 1.0
exp(x) Exponential method ex exp(1.0) = 2.71828
floor(x) Rounds x to the largest floor(9.2) = 9.0
integer not greater than x floor(-9.8) = -10.0
log(x) Natural logarithm of x, (base log(Math.E) = 1.0
e)
max(x,y) Larger value of x and y max(2.3, 12.7) = 12.7
max(-2.3, -12.3 = -2.3
min(x,y) Smaller value of x and y min(2.3, 12.7) = 2.3
pow(x,y) X raised to the power of y pow(2.0, 3.0)= 23 = 8
(Xy)
sin(x) Sine of x (x is in radians) sin(0.0) = 0
sqrt(x) Square root of x sqrt(900.0) = 30
tan(x) Tangent of x, (x is in tan(0.0) = 0
radians)

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);

Class Math also declares two commonly used mathematical


constants: Math.PI and Math.E. The constant Math.PI (3.14159…)
of class Math is the ratio of a circle’s circumference to its diameter.
The constant Math.E (2.71828…) is the base value for natural
logarithms.

5.3 Writing Your Own Methods

The general format of a method declaration is that we firstly write


the method header, which is the first line. Following the method
header, declarations and statements in braces form the method body,
which is a block. Variables can be declared in any block and blocks
can be nested, but a method cannot be declared inside another
method. The basic format of a method declaration is

return-value-type method-name(para1, para2,…. paraN) {


Declarations and statements
}

Note para means parameter.

The method-name is any valid identifier. The return-value-type is


the type of the result returned by the method to the caller (int, char,
double, …). Methods can return at most one value.

The parameters are declared in a comma-separated list enclosed in


parentheses that declares each parameter’s type and name. There
must be one argument in the method call for each parameter in the
method declaration. Also, each argument must be compatible with
the type of the corresponding parameter. For example, a parameter
of type double can receive values of 8.56, 67 or –0.89567, but not
“year” (because a string cannot be implicitly converted to a double
variable). If a method does not accept any arguments, the parameter

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 must be a one-on-one correspondence between the arguments


in the method call and the parameter list in the method. For example,
if we have the following in the method call avg(a,b,c), then x, y, and
z will represent a, b, c, respectively in the following method
declaration

static double avg(float x, float y, float z) {

Parameters x, y and z in the method avg are sometimes called the


dummy arguments or formal parameters, simply because they are
placeholders for the real and / or actual parameters or arguments that
are coming from the method call. There is no hard and fast rule
about whether the parameters in the method call and that of the
method are the same. But for good programming principle, we
always use different nomenclatures (names) for them. What this
means is that float x, float y, float z in the method could as well be
written as float a, float b, float c.

There are two major ways of passing parameters into


methods/functions in a program. When the actual values of variables
are passed into a method, this is called parameter passing by value.
Any changes on this data do not affect the original data. Parameter
passing by reference is a two-way communication process. Usually
the address of a variable is passed into a method and any changes
made on the variable affects the original value of the variable in
wherever it is located in memory. Array address passing is an
example.

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.

When a return statement executes, control returns immediately to the


statement that called the method.

Below are some examples to illustrate programmer-defined methods.

E35: A Method that Returns the Cube of an Integer

public class TestCube {


public static void main(String[ ] args) {
for (int i = 0; i < 6; i++)
System.out.println(i + “\t” + Cube(i));
}
static int Cube(int n) {
return n * n * n;
}
}

Output

C:\j2sdk1.4.2_04\bin>java TestCube
0 0
1 1
2 8
3 27
4 64
5 125

Note: Method Cube is invoked from the println method, with


argument i, which represents the current value of i in the for-loop.
Method call is Cube(i).

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.

Alternatively, we could write all our methods just after the


declaration of the class name. Example 2 below illustrates this.

E36: Methods that return the sum, mean and maximum of 2


numbers

import javax.swing.*;
class sumMeanMax {

// method to sum the two numbers


static int sum(int a, int b) {
return a + b;
}

// method to find the average of the two numbers

static double mean(int a, int b) {


// add, declared below is a local variable, local to this method

int add = sum(a,b); // calling the sum method


double avg = add/2.0;
return avg;
}

// method that returns the maximum of the two numbers

static int maxim(int a, int b) {


if (a > b)
return a;
else
return b;
}

178
Java for Beginners
// The main method

public static void main(String[ ] args) {


int x = Integer.parseInt(JOptionPane.showInputDialog("
Enter the first number", "x = "));
int y = Integer.parseInt(JOptionPane.showInputDialog("Enter the
second number", "y = "));
String output = "Summation = " + sum(x,y) + "\n" + "Average = " +
mean(x,y) + "\n" + "Maximum = " + maxim(x,y);
JOptionPane.showMessageDialog(null,output,"Methods Demo...",
JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
} // End main
} // End class

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:

static double mean(int a, int b) {


// add, declared below is a local variable, local to this method
int add = sum(a,b); // calling the sum method
double avg = add/2.0;
return avg;
}

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.

//PROGRAM USES JAVA ABSTRACT WINDOW TOOLKIT


(awt)PACKAGE
import java.awt.container;
import javax.swing.*;
public class calculate {
public static void main(String[ ]args) {
JTextArea outputTextArea = new JTextArea(20,30);
JScrollPane scroller = new
JScrollPane(outputTextArea);
//APPEND STRING TO OUTPUT
outputTextArea.setText(" "+"x"+" "+"sqr x"+"
"+"sqrt x"+" "+"cube x" + " "+"cbrt x"+"\n");
for(int x=0; x<10; x++)
outputTextArea.append(" "+x+" "+(x*x)+"
"+sqrt(x) +" "+(x*x*x)+" "+cbrt(x)+ "\n");

JOptionPane.showMessageDialog(null,scroller,
"CALCULATION", JOptionPane.INFORMATION_MESSAGE);

180
Java for Beginners
System.exit(0);
}//END MAIN

//METHOD SQUARE ROOT


static double sqrt(int b) {
double sqrt=(Math.sqrt(b));
return sqrt;
}//END SQUARE ROOT METHOD

//METHOD CUBE ROOT


static double cbrt(int a) {
double cbrt=(Math.pow(a,(0.33)));
return cbrt;
}//END CUBE ROOT METHOD

}//END CLASS CALCULATE

The figure below gives a picture of an output from this


program

181
Exercise: Modify the above program to bring out the result in a
good formatted output, possibly up to two decimal places tabulated.

E38: Program that computes the factorial of n, method fac assumes


that the factorial of any numbers less or equal to 1 is zero.

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).

5.3.2 Passing Arrays into Methods

To pass an array argument to a method, specify the name of the


array without any brackets. For example, if array score is declared as

int [ ] score = new int[5];

then the method call

swap(score);

passes a reference to array score to method swap. In Java, every


array object “knows” its own length (via the length field). Thus,
when we pass an array object into a method, we do not need to pass
the length of the array as an additional argument.

Although entire arrays and objects referred to by individual elements


of reference-type are passed by reference, individual array elements
of primitive types are passed by value exactly as simple variables
are. To pass an array element to a method, use the indexed name of
the array as an argument in the method call.

For a method to receive an array through a method call, the method’s


parameter list must specify an array parameter (or several if more
than one array is to be received). For example, the method header for
method qsort in program E35b is written as

qsort(int[ ] array1, int first, int last)

indicating that qsort expects to receive an integer array in parameter


array1. since arrays are passed by reference, when the called method
uses the array name array1, it refers to the actual array (named array)
in the calling method.

183
E39: The program below passes an array into a method and
computes the mean value in the array

import javax.swing.*;
class arrayMethod {

//method to compute the mean value in the array


static double arrayMean(int a[ ]) { // Entire array passed
double sum = 0;
for(int i = 0; i < a.length; i++){
sum += a[i];
} // next i
double mean = (double)sum/a.length;
return mean;
} // end method arrayMean

//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];

// Reading Data into the Array a


for (int m = 0; m < n; m++)
a[m] = Integer.parseInt(JOptionPane.showInputDialog("Enter
data"+ (m+1)));

// printing the original array a


System.out.println("Original array elements .....\n");
for (int l = 0; l < n; l++ )
System.out.print(a[l] + "\t");

System.out.println("\n");

//Calling the sum method to compute the mean in the array


System.out.printf("Mean of the array data is %.3f \n\n\n",
arrayMean(a) );

//Closing the program


System.exit(0);

184
Java for Beginners
}
}

Sample Output:

E40: The program below uses quicksort algorithm to sort an array. It


further illustrates how arrays could be passed into a method.

//Program to sort an array of data using quick sort.


// It also makes use of methods in java
import javax.swing.*;
class quick_sort {
static void interchange(int[ ] array, int i, int j) {
int initial = array[i];
array[i] = array[j];
array[j] = initial;
}
static int split(int [ ] array, int first, int last){
int pointer = array[first];
int lowest = first;
int highest = last;
while( lowest <= highest){
while((lowest <= last) && (array[lowest] <=
pointer))
// Note the use of logical AND && in the last previous line
lowest++;

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.

5.4 Random Number Generation

Random numbers are popular with simulation experiment and game


playing applications. Random method is part of the Math Class,
which could be invoked and used in programs.

Math method random generates a random double value in the range


from 0.0 up to, but not including, 1.0. The values returned by
random are actually pseudo-random numbers – a sequence of values
produced by a complex mathematical calculation. The calculation
uses the current system time to “seed” the random number generator
such that each execution of a program yields a different sequence of
random values. For example, the code:

double randomVal = Math.random();

will assign a double random number to randomVal.

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.

This manipulation is called scaling the range of values produced by


Math method random. For example, to produce integers from 0 to 5,
we could write:

(int)(Math.random( ) * 6)

The number 6 in the expression is called the scaling factor. The


integer cast operator (int), truncates the floating point part (the part
after the decimal point) of each value produced by the expression.
The shifting value that specifies the initial value in the desired set of
random numbers should also be stated; else, zero (0) is assumed as
in the above code. Thus we have the following formula holding for
random numbers:

number = shiftingValue + (int)(Math.random( ) * scaling factor);

For example, for a die rolling, we could write

int dieFace = 1 +(int)(Math.random() * 6);

which will assign an integer random value to dieFace.

A complete program is illustrated below, which generates 20 random


numbers from 1 to 6.

E41: 20 random numbers from 1 to 6, printing 5 data per line.

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.

Example: Testing If a Number is Prime or Not

A prime number is an integer greater than 2 whose only divisors are


1 and itself. In order to implement a program to determine if a
number n is prime or not, we continue to divide n by numbers 2, 3 4,
5, up to n-1. If at any time, the remainder of the division equals zero,
the program immediately returns that n is not prime. If at the end of
all divisions, no remainder equals zero, the program returns that n is
prime. For example, to determine if 23 is prime or not, 23 is
continuously divided by 2, 3, 4, 5 … 22. In any of the divisions,

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.

5.5 Void Methods

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)

The implementation below uses an array. It assumes that the


Fibonacci numbers are kept in an array with the 0 and 1 in the first
two indexes or locations representing the Fibonacci values of 0 and
1 respectively. The subsequent Fibonacci numbers are computed
based on the general formula presented above. That is, the Fibonacci
of 3 will be the sum of Fibonacci at location [3 – 1] and location [3 –
2], which are locations 2 and 1 respectively.

E43: Fibonacci program


import javax.swing.*;
class fibonacci {

// the void method

static void fibn( int a) {


int[ ] fib = new int[a];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i<a; i++)
fib[i] = fib[i-1] + fib[i-2];
for (int i = 0; i < fib.length; i++)
System.out.println("Fib[" + i + "] = " +
fib[i]);
}// end method fibn

// the main method …

191
public static void main(String[ ] args) {
int n = Integer.parseInt(JOptionPane.showInputDialog
("Enter the terminating point for n: "));

fibn(n); // calling the void method fibn

}
}

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.

Another example code to illustrate a void method is given below.


The program reverses an array such that element at the leat index is
swapped with the one in the first index in that order.

192
Java for Beginners

E44: Void method to reverse an array


import javax.swing.*;
class arrayMethod {

// method to reverse the array elements


static void reverse(int a[ ]) {
int i = 0, j = a.length - 1;
while (i != j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
if (j < i)
break;
} // end while loop

// Printing the array in reverse order


System.out.println("Reversed array ..... elements \n");
for (int k = 0; k < a.length; k++ )
System.out.print(a[k] + "\t");

} // end void method reverse

// main program with main method


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];

// Reading Data into the Array a


for (int m = 0; m < n; m++)
a[m] = Integer.parseInt(JOptionPane.showInputDialog("Enter
data"+ (m+1)));

// printing the original array a


System.out.println("Original array elements .....\n");
for (int l = 0; l < n; l++ )
System.out.print(a[l] + "\t");

193
System.out.println("\n");

// reversing the array a, method reverse is called here


reverse(a);

//Closing the program


System.out.println("\n");
System.exit(0);
}
}

Sample Output…

5.6 Recursive Methods

The example methods we have discussed so far are structured as


methods that can call each other in a disciplined, hierarchical
manner. However, a method can call itself in a number of times. A
recursive method is one that calls itself either directly or indirectly
through another method.

In recursion, the problems being solved are similar in nature and


their solutions too are similar. When a recursive method is called to
solve a problem, the method could actually solve the simplest case
or base case. If the method is called with a base case, the method
returns a result. However, if the method is called with a complex

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.

Example 1: Recursive Factorial

public long fac (int n) {


// Base case
if (n <= 1)
return 1;
//Recursive step
else
return n * fac(n – 1);
} // End method fac

Example 2: Recursive Fibonacci Series

public long fib (int n) {


// Base case
if (n == 0 || n == 1)
return n;
// Recursive step
else
return fib(n – 1) + fib(n – 2);
} // End method fib

195
Comparing Recursion and Iteration

 Both iteration and recursion are based on a control statement:


iteration uses a repetition control (for, while or do- while);
recursion uses a selection control (if, if – else or switch).
 Both involve repetition: Iteration explicitly uses a repetition
statement, recursion achieves repetition through repeated
method calls.
 Both involve a termination test: Iteration terminates when the
loop continuation condition fails. Recursion terminates when a
base case is recognized.
 Iteration with counter-controlled repetition and recursion, each
gradually approach termination: iteration keeps modifying a
counter until the counter assumes a value that makes the loop
continuation condition fail, recursion keeps producing simpler
versions of the original problem until the base case is reached.
 Both can occur infinitely: an infinite loop occurs with iteration
if the loop continuation test never becomes false. Infinite
recursion occurs if the recursion step does not reduce the
problem each time in a manner that converges on the base
case.
 Demerits of recursion: it repeatedly invokes the mechanism,
and consequently, the overhead, of method calls. This
repetition can be expensive in terms of both processor time
and memory space. Each recursive call causes another copy of
the method (actually, only the method’s variables) to be
created; this set of copies can consume considerable memory
space. Iteration occurs within a method, so repeated method
calls and extra memory assignment are avoided. Therefore,
there is no need of choosing recursion (Deitel and Deitel,
2007).

196
Java for Beginners
Tutorial Questions

1. Write a function in Java that could accept an integer


denoting a year and returns true or false according to
whether the year is a leap year or not.

2. Write a function in Java that accepts two dates in a year and


computes the number of days between them. State the
conditions under which the function may work properly
(regarding the ordering of input to the function).

3. Write a recursive Java method to return the factorial of a


number, n.

4. Using the concept of java methods, write a java program that


solves the combination problem, i.e. nCr. What advantages
can you infer from using method in this program?

5. Study the program below and explain its functionality.

E45:
package util;

import java.util.Arrays;

public class MathUtil {

public static double getLM(int[ ] numbers){


//find the largest of the numbers
Arrays.sort(numbers);
if(Arrays.binarySearch(numbers, 0) >= 0) // take care of the zero term
return 0;
double largest = numbers[numbers.length - 1];
int count = 0; double lcm = largest;
boolean lcmFound = false;
int mult = 1;
do {
for (int i = 0; i < numbers.length - 1; i++) {
//check if largest is a multiple of the rest

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;
}

public static void main(String[ ] args) {


int[ ] nums = {-44, 0, 2, 4, 6};
System.out.println(MathUtil.getLM(nums));
}
}

198
Java for Beginners

Strings Manipulation
In Java
6.0 Introduction

A string is a sequence of characters. Words, sentences and names are


strings.

6.1 The String Class

The simplest type of string in Java is an object of the string class and
cannot be changed.

6.3 Operations on Strings

(1) Length of Strings: gives the total number of characters in a


string. Consider the program segment below:

{
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.

(2) Getting the Character at a Particular Point or


Index. Note: Java starts its counting from 0. Using the
example above

String stringIndex4 = alphabet.charAt(4);

Solution here is letter E

(3) Getting the Index of a Character: The index


of a character is the position of the character in a string. Zero
indexing must be observed. There are 26 characters in the
string

String stringCharIndex = alphabet.indexOf(‘Z’); //solution, 25

(4) Getting the Hash code for a String

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.

String stringHashCode = alphabet.hashCode();

(5) Getting Substrings

A substring is a string whose characters form a contiguous


part of another string. The Substring() method extracts

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 substringFrom4to8 = alphabet.substring(4,8);


Solution: EFGH

String substringFrom4to4 = alphabet.substring(4,4);


Solution: nil

Note: The substring keyword must be in small case letters


throughout.

(6) Changing Case of a String: Case has to do with small or


bigletters such as a, A, b, B. We can change all the
characters in a string to either big or small letters.

String country = “NIGEria”;


String lower = country.toLowerCase();// solution: nigeria
String upper = country.toUpperCase(); //solution: NIGERIA

(7) Concatenation: We have dealt with this in our past


examples. We use + symbol to concatenate or join strings
together. Java also use the concat method for this operation.
For example:

String a1 = “I am coming ”;
String b = “to you soon”;
String c1 = a1 + b;
String c2 = a1.concat(b);

solution: both c1 and c2 contain I am coming to you soon

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:

String str = “Arise to sing a song”;


// To get the first index of s
int i = str.indexOf(‘s’);
system.out.println(“First index of ‘s’: ” + i);
//To get the next index of s
int j = str.indexOf(‘s’, i + 1);
system.out.println(“Next index of ‘s’: ” + j);
int k = str.indexOf(‘s’, j + 1);
system.out.println(“Next index of ‘s’:” + k);
//To get the last index of s
k = str.lastIndexOf(‘s’);
system.out.println(“Last index of ‘s’:” + k);

(9) Replacing Characters in a String. Using the replace()


method,we can substitute a character with another character
in a string. The example below illustrates this:

public class Replacing {


public static void main (String[ ] args) {
String inventor = “Charles Babbage”;
system.out.println(inventor.replace(‘B’,’C’));
}
} // Output: Charles Cabbage

(10) Converting Strings into Primitive Types:

The program below shows how to do arithmetic on numerical values


that are embedded within a string. Study, compile and execute this
program and report your observations.

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:

 The parseInt() method (defined in the integer class) reads the


two characters ‘1’ and ‘8’ from the todaysDayString string,
converts them to their equivalent numerical values 1 and 8,
combines them to form 18 and then returns that int value.

203
11. Comparing Strings Using the Methods equals,
equalIgnoreCase, compareTo and regionMatches

Consider the following segment

String s1 = new String(“Akinola”);


String s2 = “good day”;
String s3 = “Happy Day”;
String s4 = “happy day”;

If we wanted to test for equality, we could use the method equals.


Method equals tests any two objects for equality, that is, if the
strings contained in the two objects are identical. The method returns
true if they were and false otherwise. This method uses a
lexicographical comparison. The integer Unicode values that
represent each character in each string are compared. Thus the
statement;

if (s1.equals(“akinola”))

will return false. Note that java is case sensitive.

We use “==” operator to compare object references to determine


whether they refer to the same object; not whether two objects have
the same contents. However, if we write the following code:

if (s1 == “Akinola”), the condition will be true.

Method IgnoreCase ignores the case of the letters in each string.


Thus, if we write the following code:

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:

String output = s3.compareTo(s4);

returns a negative number to output. But s4.compareTo(s3) will


return a positive number. Note that method compareTo is case-
sensitive. Consider the following code, which sorts words in a string
in an ascending order using a bubble sort technique. Method split( )
is used in the code to split a string into tokens and converts the string
into a string array. This is explained further in section 17 of this
chapter.

E47: Sorting Words in a String


import javax.swing.*;
class str {
public static void main(String[ ] args) {

// The program accepts a string, converts the string into a string


//array Using the split method
// Sorts the string in ascending order

// reading the string


String s =JOptionPane.showInputDialog("Enter a string of any
length");
System.out.println("\n The original string is \n\n" + s);

// Splitting the string into a string array.


// Space is used as the token-separator in the string
String[ ] sArray = s.split(" ");

// sorting with bubble sort technique,


// using the compareTo( ) method

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

//Printing sorted string


System.out.println("\n The sorted words in the string are\n");
for (int i = 0; i < sArray.length; i++)
System.out.println(sArray[i]);
System.exit(0);
}
}

Practical Exercise: Extend the above program to search for a


particular word in a string.

Method regionMatches compares portions of two strings for


equality. The first argument is the starting index in the string that

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,

String s3 = “Happy Day”;


String s4 = “happy day”;

if (s3.regionMatches(0, s4, 0, 5))


output += “First 5 characters of s3 and s4 match\n”;
else
output += “First 5 characters of s3 and s4 do
not match\n”;

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:

if (s3.regionMatches(true, 0, s4, 0, 5))


output += “First 5 characters of s3 and s4 match\n”;
else
output += “First 5 characters of s3 and s4 do
not match\n”;
In this case, the first five characters in the two strings matches.

12. Other Comparison Methods – startsWith and endsWith


Just as the words indicate, the methods test if a string starts or ends
with some sets of characters. We could specify the position or index
where we want to start the comparison on the strings. Consider the
following code segments:

E48:
public class str{
public static void main(String[ ] args) {

String strings[ ] = {"Akin", "Akinola", "Akintola", "Akinsola"};


String output = " ";

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

13. Reversing a String: Characters in a string can be reversed


and printed in the reverse order.

This is a powerful way of data encryption. A counting down for-loop


could be used to achieve this. For example,

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

14. Trimming a String: The trim() method is normally used


to remove leading or trailing white spaces before and after a
string. For example:

String s1 = “ Akinola “;
String s2 = s1.trim()
// no more spaces before and after Akinola

15. Converting a String into an Array using


toCharArray() method

The code below creates a new character array ontaining a


copy of the characters in string s1 and assigns a reference to
variable charArray.

String s1 = new String(“welcome”);


//conversion to character array
char charArray[ ] = s1.toCharArray();

// to access characters in the charArray, we need to go by the way


// of array.

for(int j = 0; j < charArray.length; ++j)


System.out.println(charArray[j]);

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.*;

public class tokens extends JFrame {


private JLabel stringLabel;
private JTextField input;
private JTextArea output;
// set up user interface and event handling
public tokens( ) {
super("string Tokenization");
Container container = getContentPane();
container.setLayout(new FlowLayout());
stringLabel = new JLabel("Enter a sentence and press enter");
container.add(stringLabel);
input = new JTextField(25);
input.addActionListener(
new ActionListener(){ //Anonymous inner class
// handle text field event
public void actionPerformed(ActionEvent event) {
StringTokenizer tok = new stringTokenizer
(event.getActionCommand());
output.setText("number of elements: " + tok.countTokens() +
"\nThe Tokens are:\n");
while(tok.hasMoreTokens())
output.append(tok.nextToken() + "\n");
}

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

Split( ) is a method that can be used to split a string into its


constituent words and then stored them into a string array. The
parameter to be passed into the split( ) will be the delimiter used to
separate the words in the string, for example, space. Examine the
code below, which is another way of implementing a tokenizer. The
program also counts the number of occurrence of the word ‘the’ in
the string given.

E52: Using Split( ) method


import javax.swing.*;
class str {
public static void main(String[ ] args) {

// 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

// reading the string


String s =JOptionPane.showInputDialog("Enter a string of any length");
System.out.println("\n The original string is \n\n" + s);

// Splitting the string into a string array.


// Space is used as the token-separator in the string
String[ ] sArray = s.split(" ");

//Printing out the length of the string array


System.out.println("Number of words in the array is "+ sArray.length);

//Printing out the tokens


System.out.println("\n The tokens in the array subscripts\n");
for (int i = 0; i < sArray.length; i++)
System.out.println(sArray[i]);

//Checking for 'the' occurrence


int count = 0;
for (int i = 0; i < sArray.length; i++) {
//System.out.println(sArray[i]);
if (sArray[i].equalsIgnoreCase("the"))

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

String[ ] sArray = s.split(",");

The sorting code is re-run here but with a comma separated tokens.
Only the output is shown here.

18. StringBuffer Objects: normally used for string objects


that need to be changed. Consider the example below, which creates
only one object, buf, which is then modified several times using
concatenation operator and the append() method:

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

(19) Replacing StringBuffer Objects. Using the simple


program above, write another line of code after the last line
as:

buf.SetCharAt(1,”s”);
System.out.println(“Replaced statement is:“ + buf);

Output: Is was the best

Implemented Example: Palindrome

A palindrome is a string that can be spelt same way forwards and


backwards. The algorithm for a palindrome is stated here.
1. Two indexes i, and j are set at the extreme ends of the string
respectively.
This is a string

i j

2. Index i is incremented by 1 to the right while index j is


decremented by 1 to the left.
3. The Characters they are pointing to are compared. If they are the
same, step number 2 is repeated to other set of characters in the
string.
4. If at any point, the characters being pointed to by the indexes
differs, the program reports that the string is not a palindrome.
But when the two indexes meet on a character, the string is a
palindrome.

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;

while (i < a.length( ))


{
if (a.charAt(i) == a.charAt(j))
{
i++;
j--;
stop = true;
continue;
} // end if
else {
System.out.println(a + " is not a
palindrome");
break;
} // end else
}// end while
if (stop == true) {
System.out.println(a + " is a palindrome");
}
System.out.println("Good bye to palindrome
user");
}// end main
}//end class

217
Sample Output

218
Java for Beginners

E55: A more efficient code is shown below

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");
}
}
}

Explain how this above code achieves the principle of palindrome.

TUTORIAL QUESTIONS

1. Consider the following program


segment/snippet:

String univer = “My University is very good”;


String Uni = “my university is very Good”;

Write Java snippets to:


a. Get the total length of the string univer.
b. Compare if the two strings are equal, not minding
letter cases.
c. Print out only “University is good” from univer
d. Reverse the string Uni
e. Get the last index of ‘s’from the string univer

2. Write a program in Java that reads a line of text from the


keyboard and displays it on the screen one word per line as
well as writing on the screen the number of words in the
text. The text contains letters and blanks only.

220
Java for Beginners

Introduction to Java Applets


7.0 Introduction

A java applet is a java program that can be embedded in a HyperText


Markup Language (HTML) document (i.e. a web page). When a
browser loads a web page containing an applet, the applet downloads
into the web browser and begins execution. This enables us to create
programs that anyone can execute simply by loading the appropriate
web page in their Web browser.

The browser that executes an applet is known as the applet


container. Most of the java development tool kits like J2SDK 1.4.1
and above includes the appletviewer applet container for testing
applets separately before we embed them in a web page.

It should be noted that some web browsers do not support Java 2


directly. However, Netscape 7 supports it very well. To run applets
on Microsoft Internet Explorer, we need the Java Plug-in, which is
installed as part of Java toolkits.

7.1 Creating an Applet

Let us begin with a simple example as follows.

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

double sum, average;


// Applet initialization and data capturing

public void init() {


String Num1 = JOptionPane.showInputDialog("Enter the
first Number ");
double n1 = Double.parseDouble(Num1);
String Num2 = JOptionPane.showInputDialog("Enter the
second Number ");
double n2 = Double.parseDouble(Num2);
sum = n1 + n2;
average = sum/2.0;
} //End Method Init

// Draw results in a rectangle on applet's background


public void paint(Graphics g) {
super.paint(g); //Superclass version of the method paint called
// Draw rectangle starting from (15,10) that is 270 pixels
// wide and 20 pixels tall
g.drawRect(15,10,270,20);
//draw results as a String at (25,25)
g.drawString("The sum is: " + sum + " and the average
is: " + average, 25, 25);
} //End method paint
} // End Class AverageApplet

Now, let us explain this program and how it could be compiled and
run.

1. Some packages from the java Application Programming


Interface (API) need to be imported into the applet program:
java.awt.Graphics, and javax.swing.Jappplet. Java contains
many predefined entities called classes that are grouped into
packages (named collections of classes) in the Java API.

222
Java for Beginners

The Statement import java.awt.Graphics; indicates an import


declaration, which indicates that the applet uses Graphics from
package java.awt. Class Graphics enables a java applet to draw
graphics such as lines, rectangles, ovals and strings of characters.
awt actually stands for Abstract Windows Toolkit. To draw a
horizontal line from (15,10) to (210,10), we write
g.drawLine(15,10,210,10); in the program.

The Statement import javax.swing.JApplet; is also an import


declaration which indicates that the applet uses class Japplet from
package javax.swing.

2. The keywords extends Japplet in line 5 indicates that the class


AverageApplet inherits existing members (data and methods)
from another class, JApplet. In this inheritance relationship,
JApplet is called the superclass and AverageApplet is the
subclass. We shall deal with this aspect in later chapters
ahead.
3. The statement, public void init() indicates that init is a public
method that receives no arguments (empty parenthesis after
init) to perform its task and returns no information (void)
when it completes.
4. The statement, public void paint(Graphics g) begins the
applet’s paint method, which is one of the three applets
methods (or behaviour) that the applet container calls when it
begins executing the applet. In order, these methods are init(),
start() and paint().The applet class we defined has access to all
these when we specify extends JApplet in the first line of the
class declaration. To enable our applet to draw, class
AverageApplet redefines the superclass version of paint by
placing statements in the body of paint that draw a message on
the screen. When the applet container tells the applet to “draw
itself” on the screen by calling method paint, the message in
the drawstring parenthesis appears rather than a blank screen.
Keyword void indicates that this method does not return any
results when it completes its task. The set of parentheses after

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

A pixel (“picture element”) is a unit of display for a computer’s


screen. Each pixel has a coordinate pair that describes the
coordinate’s position on the screen. In a coordinate pair, the first
coordinate is the x-coordinate (the number of pixels from the left
side of the applet), and the second coordinate is the y-coordinate (the
number of pixels from the top of the applet. On a computer screen, a
pixel appears as one coloured dot on the screen. Many personal
computers have 800 pixels for the width of the screen and 600 pixels
for the height of the screen, for a total of 800 times 600 or 480,000
displayable pixels. However, most computers have higher resolution
than this. The size of an applet on the screen depends on the size and
resolution of the screen. For screens with the same size, the applet
will appear smaller on the screen with the higher resolution due to
the greater number of pixels on the screen.

224
Java for Beginners
7.2 To Compile and Execute the Applet…

o As with all application classes, we save the applet


application with the same we give to the class. For the above
example, we need to save it as AverageApplet.java. And to
compile it, we follow the same procedure: javac
AverageApplet.java. If there is no error, the resulting
bytecodes are stored in the file AverageApplet.class.
o In order to execute the applet, it has to be deployed to an
HTML documents. Recall that applets are embedded in web
pages for execution in an applet container (appletviewer or a
browser). Typically, an HTML (Hypertext Mark-up
Language) document ends with an “.html” or “.htm” file-
name extension. Browsers display the contents of documents
that contain text (also known as text files). To execute a java
applet, an HTML document must indicate which applet the
applet container should load and execute. A simple HTML
code to execute our example applet is illustrated below:

<html><head><title> Applet Demo </title></head>


<body>
<applet code = “AverageApplet.class” width = “300” height =
“50”></applet>
</body></html>

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

o The appletviewer uses an HTML document to load an


applet.
o If your applet executes in the appletviewer, but does not run
well in Netscape or Internet Explorer, the Java Plug-in might
not be installed. In this case, visit the web site
java.sun.com/getjava. This site provides Java Plug-in
installation instructions for several platforms. If you are
using Internet Explorer, you can simply click the Free
Download button at the top of the page to install the Java
plug-in for Internet Explorer.
o If after installing the Plug-in, applets still do not execute in
Internet Explorer, click the Tools menu and select Internet
Options… then click the Advanced tab in the window that
appears. Locate the option “Use Java 2 v1.4.1 for
<applet>(requires restart)” and ensure that it is checked,
then click OK. Close all your browser windows before
attempting to load another applet.

As an exercise, try to execute the code below both in the


appletviewer and Internet explorer:

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

7.3 Applet Resources on the Web

There are a large number of java applet resources available on


the Internet. The best place to start with is at the source – the
Sun Microsystems, Inc. Java Web site, java.sun.com. The web
page , Java.sun.com/applets, contains several java applet
resources, including free applets you can use on your own
World Wide Web site, the demonstration applets from J2SDK
and other applets (many of which can be downloaded and
used on your computer. There is also a section entitled
“Applets at Work” where you can read about uses of applets
in industry. Another useful applets repository website is the
Java Applet Rating Service (JARS), www.jars.com

Tutorial Exercises

1. Develop an applet that reads in the radius of a circle and


draws its diameter, area and circumference
2. Develop an applet that accepts five integers from the
keyboards and determines largest and smallest in the group.
3. Develop an applet that calculates the squares and cubes of
numbers from 0 to 10 and draws the resulting values in table
format as shown below

number square cube


0 0 0
1 1 1
2 4 8

227
8
Introduction to Object-Based
Programming
8.0 Introduction

This chapter is an introduction to object-based programming. In this


chapter, we shall be introduced to the techniques involved in
developing our own objects and classes. The reader is enjoined to
review the section on basic concepts in object oriented programming
in Chapter One.

8.1 Java Classes

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;
}

On issuing the compilation command:

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.

A class is usually described as the template or blueprint from which


the object is actually made. When you create an object from a class,
you “create an instance” of the class. Consider the example below:

fruits mango = new fruits();

The new operator creates a new instance of the fruits class.

An object is characterized by its ‘state’ and ‘behaviour’. The object’s


data is its state, and the method used in manipulating those that data
is its behaviour.

In essence, Object Oriented Programming (OOP) means writing


programs that define classes whose method carry out the
program’s instructions. OOP programs are designed by deciding
first what classes will be needed and then defining methods for those
classes that solve the problem. Java classes are similar to types (int,
short), but three essential characteristics of classes that distinguish
them from Java types are:
 They are or can be user/programmer’s defined
 Class objects can contain variables, including references to
other objects.
 Classes can contain methods that give their objects the
ability to act.

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.

Classes can be (and in Java always are) built on other classes.


Therefore, a class that builds on another class ‘extends’ it. Java
comes with ‘base class’ from which all other classes are built.

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’.

8.2 Relationships between classes:

The relationships between different classes could be


 Use
 Containment (“has –a”)
 Inheritance (“Is-a”)

A class uses another class if it manipulates objects of that class.


Generally class A uses class B if
 a method of A sends a message to an objects of class B
or
 a method of A creates, receives or returns objects of class B

Containment is a special case of use; if object A contains objects B,


then at least one method of class A will make use of that object of
class B.

If class A extends class B, class A inherits methods from class B, but


has more capabilities.

8.3 Building Your Own Classes

The syntax for a class in Java is

accessSpecifier class NameOfClass {

// definitions of the class’s features


// includes methods and instance fields
}

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.

Essentially, there are three aspects to consider when we are writing


our own classes.
(i) The class fields, which are the private variables to be
declared and used in the class,
(ii) The class constructor, which is a special
method/function that will be used to instantiate the
class, and
(iii) Other methods that will be used to manipulate the
private data in the class.

Consider the following example, which is an Account class that


might be used by a business in writing a simple customer accounting
system:

E58: The Account Class

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
}

// method to compute new balance after withdrawal

public void withdraw(double out) {


balance -= out;
}
}

// Program to test the class


public class AccountTest {
public static void main(String[ ] args) {
Account acc = new Account(“Akinola S.O.”, 500);
String name;
double bal;
name = acc.getName( );
bal = acc.getBalance( );
System.out.println(“Account for “ + name + “has balance
=N=” + bal);
acc.deposit(800);
bal = acc.getBalance( );
System.out.println(“New Account balance after
deposit for “ + name + “is =N=” + bal);
acc.withdraw(1000);
bal = acc.getBalance( );
System.out.println(“New Account balance after
withdraw for “ + name + “is =N=” + bal);
}
}

Sample Output from this Program is shown next:

232
Java for Beginners

Note: To run this program,


(i) The class Account and its tester AccountTest.Java need to
be in one file and saved as AccountTest.Java since this is the
one having the main method.
(ii) On compilation, two classes will be created;
AccountTest.class and Account.class
(iii) On Executing or running the code, java byte code interpreter
starts running the code in the main method in the
AccountTest class. This code in turn creates some new
Account objects and shows us their states.

Now, let us analyze this Account class.

1. The class has five methods with headers:

public Account(String name, double bal)


public void deposit(double dep)
public double getBalance( )
public String getName( )
public void withdraw(double out)

The word public here is called Access modifier discussed soon.


These modifiers always specify who can use the method or the class.

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.

2. There are two instance fields, holding data in the Account


class:

String custName;
double balance;

Normally, private keyword is used as access modifier for instance


fields. That is, we could declare the instance filed like:

private String custName;

private keyword means that no outside agency can access the


instance fields except through the methods of our class. Using public
keyword or not specifying anything as in the Account class for the
instance fields does not matter but ruins encapsulation.

3. The Class Constructor

Classes can have three kinds of members: fields, methods and


constructors.

 A field is a variable that is declared as a member of a class. Its


type may be any of the eight primitive data types - boolean,
char, byte, short, int, long, float, double) or a reference to an
object.

 A Method is a function that is used to perform some action for


instances of the class.

 A constructor is a special function/method whose only


purpose is to create the class’s objects. This is called
instantiating the class, and the objects are called instances of
the class.

234
Java for Beginners
The constructor in our Account class is:

public Account(String name, double bal) {


custName = name;
balance = bal;
}

This constructor is used to initialize objects of the class -giving the


instance variables the initial state you want them to have.

For example, in creating an instance of the class with code

Account acc = new Account(“Akinola S.O.”, 500);

We set the instance fields, as follows

custName = “Akinola S.O”;


balance = 500;

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.

8.4 Properties of Constructors

The following are the general properties of constructors

1. A constructor has the same name as the class itself.


2. A constructor may take one or more (or none) parameters.
3. A constructor is always called with the new keyword.
4. A constructor returns no value.

Q. Differentiate constructors from ordinary methods

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 can overload a constructor or a method. That is, different


constructors/methods with the same signature. We shall see example
of this later. Also, it is possible to have more than one constructor in
a class.

Summarily, a constructor is a member function of a class that is


used to create objects of that class. This has the same name as the
class itself, has no return type and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own
name, a return type (which may be void) and is invoked using the
dot operator. For example, double y = Math.pow(a,b)

8.5 Caution about Constructor

We must not introduce local variables with the same names as the
instance fields. For example, the following constructor will not set
the balance.

public Account (String name, double bal) {


custName = name;
double balance = bal; // Error, variable balance redeclared
}

The last line declares a local variable ‘balance’ (with double


appended as data type beside it) that is only accessible inside the
constructor. This shadows the instance field ‘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.

8.6 The methods of the Account Class

These four methods are just like ordinary methods we know.


However, all these methods have access to the private instance fields
by name. This is because instance fields are always accessible by the
methods of their own class. For example,

public void deposit (double dep) {


balance += dep;
}

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);

will make initial deposit to be increased by 1000.

Every method declared within a class has two arguments passed to


it: one is implicit and will not appear in the method’s parenthesis and
the other(s) is/are explicitly declared in the parenthesis. For instance,
the implicit argument to the deposit method is the object of type
Account, which does not appear in the method declaration. The
explicit argument -double dep, is listed in the method declaration.

Other methods in the account class are like ordinary methods we


know. Some of the methods may have empty argument list, that is,
no data is passed into them. The idea is that they make use of the
instantiating field values already passed into the constructor of the
class. These type of methods are normally used to return values to
the object’s references.

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.

8.7 Using the Class

In order to make use of this class in programs, the Account class will
be called or referenced like we have in arrays:

Account acc = new Account (“Akinola S. O.”, 500)

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.

The next examples illustrate further on creating objects and classes

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);
}
}

// Main program to test the Rectangle class

public class RectangleTest {


public static void main(String [ ] args) {
Rectangle myRectangle = new Rectangle(1.5, 4);

double height, width, area, perimeter;

height = myRectangle.getHeight( );
width = myRectangle.getWidth( );
area = myRectangle.area( );
perimeter = myRectangle.perimeter( );

System.out.println(“The rectangle’s height is “ + height);


System.out.println(“The rectangle’s width is “ + width);
System.out.println(“The rectangle’s area is “ + area);
System.out.println(“The rectangle’s perimeter is “ +
perimeter);
}
}

239
Sample Output:

8.8 Classes without Explicit Constructor

We could define a class without an explicit constructor. Just as was


mentioned earlier, in this type of class, the compiler will
automatically declare one with no arguments. This is called a default
constructor. A default constructor has no arguments. The default
constructor sets all the instance variables to their default values. All
numeric data contained in the instance fields would be set to zero, all
booleans would be false and all object variables would point to null.
Consider the example below:

E60: The person Class, with default constructor

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

//method to return the given name


public String getGivenName() {
return givenName;
}
//method to return the year of Birth
public int getYearOfBirth() {
return yearOfBirth;
}
// method to give a value to the family name
public void setFamilyName(String name) {
familyName = name;
}
// method to give a value to the given name
public void setGivenName(String name) {
givenName = name;
}
// method to give a value to the year of birth
public void setYearOfBirth(int year) {
yearOfBirth = year;
}
}

// main program to test the person class


public class PersonTest {
public static void main(String [ ] args) {
Person theLecturer = new Person( );
String temp;
int year;
temp = theLecturer.getFamilyName( );
System.out.println(“The Lecturer’s family name is “ + temp);
theLecturer.setFamilyName(“Akinola”);
temp = theLecturer.getFamilyName( );
System.out.println(“The Lecturer’s family name is “ + temp);
temp = theLecturer.getGivenName( );
System.out.println(“The Lecturer’s given name is “ + temp);
theLecturer.setGivenName(“Olalekan”);
temp = theLecturer.getGivenName( );
System.out.println(“The Lecturer’s given name is “ + temp);
year = theLecturer.getYearOfBirth();
System.out.println(“The Lecturer’s year of birth is “ + year);

241
theLecturer.setYearOfBirth(1990);
year = theLecturer.getYearOfBirth();
System.out.println(“The Lecturer’s year of birth is “ + year);
}
}

Note that in this type of class with default constructor:

(i) When we are creating the new object theLecturer from the
class Person, we did not pass any instantiating value into the
invocation.

Person theLecturer = new Person();

This shows that we want to use a default constructor for our


class. We could initialize the class instantiating fields to
whatever we want, or we just declare them without
initialization.

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,

// method to give a value to the year of birth


public void setYearOfBirth(int year) {
yearOfBirth = year;
}

(iv) Any attempt for us to reference the class methods without


first of all set values to the class fields would mean that the
values returned by the methods will be default values as set
by the default constructor itself. For instance, consider the
code:

temp = theLecturer.getFamilyName( );
System.out.println(“The Lecturer’s family name is “ + temp);

This method getFamilyName( ) returns: The Lecturer’s


family name is I don’t have a name yet

This happens to be the value given to the familyName field


initially.

private String familyName = “I don’t have a name yet”;

But when we set the field with a value:

theLecturer.setFamilyName(“Akinola”);

243
temp = theLecturer.getFamilyName( );
System.out.println(“The Lecturer’s family name is “ + temp);

Then the method returns:

The Lecturer’s family name is Akinola.

8.9 The Life Cycle of an Object

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.

8.10 The Scope of a Class

All instance variables and methods in a class belong to the class


scope. Within a class’s scope, class members are immediately
accessible to all of that class’s methods and can be referenced simply
by name. Variables defined in a method belong to that method and
are ‘local’ to it. Such variables are said to have block scope.

The class members that could be accessed by other objects (i.e.,


public members) can be accessed off a “handle” (i.e. primitive data
type members can be referred to by

objectReferenceName.primitiveVariableName

and object members can be referenced by

objectReferenceName.objectMemberName.

If a method defines a variable with the same name as a variable with


class scope (i.e. an instance variable), the class-scope variable is
hidden by the method-scope variable in the method scope. A hidden
instance variable can be accessed in the method by preceding its
name with the keyword ‘this’ and the dot operator, as in this.x. The

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;
}

Note: In a method in which a method parameter has the same name


as one of the class members, use ‘this’ explicitly if you want to
access the class member, otherwise you will incorrectly reference
the method parameters.

Essentially, in a method, the keyword ‘this’ refers to the object on


which the method operates. For example, many java classes have a
method called “toString()” that returns a string describing the
object. If you pass any object to the System.out.println method, that
method invokes the ‘toString()’ method on the object and prints the
resulting string. Therefore, we can print out the current state of the
implicit argument of any method as System.out.println(this). This is
a useful strategy for debugging.

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,

class customer (String n ) {


this(n, Account.getNewNumber();
{

public customer (String n, int a) {

245
name = n,
accountNumber = a;
}



}

A call, like new customer(“Akinola S.O”) invokes the


customer(String n), which in turn calls the customer(String n, int
a) constructor.

As an example, consider the following example with default


constructor. The program demonstrates that methods in the same
class can call each other and that both the class and the tester
program for the class could be in one monolithic file.

The class firstly computes the customer’s payment before discount.


Then it computes the discount to be given to a customer based on the
number of quantities bought from the store. If the quantity bought is
20 and above then a 20% discount is given to the customer, if it is
between 10 to 19, a 5% discount is given. If the quantityis between 6
to 9, discount is 2% and if it is between 1 to 5, 0.5% discount is
given on the initial payment. Finally, the program computes the net
pay after discount.

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;
}

// method to return the discount

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( )

// Method to return the net pay after discount


public double np( ) {
return ip( ) - d( ); // the two methods up are called
}
// method to set the unit price p
public void setP(double x) {
this.p = x; //keyword ‘this’ explained recently
}

// method to set the quantity q


public void setQ(int y) {
this.q = y;
}
// The main program begins…
public static void main(String[ ] args) {
sales market = new sales(); // calling the default
//constructor with no arguments
int q = Integer.parseInt (JOptionPane.showInputDialog ("Enter
the quantity bought"));
double p = Float.parseFloat(JOptionPane.showInputDialog
("Enter the unit price"));

//Setting the unit price and quantity class instance


// fields using their methods in the class
market.setP(p);
market.setQ(q);

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";

// printing out values


JOptionPane.showMessageDialog(null, out, "Akinola Supermarket and
Stores", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
} // end method main
} // end class

Output Screen Shots

248
Java for Beginners

E62: The example below gives the general quadratic


equation class

//The general class for solving quadratic equations


import javax.swing.JOptionPane;
class quadratic {
private float a, b,c;

//Constructor
public quadratic(float a, float b, float c) {
this.a = a;
this.b = b;
this.c = c;
}

//Method to compute discrimant, d


public double d() {
return (b*b - 4.0 *a * c);
}

//Method to compute first root


public double r1() {

249
return (-b + Math.sqrt(d()));
}

//Method to compute second root


public double r2() {
return (-b - Math.sqrt(d()));
}

//Method to compute real part


public double real() {
return (-b /(2.0*a));
}

//Method to compute imaginary part


public double imag() {
return (Math.sqrt(Math.abs(d()))/(2.0*a));
}

//The main method


public static void main(String[] args) {
//Data entry
float a = Float.parseFloat(JOptionPane.showInputDialog("Enter
the coefficient of x-square, a"));
float b = Float.parseFloat(JOptionPane.showInputDialog("Enter
the coefficient of x, b"));
float c = Float.parseFloat(JOptionPane.showInputDialog("Enter
the constant, c"));

//Instantiating a new object quad from the quadratic class


quadratic quad = new quadratic(a, b, c);

//Reporting the roots


System.out.println("a = "+ a + " b = "+ b + " c = " + c + "\n\n");
if (quad.d() < 0) // complex roots
System.out.printf("Complex roots please \n Complex Root1 =
i%.2f \n Complex Root2 = i%.2f", quad.imag(), quad.real());
else if (quad.d() == 0) // One real root
System.out.printf("One Real Root with value %.2f", quad.real());
else //Two real roots
System.out.printf("Two Real Roots with values \n Root1 = %.2f

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.

If none of the three access modifiers, (public, protected and private)


is specified for a class, field, constructor or method, then they have
“package access”, which means that it can be accessed from any
class in the same package.

The modifier ‘static’ is used to specify that a method is a class


method, else without it, the method is an instance method, which can
be invoked only when bound to an object of the class. For example,
Add() is an instance method which can be invoked as y.Add() in the
main() program. In this invocation, method Add() is bound to the
object y, so y is an implicit argument.

A ‘class method’ is a method that is invoked without being bound to


any specific object of the class.

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.

E63: The Rectangle Class, having four Constructors

public class Rectangle {


public int width = 0;
public int height = 0;
public Point origin; // Point is another class

// The four Constructors..


public Rectangle( ) {
origin = new Point(0, 0);
}

public Rectangle(Point p) {
origin = p;
}

public Rectangle(int w, int h) {


this(new Point(0, 0), w, h);
}
public Rectangle(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}
// A method for moving the rectangle
public void move(int x, int y) {
origin.x = x;
origin.y = y;
}
254
Java for Beginners

//A method for computing the area of the rectangle


public int area( ) {
return width * width;
}
}

// Here’s the code for the Point class

public class Point {


public int x = 0;
public int y = 0;
// The only constructor for the class
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}

/* Here is a small program, called RectangleTest, which creates three


objects: one Point object and two Rectangle objects. You will need all
three source files to compile this program */

public class RectangleTest {


public static void main(String[ ] args) {

// creates a point object and two rectangle objects


Point origin_one = new Point(23, 94);
Rectangle rect_one = new Rectangle(50, 100);
Rectangle rect_two = new Rectangle();

// display rect_one’s width, height and area


System.out.println(“Width of rect_one: “ + rect_one.width);
System.out.println(“Height of rect_one: “ + rect_one.height);
System.out.println(“Area of rect_one: “ + rect_one.area());

// Set rect_two’s position


rect_two.origin = origin_one;

// Display rect_two’s position


System.out.println(“X position of rect_two: “ + rect_two.origin.x);

255
System.out.println(“Y position of rect_two: “ + rect_two.origin.y);

// Move rect_two and display its new position


rect_two.move(40,72);
System.out.println(“New X position of rect_two: “ +
rect_two.origin.x);
System.out.println(“New 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:

Width of rect_one: 100


Height of rect_one: 200
Area of rect_one: 20000
X position of rect_two: 23
Y position of rect_two: 94
New X position of rect_two: 40
New Y position of rect_two: 72

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:

Rectangle rect-one = new Rectangle(origin_one, 100, 200);

It knows to call the constructor in the rectangle class that requires a


point argument followed by two integer arguments.

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

8.14 Writing Classes without Constructors and private


fields

We have used the Math class methods without instantiating a new


object of the class before we used them. For example, Math.pow,
Math.PI, Math.E, etc. We can also write a class that may not have a
constructor and without any private data field. The only thing is that
the method of the class should be declared as static and must not
refer to any of the fields declared for the class. To call the method
from the class, we only need to write className.method(argument),
like in the example below: dem.value(k). dem is the name of the
class and value is a method we are calling from the class. k is the
argument passed to the method from the main program.

E64.
import javax.swing.*;
class dem {

static int value(int a) {


return a*a;
}
public static void main(String[ ] args) {
// computing the square of a number

257
int k =
Integer.parseInt(JOptionPane.showInputDialog
("Enter a number"));
System.out.println("The square of " + k + " = "+ "
" + dem.value(k));
System.exit(0);
}
}

Exercise: Extend this class to compute the cube and cube-root of


numbers.

258
Java for Beginners
Tutorial Questions

1. Write a java program, using a class to compute the roots of


any quadratic equation whose model equation is ax2 + bx + c
= 0.

2. Write a java class to search for x in a 1-dimensional array of


integer data, x belongs to the class of integers.
3. Matrix has been a wonderful mathematical tool for solving
real – life computational problems. Write Java class program
that
(a) Adds three sum-able matrices together.
(b) Computes the product of any two multipliable
matrices.
(c) Add all the elements in the right diagonal of a
square matrix A, with those in the left of
another square matrix B, and prints out the
summation.
(All conditional rules of matrix operations should be
included in your codes).

4. (a) Of what importance is a constructor in a class?


(b) What happens if there was no explicit constructor in
a class?
(c) Give two precautions that are needed to be taken
when using constructors in a class.
(d) Practically implement a class without a constructor
and class fields to compute the square, square root,
cube and cube roots of numbers from 1 to n.

259
9
Java Packages
9.0 Introduction

A package is a collection of classes. They are convenient for


organizing works and for separating then from code libraries
provided by others. The standard java library is distributed over a
number of packages, including java.lang, java.util, java.net, etc.
Organization of packages are always hierarchical, that is, packages
can be nested into each other just like subdirectories, just to
guarantee the uniqueness of package names.

9.2 Benefits of Packages

(1) Packages provide a mechanism for ‘software reuse’. We


don’t need to repeatedly redefine code in separate
programs. All we need is to use or import the existing
ones.
(2) They provide a convention for ‘unique class names’.

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

The steps for creating a re-usable class are:


1. Define a public class. If the class is not public, it can be used
only by other classes in the same package.
2. Choose a package name and add a ‘package’ statement to
the source code file for the re-usable class definition.
3. Compile the class so that it is placed in the appropriate
package directory structure and make the new class
available to the compiler and the interpreter
4. Import the re-usable class into a program and use the class.

Example:
package com.csc232.pack; //second step
public class sample extends object // first step
private - - -
private - - -
// constructor
public sample() {
-
-
-
}
// Other methods
public string toString ( ) {
-
-
-
}
}

// Testing the sample class

import com.csc232.pack.sample; // import the sample class


public class sample test {
public static void main (String args[]){
-
-
-

261
}
}

9.3 Why the com. Naming Convention?

In an effort to p[provide unique names for every package, Sun


Microsystems (the java originator) specifies convention for package
naming. Every package name must start with your Internet domain
name in reverse order. Let’s assume our domain name is
csc232.com, then we use com.csc232

9.4 Compiling a file containing a package

When a java file containing a package statement is compiled, the


resulting .class file is placed in the directory specified by the
package statement. Our sample package statement above indicates
that the class sample package statement above indicates that the
class sample should be placed in the directory ‘pack’. The other
names – com and csc232 are also directories. The directory names in
the package statement specify the exact location of the classes in the
package. If these directories do not exist at the time of compilation;
the compiler creates them.

To actually compile our package, option –d must be passed to the


compiler that specifies where to create (or locate) all the directories
in the package statement. For example,

javac -d c:\jdkl.2.1\jre\classes sample.java

However, if Jcreator is used for the program, we do not need to enter


all these parameters for the compilation. All we need to do is to click
on Build, then compile file and finally execute the file if there were
no compile-time error.

On executing the compilation command, the directory


c:\jdk\.2.1\jre\classes contains a directory called com. com contains

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.

The example class below illustrates the use of packages in programs.

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;
}

//method to return their products


public float prod( ) {
return a * b;
}

// The class tester program


public static void main(String[ ] args) {
float n1 = Float.parseFloat (OptionPane.showInputDialog
("Enter the first data"));
float n2 = Float.parseFloat( JOptionPane.showInputDialog("Enter
the second data"));
pack mpy = new pack(n1,n2);
float product = mpy.prod( );
JOptionPane.showMessageDialog(null, "The product
of the two numbers is" + product +"\n\nBye...");
System.exit(0);

263
} // end main of tester program

} // end class

The following program is independently implemented to use the above


package example. But remember that all codes must be saved into the Bin
subfolder of your java toolkit.

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

The programs above were implemented in the JCreator environment.


On examination, the Bin sub-folder of the Java toolkit contains the
com folder, another folder named example is contained in the com
folder, and finnaly, the example folder contains the pack class.

The pack class can then be used in any program requiring


multiplication of two floating (real) data; by importing the package
into the program as illustrated above.

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.

9.5 To use packages

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

This is the same mechanism employed when we import classes from


the java APIs. For examples

import java.util.*; // imports all classes of util


import javax.swing.JOptionPane; //imports a specific class

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.

We can also import a specific class inside a package. The examples


above illustrate these points,

Tutorial Question

Practically implement a program to solve quadratic equation using


the technique of packages learnt in this chapter.

267
10

Introduction to the
Concept of Inheritance
10.0 Introduction

The idea behind inheritance in Object Oriented Programming (OOP)


is that we can re-use or change the methods of existing classes, as
well as add new instance fields and new methods in order to adapt
them to new situations. For instance, we need to use inheritance to
show text or graphics in a window.

10.1 What is Inheritance?

Essentially, inheritance is a form of software re-usability in which


new classes are created from existing classes by absorbing their
attributes and behaviours and embellishing these with capabilities
the new classes require.

Software re-usability saves time in program development. It


encourages reuse of proven and debugged high quality software,
thus reducing problems after a system becomes operational.

Polymorphism makes it easy to add new capabilities to a system.


Inheritance and polymorphism are effective techniques for dealing
with software complexity.

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.

The direct superclass of a subclass is the superclass from which the


subclass explicitly inherits (via the keyword ‘extends’). An indirect
superclass is inherited from two or more levels up the class
hierarchy.

Java only supports single inheritance whereby a class is derived


from one Superclass. This is opposed to C++, which supports
multiple inheritance. This is archived in Java through “interfaces”.

The superclass is not superior to its subclass or contains more


functionality. In fact, the opposite is true; subclasses have more
functionality than their superclasses. This is because a subclass
normally adds instance variables and instance methods of its own,
making it more robust. Every object of a subclass is also an object of
the subclass’s superclass. The converse is not true. Subclass methods
and methods of other classes in the same package as the superclass
can access ‘protected’ superclass members.

Recall our ‘is a’ and ‘has a’ relationships. ‘Is a’ is inheritance and


‘has a’ is composition. In a “has a” relationship, a class object has
one or more objects of other classes as members.

A subclass’s methods may need to access certain of its superclass


instance variables and methods. If a subclass could access the
superclass’s ‘private’ members, this would violate information
hiding in the superclass. A subclass can however access the ‘public’,
‘protected’ and ‘package’ access members of its superclass provided
it is in the same package as the superclass. Superclass members that
should not be accessible to a subclass via inheritance are declared
‘private’ in the superclass. A subclass can effect state changes in

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.

Examples of Superclass and Subclasses

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

Suppose we have a class named Employee already, which is a class


program for computing salaries of employees in a particular
organization. Suppose in the company, the managers are treated
differently than other employees. Their salary raises are computed
differently, they have access to a secretary, etc. This kind of
situation calls for inheritance as decried by OOP. This is because, we
need to define a new class, say manager, and add functionality. But
we can retain some of what we have already programmed in the
Employee class, and all the instance fields of the original class can

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;
}

public void print( ) {


System.out.println(name + “ “ + salary + “ “ + hireYear);
}

public void raiseSalary(double byPercent) {


salary * = 1 + byPercent / 100;
{

public int hireYear( ) {


return hireDay.getYear();
}

private String name;


private double salary;
private Day hireDay;
}

// Inheritance code

class Manager extends Employee {


public Manager (String n, double s, Day d) {
super(n, s, d);
SecretaryName = “ “;
}

public void raiseSalary (double byPercent) {

271
// Add 0.5% bonus for every year of service

Day today = new Day( );


double bonus = 0.5*(today.getYear( ) – hireYear( ));
super.raiseSalary(byPercent + bonus);
}

public String getSecretaryName( ) {


return secretaryName;
}
pubic void setsecretaryName (String name) {
secretaryName = name;
}

private String secretaryName;


}

Analysis
(i) The keyword “extends” in the statement.

class Manager extends Employee indicates we are making a


new class that derives from an existing class. The existing class is
the Employee, which is called the superclass, base class or parent
class. The new class, Manager is the subclass, derived class or child
class.

(ii) In the constructor for the manager class.

public Manager (String n, double s, Day d) {


super(n, s, d);
secretaryName = “ “;
}

The line super(n, s, d) is a shorthand for “call the constructor of the


employee class with n, s, and d as parameters”.

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

super.raiseSalary (by percent + bonus);

the method looks to the raiseSalary method of the super


class and passes it a parameter that adds the original
parameter and a bonus of half a percent for each year the
manager have been employed since thy were hired.

The raiseSalary method of the Manager class has no direct access to


the private instance fields of the superclass. This means that the
raiseSalary method of the Manager class cannot directly change the
salary field, even though every Manager object has a salary field.
Only the methods of the Employee class have access to the private
instance fields. As a practical example, examine the following codes.
273
The code is a rectangle class which could be used to compute the
area and perimeter of any rectangle.

E67:
class Rectangle {
float l;
float b;
//constructor
public Rectangle(float length,float breadth) {
l=length;
b=breadth;
}

public float area() {


return l*b;
}
public double perimeter() {
return 2.0*(l+b);
}
}

//The following class inherits from the Rectangle class.


class Prism extends Rectangle {
float h;
//constructor
public Prism(float l,float b,float height){
super(l, b);
h = height;
}
//method to compute volume
public float volume(){
return h * super.area();
}
}
The following is a program to test the two clases.

public class Tester {

public static void main(String[ ] args){


Prism oprism = new Prism(10,5,5);
System.out.println("The volume of the prism= "+

274
Java for Beginners
oprism.volume());
Rectangle r = new Rectangle(10,5);
System.out.println("The Area of the Rectangle =
"+r.area());
}

The Output

Note: Each of the above programs is compiled separately in different


files.

Tutorial Question

1. Explain why inheritance is important in Object Oriented


Programming.
2. Design and implement a program involving inheritance that
will compute the volume and surface area of hemispheric
and spheric objects. Check Secondary School Mathematics
Textbook to get the necessary formulae.

275
11

Java File Handling


11.0 Introduction

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.

Records are usually arranged in form of table as shown below:

Rec_no Name Matric Age Sex Ume_Score


o1 Akinola s. O. 68888 25 m 222
02 Zacheus M.G. 133564 17 f 257

…. …. …. ….

276
Java for Beginners
The combination of all these records forms a file. Thus, a file is a
group of related records.

To facilitate the retrieval of specific records from a file, at least one


field in each record is chosen as a record key. Usually, the key is
unique to every record to avoid duplication of records in the file. In
the example table above, matric is a good candidate for the record
key. The key is also used for searching and sorting records in a file.

Records in a file could be organized sequentially, in which records


are stored in order by the record key, or in random order, in which
case, there is no particular ordering of the records in the file, but the
records are indexed.

Usually, in big organizations, data are stored in many files. For


example we could have customer file, payroll file, recruitment file,
supplies file, etc. These files are kept in a database. A group of
related files is called a database. We introduce this concept in the
next chapter.

11.1 Java Perception of Files

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.

When java opens a file, an object in which a stream of bytes is


associated with, is created. In some cases, java associates streams of
bytes with any of the three different devices: System.in, System.out
and System.err. Object System.in allows the input of data via the
keyboard, System.out allows output of result to the screen and
System.err allows output of error messages to the screen. All the
three form the standard files, otherwise called standard stream
objects in Java.

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.

Java.io package must be imported to a java program before files can


be used in that program. The java.io package provides definitions for
stream classes and methods such as
 FileInputStream – for byte-based input from a file
 FileOutputStream – for byte-based output to a file
 FileReader – for character-based input from a file
 FileWriter – for characterbased output to a file.

Files are opened by creating objects of these stream classes that


inherit from classes InputStream, OutputStream, Reader and Writer
respectively.to perform input and output of data types, objects of
classes ObjectInputStream, DataInputStream, ObjectOutputStream
and DataOutputStream will be used togther with the byte-based file
stream classes FileInputStream and FileOutputStream.

Files that are created using byte-based streams are referred to as


binary files, while files created using character-based streams are
referred to as text files. Text files can be read by text editors, while
binary files are read by a program that converts the data to a human-
readable format.

Java provides many classes for performing input/output operations.


 InputStream and OutputStream subclasses of object are
abstract classes that declare methods for performing byte-
based input and output respectively.
 FileInputStream subclass of InputStream and
FileOutputStream subclass of OutputStream are used to
manipulate files.
 PipedOutputStream, PipedInputStream, are used in
connection with threads in java.

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.

In addition, large chunks of data may be transferred to a temporary


storage before being read or written to enhance speed of data
transfer. This is known as buffering technique. BufferedInputStream,
a subclass of FileInputStream and BufferedOutputStream, a subclass
of FileOutputStream are used for this purpose. Typical input/output
operations are extremely slow compared with the speed of accessing
computer memory. Buffered inputs and outputs normally yield
significant performance improvements over unbuffered inputs and
outputs.

In addition to the byte-based streams, we have Reader and Writer


classes, which are Unicode two-byte, character-based streams. Most
of the byte-based streams have corresponding character-based
Reader and Writer classes.

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.

In this text, we introduce the reader to sequential file processing in


java.

11.2 Processing Sequential Access Data File

In this section, we implement a program to process a sequential data


file containing both string and numeric data. This program shows
how to read data sequentially from a text file.

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

Output: Use WordPad to open the output if you don’t have


EditPlus.

282
Java for Beginners

You need to study this program carefully line by line in order to


understand how to use file for your subsequent programs. Below is
the explanation for the program.

The program demonstrates how class Scanner can be used to input


data from a file rather than the keyboard.

The Scanner is a Sub class of Java.util class (util means utility).


Therefore, both java.io, javax.swing and java.util APIs are imported
into the program in lines 1 to 3. Swing is for the JOptionPane. Line
14 uses Scanner method hasNext( ) to determine whether the end-of-
file key combination has been entered. The loop executes until
hasNext( ) encounters the end-of-file marker.

Line 7 contains a try statement. All processes in a file must be put in


a try – catch block. This is a necessity as java believes that an error
may occur in reading from or writing to a file. For instance, there
may be file input error, in which the file name specified is not found.

8. Scanner input = new Scanner(new File( "data.dat" ));

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.

Lines 10 – 12 are for generating the headings in the output as shown


in the output screen shot. We generated the output in tabulated
format with appropriate headings.

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( );

In order to read a String data by the Scanner, input.next( ) method


(or function) is used. To read an integer data, we use the
input.nextInt( ) method. This goes for float, input.nextFloat( ) and
double input.nextDouble( ). Note that the Scanner reads a record at a
time as tokens (i.e. field by field). Therefore, we assign each field to
their individual field names. It is possible to read the three scores
into a one-dimensional array, and then use for-loop to read the data
into the array, especially if we have more than three scores.
However, this is left as an exercise for the reader.

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.

Line 47 and 48:

47. JOptionPane.showMessageDialog(null,"Data has been

285
written to file!","Writing Complete",
48. JOptionPane.INFORMATION_MESSAGE);

These statements inform the user of the program that the data has
been processed.

11.3 Other File Methds

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.

2. Modify the input data to contain 10 or more scores per


record. Modify the program to use array for the scores and
compile and run the program. Record your observations and
errors incurred in the exercise.

287
12

Introduction to Java Database


Connectivity
(JDBC)
14.0 Introduction

The Java Database Connectivity Application Programming Interface


(JDBC API) is a Java API that can access any kind of tabular data,
especially data stored in a relational database.

JDBC helps you to write java applications that manage these three
programming activities:

1. Connect to a data source, like a database


2. Send queries and update statements to the database
3. Retrieve and process the results received from the database
in answer to your query

The following simple code fragment gives a simple example of


these three steps:

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. }

This short code fragment instantiates a DriverManager object to


connect to a database driver and log into the database, instantiates a
Statement object that carries your Structured Query Language (SQL)
query to the database; instantiates a ResultSet object that retrieves
the results of your query, and executes a simple while loop, which
retrieves and displays those results. It's that simple.

12.2 The Basics

12.1.1 JDBC Product Components

JDBC includes four components:

1. The JDBC API

The JDBC™ API provides programmatic access to relational data


from the Java™ programming language. Using the JDBC API,
applications can execute SQL statements, retrieve results, and
propagate changes back to an underlying data source. The JDBC
API can also interact with multiple data sources in a distributed,
heterogeneous environment.

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.

2. JDBC Driver Manager

The JDBC DriverManager class defines objects which can connect


Java applications to a JDBC driver. DriverManager has traditionally
been the backbone of the JDBC architecture. It is quite small and
simple.

The Standard Extension packages javax.naming and javax.sql let


you use a DataSource object registered with a Java Naming and
Directory Interface™ (JNDI) naming service to establish a
connection with a data source. You can use either connecting
mechanism, but using a DataSource object is recommended
whenever possible.

3. JDBC Test Suite

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.

There are many possible implementations of JDBC drivers. These


implementations are categorized as follows:

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.

Installing a JDBC driver generally consists of copying the driver to


your computer, then adding the location of it to your class path. In
addition, many JDBC drivers other than Type 4 drivers require you
to install a client-side API. No other special configuration is usually
needed.

12.1.2 JDBC Architecture

Two-tier and Three-tier Processing Models

The JDBC API supports both two-tier and three-tier processing


models for database access.

291
Figure 12.1: Two-tier Architecture for Data Access.

In the two-tier model, a Java applet or application talks directly to


the data source. This requires a JDBC driver that can communicate
with the particular data source being accessed. A user's commands
are delivered to the database or other data source, and the results of
those statements are sent back to the user. The data source may be
located on another machine to which the user is connected via a
network. This is referred to as a client/server configuration, with the
user's machine as the client, and the machine housing the data source
as the server. The network can be an intranet, which, for example,
connects employees within a corporation, or it can be the Internet.

In the three-tier model, commands are sent to a "middle tier" of


services, which then sends the commands to the data source. The
data source processes the commands and sends the results back to
the middle tier, which then sends them to the user. MIS directors
find the three-tier model very attractive because the middle tier
makes it possible to maintain control over access and the kinds of
updates that can be made to corporate data. Another advantage is
that it simplifies the deployment of applications. Finally, in many
cases, the three-tier architecture can provide performance
advantages.

292
Java for Beginners

Figure 22.2: Three-tier Architecture for Data Access.

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.

With enterprises increasingly using the Java programming language


for writing server code, the JDBC API is being used more and more
in the middle tier of a three-tier architecture. Some of the features
that make JDBC a server technology are its support for connection
pooling, distributed transactions, and disconnected rowsets. The
JDBC API is also what allows access to a data source from a Java
middle tier.

293
12.2 A Relational Database Overview

A database is a means of storing information in such a way that


information can be retrieved from it. In simplest terms, a relational
database is one that presents information in tables with rows and
columns. A table is referred to as a relation in the sense that it is a
collection of objects of the same type (rows). Data in a table can be
related according to common keys or concepts, and the ability to
retrieve related data from a table is the basis for the term relational
database. A Database Management System (DBMS) handles the
way data is stored, maintained, and retrieved. In the case of a
relational database, a Relational Database Management System
(RDBMS) performs these tasks. DBMS as used in this book is a
general term that includes RDBMS.

 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.

A second integrity rule of the traditional relational model is that


column values must not be repeating groups or arrays. A third aspect
of data integrity involves the concept of a null value. A database
takes care of situations where data may not be available by using a
null value to indicate that a value is missing. It does not equate to a
blank or zero. A blank is considered equal to another blank, a zero is
equal to another zero, but two null values are not considered equal.

When each row in a table is different, it is possible to use one or


more columns to identify a particular row. This unique column or
group of columns is called a primary key. Any column that is part of
a primary key cannot be null; if it were, the primary key containing

294
Java for Beginners
it would no longer be a complete identifier. This rule is referred to as
entity integrity.

Table 12.1 illustrates some of these relational database concepts. It


has five columns and four rows, with each row representing a
different student.

Matric_Number Car_Number First_name Last_Name Score


10001 5 Akinola Solomon 45
10083 Abel John 56
10005 12 Hammed F. 67
10035 John Solomon 46

Table 12.1: Table Students

The primary key for this table would generally be the


Matric_number because each one is guaranteed to be different. (A
number is also more efficient than a string for making comparisons.)
It would also be possible to use First_Name and Last_Name because
the combination of the two also identifies just one row in our sample
database. Using the last name alone would not work because there
are two employees with the last name of "Solomon." In this
particular case the first names are all different, so one could
conceivably use that column as a primary key, but it is best to avoid
using a column where duplicates could occur. If John Ibekwe gets an
admission at this school and the primary key is First_Name, the
RDBMS will not allow his name to be added (if it has been specified
that no duplicates are permitted). Because there is already a John in
the table, adding a second one would make the primary key useless
as a way of identifying just one row. Note that although using
First_Name and Last_Name is a unique composite key for this
example, it might not be unique in a larger database.

Manipulating a database involves the use of Structured Query


Language (SQL) to create tables, retrieve data from the database and
edit data in the database.
295
SQL query keywords.

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.

A SELECT statement, also called a query, is used to get information


from a table. It specifies one or more column headings, one or more
tables from which to select, and some criteria for selection. The

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:

SELECT First_Name, Last_Name


FROM Students
WHERE Matric_Number IS NOT NULL

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

The WHERE clause in a SELECT statement provides the criteria for


selecting values. For example, in the following code fragment,
values will be selected only if they occur in a row in which the
column Last_Name begins with the string 'Jo'.

SELECT First_Name, Last_Name

297
FROM Students
WHERE Last_Name LIKE Jo%'

The keyword LIKE is used to compare strings, and it offers the


feature that patterns containing wildcards can be used. For example,
in the code fragment above, there is a percent sign (%) at the end of
'Jo', which signifies that any value containing the string 'Jo' plus zero
or more additional characters will satisfy this selection criterion. So
‘John' or 'Johnson' would be matches, but 'Jeoson' would not be. The
other wildcard used in LIKE clauses is an underbar (_), which stands
for any one character. For example,

WHERE Last_Name LIKE 'Ba_man'

would match 'Batman', 'Barman', 'Badman', 'Balman', 'Bagman',


'Bamman', and so on.

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.

SELECT First_Name, Last_Name


FROM Students
WHERE Car_Number = 12

The next code fragment selects the first and last names of students
whose Matric_number is greater than 10005:

SELECT First_Name, Last_Name


FROM Students
WHERE Matric_Number > 10005

WHERE clauses can get rather elaborate, with multiple conditions


and, in some DBMSs, nested conditions. This overview will not
cover complicated WHERE clauses, but the following code fragment
has a WHERE clause with two conditions; this query selects the first

298
Java for Beginners
and last names of students whose Matric_number is less than 10100
and who do not have a car.

SELECT First_Name, Last_Name


FROM Students
WHERE Matric_Number < 10100 and Car_Number IS NULL

A special type of WHERE clause involves a join, which is explained


next.

 Joins

A distinguishing feature of relational databases is that it is possible


to get data from more than one table in what is called a join.
Suppose that after retrieving the names of employees who have
company cars, one wanted to find out who has which car, including
the make, model, and year of car. This information is stored in
another table, Cars, shown in Table 12.2.

Table 12.2. Cars

Car_Number Make Model Year


5 Honda Civic DX 1996
12 Toyota Corolla 1999

There must be one column that appears in both tables in order to


relate them to each other. This column, which must be the primary
key in one table, is called the foreign key in the other table. In this
case, the column that appears in two tables is Car_Number, which is
the primary key for the table Cars and the foreign key in the table
Students. If the 1996 Honda Civic were wrecked and deleted from
the Cars table, then Car_Number 5 would also have to be removed
from the Students table in order to maintain what is called referential
integrity. Otherwise, the foreign key column (Car_Number) in
Students would contain an entry that did not refer to anything in
Cars. A foreign key must either be null or equal to an existing
299
primary key value of the table to which it refers. This is different
from a primary key, which may not be null. There are several null
values in the Car_Number column in the table Students because it is
possible for a student not to have a car.

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.

SELECT Students.First_Name, Students.Last_Name, Cars.Make,


Cars.Model, Cars.Year
FROM Students, Cars
WHERE Students.Car_Number = Cars.Car_Number

This returns a result set that will look similar to the following:

FIRST_NAME LAST_NAME MAKE MODEL YEAR


----------- ------------ -------- --------- -------
Akinola Solomon Honda CivicDX 1996
Hammed F. Toyota Corolla 1999

 Common SQL Commands

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.

A list of the more common DML commands follows:

 SELECT — used to query and display data from a


database. The SELECT statement specifies which columns

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

The more common DDL commands follow:

 CREATE TABLE — creates a table with the column


names the user provides. The user also needs to specify a
type for the data in each column. Data types vary from one
RDBMS to another, so a user might need to use metadata to
establish the data types used by a particular database.
CREATE TABLE is normally used less often than the data
manipulation commands because a table is created only
once, whereas adding or deleting rows or changing
individual values generally occurs more frequently.
 DROP TABLE — deletes all rows and removes the table
definition from the database. A JDBC API implementation
is required to support the DROP TABLE command as
specified by SQL92, Transitional Level. However, support
for the CASCADE and RESTRICT options of DROP
TABLE is optional. In addition, the behavior of DROP
TABLE is implementation-defined when there are views or
integrity constraints defined that reference the table being
dropped.
 ALTER TABLE — adds or removes a column from a
table. It also adds or drops table constraints and alters
column attributes

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

When one user is accessing data in a database, another user may be


accessing the same data at the same time. If, for instance, the first
user is updating some columns in a table at the same time the second
user is selecting columns from that same table, it is possible for the
second user to get partly old data and partly updated data. For this
reason, DBMSs use transactions to maintain data in a consistent
state (data consistency) while allowing more than one user to access
a database at the same time (data concurrency).

A transaction is a set of one or more SQL statements that make up a


logical unit of work. A transaction ends with either a commit or a
rollback, depending on whether there are any problems with data
consistency or data concurrency. The commit statement makes
permanent the changes resulting from the SQL statements in the
transaction, and the rollback statement undoes all changes resulting
from the SQL statements in the transaction.

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

A stored procedure is a group of SQL statements that can be called


by name. In other words, it is executable code, a mini-program that
performs a particular task that can be invoked the same way one can
call a function or method. Traditionally, stored procedures have been
written in a DBMS-specific programming language. The latest
generation of database products allows stored procedures to be
written using the Java programming language and the JDBC API.
Stored procedures written in the Java programming language are
bytecode portable between DBMSs. Once a stored procedure is
written, it can be used and reused because a DBMS that supports
stored procedures will, as its name implies, store it in the database.

The following code is an example of how to create a very simple


stored procedure using the Java programming language. Note that
the stored procedure is just a static Java method that contains normal
JDBC code. It accepts two input parameters and uses them to change
a student’s car number. Do not worry if you do not understand the
example at this point. The code example below is presented only to
illustrate what a stored procedure looks like. You will learn how to
write the code in this example in the tutorials that follow.

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");

pstmt = con.prepareStatement( "UPDATE STUDENTS


SET CAR_NUMBER = ? " + "WHERE
MATRIC_NUMBER = ?");
pstmt.setInt(1, carNo);
pstmt.setInt(2, Matric_number);
pstmt.executeUpdate( );
}
finally {
if (pstmt != null) pstmt.close( );
}
}
}

 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

Step 1: Create a Microsoft Access 2007 database having the


following table schemas and add some hypothetical records to the
tables:

Student(Matric, Surname, FirstName, Middlename, Age, Gendar)

Course(CosCode, Title, Unit, Status)

Student_Course(Matric, CosCode, Session, Score)

Note: The primary keys are underlined for the tables.

Save the database name as Stud in the BIN subfolder of the Java
toolkit.

Step 2: Set up the JDBC-ODBC bridge driver via the following


steps:

(i) From the Start Menu, Click on Control Panel


(ii) Double-Click on Administrative tools
(iii) Double-Click on Data Sources (ODBC)
(iv) Click on Add
(v) Select Microsoft Access Driver (*.mdb, *.accdb) on the
next pop-up window, then click on Finish
(vi) Type Studs as the datasource name
(vii) Select the database via the Select button and then click on
OK.

Step 3: Writing the Java Code

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.

All programs that use an ODBC data sources use


sun.jdbc.odbc.jdbcodbcDriver, the JDBC-ODBC bridge driver
included with java. Loading this class into a Java Interpreter requires
the following statement:

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 getConnection(String, String, String) method of


DriverManager can be used to set up the connection. It returns a
reference to a connection object representing an active data
connection. The three arguments of this method are as follows:

 A name identifying the data source and the type of database


connectivity used to reach it
 A username
 A password

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.

The following statement could be used to connect to a data source


called Studs with a username of “Lekan” and a password of “ola”:

Connection con = DriverManager.getConnection( “jdbc:odbc:Studs”,


“Lekan”, “ola”);

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.

The getConnection( ) Method and all others called on a data source


throw SQLException errors if something goes wrong as the data
source is being used. SQL has its own error messages, and they are
passed along as part of SQLException objects.

An SQL statement is represented in Java by a Statement object.


Statement is an interface, so it can’t be installed directly. However,
an object that implements the interface is returned by the
CreateStatement( ) method of a connection object, as in the
following example:

Statement st = con.createStatement();

This Statement object, st, would now be used to conduct an SQL


query by calling the object’s executeQuery(String) method as in the
following example:

ResultSet rs = st.executeQuery("SELECT * " + "FROM Student


" + "WHERE Matno < 400 " + “ORDER BY Gendar”);
System.out.println("Matno \tSurname \tFirst Name \tMiddle
Name \tAge \tGendar\n");

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.

If the SQL query has been phrased correctly, the executeQuery( )


method returns a ResultSet object holding all the records that have
been retrieved from the data source.

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.

These are just the simplest methods available in the Resultset


interface. The methods used depend on the form that the field data
takes in the database, although methods such as getString() and
getInt() can be more flexible in the information they retrieve from a
record.

We can also use an integer as the argument to any of these methods,


such as getString(5), instead of a string. The integer indicates which
field to retrieve (1 for the first field, 2 for the second field and so
on).

After we have pulled the information needed from a record, we can


move to the next record by calling the next( ) method of the
ResultSet object. This method returns a false Boolean value when it
tries to move past the end of a resultset. Normally, we move
through a resultset once from start to finish, after which its contents
cannot be retrieved again.

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.

The database table ‘Student’ used for the following program 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

E69: Retrieving Data from a Table in a Database

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

An instance of ResultSet is returned from executeQuery( ), and one


or more instances may be returned from execute( ). A ResultSet is a
representation of the data returned by your query, and it allows you
to process the results one row at a time. Before you can process a
row, you must move the ResultSet’s cursor (pointer) to that row, and
the row that’s pointed to by the cursor is called the current row.
When a ResultSet is created, the cursor is initially positioned before
the first row.

310
Java for Beginners

It’s helpful to review some ResultSet properties before describing


the methods defined in that interface, because its properties
determine which of a ResultSet’s methods you’re able to use for a
particular instance and how they function.

 Forward-Only vs. Scrollable (Scrollability Type)

Scrollability describes the type of cursor movement that’s allowed,


and a forward-only ResultSet allows the cursor to be moved forward
only one row at a time using the next( ) method. However, with a
scrollable ResultSet, you can use a variety of methods to position the
cursor. It can be moved forward or backward, and it can be moved in
those directions by any number of rows. In addition, it’s possible to
move the cursor to a specific row (in other words, to use absolute
instead of relative positioning), including the first and last rows in
the ResultSet.

 Read-Only vs. Updatable (Concurrency Mode)

ResultSet defines a large number of getXXX() methods that allow


you to read column values from the current row (for example,
getString(), getFloat(), and so on), and it includes a
corresponding updateXXX() method for each getXXX(). While it’s
always possible to call the read/get methods, a ResultSet’s
concurrency mode determines whether you can use the write/update
methods. As its name implies, a read-only ResultSet allows you only
to read the data, while an updatable ResultSet allows you both to
read the data and to modify it through the ResultSet.

 Update Sensitivity

While you’re using a ResultSet to process the results of a query, it’s


usually possible for other users/applications to modify the rows in
the database that were returned by your query. Update sensitivity
indicates whether the ResultSet will reflect changes that are made to
the underlying data after the ResultSet is created. Those updates are

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.

Update sensitivity doesn’t imply that a ResultSet is sensitive to all


types of changes. For example, a ResultSet might be sensitive to row
deletions but not to row updates or insertions.
In addition, a ResultSet’s sensitivity to “changes by others” can be
different from its sensitivity to its own changes (modifications to the
data made through the updateXXX() methods). However,
DatabaseMetaData provides methods that allow you to determine
which types of changes are visible for a given ResultSet type.

 Selecting ResultSet Properties

To set the scrollability, concurrency, and sensitivity properties, you


must specify the appropriate values when creating a Statement. The
code segments shown earlier used the createStatement( ) method that
doesn’t accept any parameter values, but another version of
createStatement( ) allows you to specify two integer values
representing ResultSet properties:

int resultSetType, resultSetConcurrency;


// ...
Statement stmt = con.createStatement(resultSetType,
resultSetConcurrency);

The resultSetType parameter represents a combination of the


scrollability and sensitivity properties, and it should be assigned one
of the following constants defined in ResultSet:

312
Java for Beginners
TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, or
TYPE_SCROLL_SENSITIVE.

The resultSetConcurrency value represents the concurrency mode


for ResultSet instances created by this statement and should be
assigned the value of either CONCUR_READ_ONLY or
CONCUR_UPDATABLE.

You can use these constants and the createStatement( ) method


shown previously to create a Statement that will produce ResultSet
instances with the desired properties. For example, you can use code
similar to the following to create a Statement and request that the
ResultSet instances it creates be scrollable, sensitive to others’
changes, and updatable:

Statement stmt = connect.createStatement


(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);

Note that if you specify a type of ResultSet that’s not supported by


the driver, it won’t generate an error when createStatement() is
called. Instead, the Statement will produce ResultSet instances that
match the type you requested as closely as possible. In this case, for
example, if the driver supports updatable ResultSet instances but not
scrolling, it will create forward-only instances that are updatable.

12.4 PreparedStatement

When you call one of Statement’s execute() methods, the SQL


statement specified is “compiled” by the JDBC driver before being
sent to the DBMS. In many cases, you’ll want to execute multiple
statements that are similar and may differ only by a single parameter
value. For example, you might execute SQL statements like these:

Statement stmt = connect.createStatement();


stmt.executeUpdate(
"UPDATE MYTABLE SET FNAME = 'Jacob' WHERE CUSTID = 123");

313
stmt.executeUpdate(
"UPDATE MYTABLE SET FNAME = 'Jordan' WHERE CUSTID =
456");

stmt.executeUpdate(
"UPDATE MYTABLE SET FNAME = 'Jeffery' WHERE CUSTID =
789");

Compiling each SQL statement can result in poor performance if a


large number of statements are executed. However, this example
illustrates the usefulness of PreparedStatement, which is a subclass
of Statement. PreparedStatement allows you to compile a statement
one time and use substitution parameters to modify the final SQL
statement that’s executed. In this case, for example, you might create
a PreparedStatement using code like this:

PreparedStatement pstmt = connect.prepareStatement(


"UPDATE MYTABLE SET FNAME = ? WHERE CUSTID = ?");

The two question marks (?) in the statement represent substitution


parameters, and you can use the setXXX() methods defined in
PreparedStatement to specify values for those fields.

For example, the following code is functionally equivalent to the


group of statements used earlier:

PreparedStatement pstmt = connect.prepareStatement(


"UPDATE MYTABLE SET FNAME = ? WHERE CUSTID = ?");
pstmt.setString(1, "Jacob");
pstmt.setInt(2, 123);
pstmt.executeUpdate( );
pstmt.setString(1, "Jordan");
pstmt.setInt(2, 456);
pstmt.executeUpdate( );
pstmt.setString(1, "Jeffery");
pstmt.setInt(2, 789);
pstmt.executeUpdate( );

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.

Another advantage of using a PreparedStatement instead of a


Statement is that it partially insulates your application from the
details of creating a valid SQL statement.

The example program below add more data into the Student table:

E70: Inserting Data into a Database 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

The structure of the Table Student after several data insertions is


shown below.

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

An attempt to insert a record with the same matric number to the


table would result into an error. This is because duplication of
records is not allowed with the use of primary key in a table. The
sample output obtained for this observation is shown below:

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 ).

17. System.out.println("Enter the new matric number (e.g. 234: " );


18. String a = input.next( );
19. st.setString(1, a);

33. System.out.println("Enter the new Age: " );


34. String e = input.next( );
35. st.setString(5, e);

However, level of SQL support varies based on the product and


ODBC driver involved.

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.

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

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.

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

12.5 Moving Through Resultsets

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:

 afterLast( ) - Moves to a place immediately after the last


record in the set
 beforeFirst( ) - Moves to a place immediately before the
last record in the set
 first( ) - Moves to the first record in the set
 last( ) – Moves to the last record in the set
 previous( ) – Moves to the previous record in the set.

These actions are possible when the resultset’s policies have been
specified as arguments to a database connection’s createStatement( )
and prepareStatement( ) methods.

For a more flexible resultset, call createStatement ( ) with three


integer arguments that set up how it can be used. Here is an
example:

Statement st = con.CreateStatement (
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY,

320
Java for Beginners
ResultSet.CLOSE_CURSORS_AT_COMMIT);

The same three arguments can be used in the


prepareStatement(String, int, int, int) method after the text of the
statement.

12.8 Dealing With Multiple Tables (Joins)

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.

E71: Retrieving Data from Two Tables

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( ));
}
}
}

12.9 Database Search

Sometimes we may be interested in searching a record or group of


records from a table in a database. Prepared statement is useful in
this case for handling the query. The example below is a program
that searches for a particular student in the Student table in our
database. The program firstly asks for the Matric number of the
student being searched for. If the Matric number is found, the
program prints out his/her Matric number, Surname, Age and
Gender. But if the number is not found in the database table, an
empty record is printed.

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

The query for searching for a record in the database is implemented


with the use of PreparedStatement (Lines 17 – 18). In Line 21, the
place holder (?) in the query is assigned with the Matno (mat) of the
student earlier captured in Lines 13 – 14. The query is finally
executed in Line 24. At the point, the record set pointer rs would be
assigned to the first record in the table.

Note that rs.next( ) specified in Line 26 only tests if there is any


‘next record’ in the table and so it returns a true or false boolean
value.

27. L2: while (true) {

Line 27 while loop is labeled as L2 for the program to be able to


repeat the code again in case the record being searched for is not
found and the user of the program still wants to search for another

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;

However, Line 27 is also used to terminate the entire program if


what we looked for has been found and reported. This is achieved
with the use of break with label in Line 38.

38. break L1;

With this introduction to database handling in Java, powerful


database-driven programs could be developed by you with no stress.

Tutorial Question

1. Think of an information system for a school library,


implement a Java program that can be used for monitoring
borrowing and returning of books in the library.

2. Perform a system analysis study of how your results are


computed in your school. Write a java-based information
system for computing final year results in your department.

326
Java for Beginners

13

Solving Common Coding Problems


13.0 Introduction

This section covers some common problems that you might


encounter when learning the Java language. After each problem is a
list of possible solutions.

13.1 The Problems

Problem 1: The compiler complains that it can't find a class.

 Make sure you've imported the class or its package.


 Unset the CLASSPATH environment variable, if it's set.
 Make sure you're spelling the class name exactly the same
way as it is declared. Case matters!
 If your classes are in packages, make sure that they appear
in the correct subdirectory as outlined in Managing Source
and Class Files.
 Also, some programmers use different names for the class
name from the .java filename. Make sure you're using the
class name and not the filename. In fact, make the names the
same and you won't run into this problem for this reason.

Problem: The interpreter says it can't find one of my classes.

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.

Problem 2: My program doesn't work! What's wrong with it?

The following is a list of common programming mistakes by novice


Java programmers. Make sure one of these isn't what's holding you
back.

 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.

Remember that array indices begin at 0, so iterating over an array


looks like this:

for (int i = 0; i < array.length; i++)


...

 Are you comparing floating-point numbers using ==?


Remember that floats are approximations of the real thing. The
greater than and less than (> and <) operators are more
appropriate when conditional logic is performed on floating-
point numbers.

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.

 Make sure that blocks of statements are enclosed in curly


brackets { }. The following code looks right because of
indentation, but it doesn't do what the indents imply because the
brackets are missing:

for (int i = 0; i < arrayOfInts.length; i++)


arrayOfInts[i] = i;
System.out.println("[i] = " + arrayOfInts[i]);

 Are you using the correct conditional operator? Make sure you
understand && and || and are using them appropriately.

 Do you use the negation operator ! a lot? Try to express


conditions without it. Doing so is less confusing and error-prone.

 Are you using a do-while? If so, do you know that a do-while


executes at least once, but a similar while loop may not be
executed at all?

 Are you trying to change the value of an argument from a


method? Arguments in Java are passed by value and can't be
changed in a method.

 Did you inadvertently add an extra semicolon (;), thereby


terminating a statement prematurely? Notice the extra semicolon
at the end of this for statement:

for (int i = 0; i < arrayOfInts.length; i++) ;


arrayOfInts[i] = i;

329
13.2 Managing Source and Class Files

Many implementations of the Java platform rely on hierarchical file


systems to manage source and class files, although The Java
Language Specification does not require this. The strategy is as
follows.

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 (/):

class name graphics.Rectangle


pathname to file graphics/Rectangle.java

As you may recall, by convention a company uses its reversed


Internet domain name in its package names. The fictional company
whose Internet domain name is taranis.com would precede all its
package names with com.taranis. Each component of the package
name corresponds to a subdirectory. So if Taranis had a graphics

330
Java for Beginners
package that contained a Rectangle.java source file, it would be
contained in a series of subdirectories, as shown below.

When you compile a source file, the compiler creates a different


output file for each class and interface defined in it. The base name
of the output file is the name of the class or the interface, and its
extension is .class, as shown in the following figure.

Like a .java file, a .class file should also be in a series of directories


that reflect the package name. However, it does not have to be in the
same directory as its source. You could arrange your source and
class directories separately, 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.

Definition: A class path is an ordered list of directories or ZIP files


in which to search for class files.

Each directory listed in the class path is a top-level directory in


which package directories appear. From the top-level directory, the
compiler and the interpreter can construct the rest of the path, based
on the package and the class name for the class. For example, the
class path entry for the directory structure shown in the previous
diagram would include classes but not com or any of the directories
below com. Both the compiler and the interpreter construct the path
name to a .class file with its full package name.

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.

Q1. Arrays have been a wonderful computational tool for


solving real life problems such as matrices in Mathematics.
Despite all the computational background of John, he finds
it difficult to employ a ragged array in solving some of his
problems; because not all the rows of the array are
completely filled. The “worst array structure” as coined by
John is shown below:

* * * * *
*
* * *

* * * *

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

Q2. Data sent across Computer Networks has always been


vulnerable to so many types of security threats. Anyway,
data encryption algorithms have been developed over the
years, with some relative problems associated with them.
Akinola (2009) develops a data encryption algorithm
recently, with the following features:
(i) A data to be sent along across a network is taken as
a single string. However, the minimum number of
characters in a string has to be three (3)
(ii) The string is then divided into two roughly equal
substrings, A and B.
(iii) Each of the substrings A and B are then encoded in
a reverse order.
(iv) To further encrypt the string data, vowels in the
substrings are encoded as follows:

Vowel Encoding Number


a 1
e 5
i 3
o 2
u 4

(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.

Q3. CSC Grammar School has just concluded an entrance


examination test for her prospective students. This has been
a yearly routine exercise for the intending students of the
school. As a matter of fact, varied number of students
attends the test yearly. The range of scores in the test always
varies from 0 to 80; 50 being set as the cut-off point for the
admission. The management of the school has just decided
to employ the use of computers to assist them in computing
some statistics from the yearly test results and you have
been contacted on this, being a prospective full-fledged
computer programmer.

Your analysis of the system shows that the following


information are needed from the examination results data:
(i) Total number of students that participated in an
entrance examination test;
(ii) Data and number of students that are admit-able in
a session;
(iii) The average score in the examination;

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
…. …. … ….

Populate the database table with about 20 records or more.

(ii) Implement a java program to read the data from the


database and computes all the information needed by the
school.
(iii) Your outputs, with appropriate sectional information
headings, should be directed to an output file to be
named “out.txt”, and newly created by the program.

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:

Emp. No. Name


Design- Grade Year Basic
ation Level Spent Salary
MC/01 Akinola S. Prod Mgr 08 9 65,000
MC/02 Joy Osiagwu Admin Mgr 06 11 55,000
….. …….. …..

Populate the database table with about 20 records.

(ii) Implement a Pay Roll program for the Company, using a


java class and a tester program.
(iii) Your output should be directed to a text file named
“output.txt”, to be newly created by the program. The
file should contain a tabulated comprehensive monthly
take home of all the staff as well as the individual pay
slips to be printed and cut for each staff.

338
Java for Beginners

List of References

Brian Overland and Michael Morrison (2001). Java 2 in Plain


English, MIT Books.

Deitel H. M. and Deitel P. J. (2004). Java™ How to Program,


Sixth Edition, Prentice Hall Publication.

French C. S. (1984). Computer Science, 3rd Edition, DP


Publications, London, UK.

John R. Hubbard (1999). Schaums Outline of Theory and


Problems of Programming with Java, McGraw-Hill
publications, UK.

Rogers Cardenhead and Laura Lemay (2007). Sams Teach Yourself


JavaTM 6 in 21 Days, Sams Publications, Indiana

Web Resource: java.sun.com

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

You might also like