0% found this document useful (0 votes)
23 views

Java Lecture Note COM 124

Uploaded by

dq2hnq6gck
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Java Lecture Note COM 124

Uploaded by

dq2hnq6gck
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

1.

INTRODUCTION TO OBJECT ORIENTED PROGRAMMING USING JAVA

COM 123 – ND YEAR 1 SECOND SEMESTER LECTURE NOTE

COMPILED BY DR ARAOYE O. I.

NOT FOR SALE

1
1.

Programming Techniques
Programming is meant to solve real problems. Approach to solve real world problems is
referred here as programming techniques
1.6.1 Procedure Oriented Programming (POP) Technique
In the procedure oriented technique exhibits a top-down approach in solving problem in which the
problem is viewed as the sequence of things to be done such as input data, process data and output
result in this order as seen in programming language such as BASIC, pascal and c.
Example in BASIC is shown below

INPUT A, B, C
LET A = B+ C
PRINT A
This program is organized in sequential order and follow a particular logic
The primary focus is on functions. Program are broken down into subprograms known as
functions or procedures

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 we do not model real world
problems very well. This is because functions are action-oriented and do not really corresponding
to the element of the problem.
Some Characteristics exhibited by POP are:
• Emphasis is on doing things (algorithms).

2
1.

• 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.6.2 Object Oriented Programming (OOP) Technique


In this approach the components of program are viewed in term of objects. OOP model
real world objects such as person, account, database e.t.c An object consist of data known
as properties and set of instructions to operate on data known as method integrated into a
unit through a process known as encapsulation. Every object has a unique name. consider
an account object in figure

Figure 1.1: Example of Object

Let the object name be Obj1. Obj1 has the following properties: name, password,
Account number and balance. Obj1 methods are: displayBalance(), displayName(),
displayAccount()

3
1.

In OOP, data of an object is private to the object and cannot be accessed by another
object.
Objects communicate in OOP by sending message to each other through method.
Some of the features of OOP 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 ties together in the data structure.
• Data is hidden and cannot be accessed by external function.
• Objects may communicate with each other through function.
• New data and functions can be easily added whenever necessary.
• Follows bottom up approach in program design.

Exercise 1.1
1. What is programming?
2. Discuss types of Programming Language
3. State the advantages of high-level programming languages over the other
4. Compare the speed of the three major Computer Programming Language
5. Discuss Translator
6. Compare Compiler and Interpreter in term of speed, interpretation method and
execution method.
7. Discuss OOP and POP
8. Describe an object
9. State the advantages of OOP over POP

2.1 Class And Object


A class is an abstract data type (ADT) that models objects. In essence A class is a model
to objects of the same category. It contains data variables known as properties without any
assigned values and methods that will operate on the data. From one particular class you
can get as many objects as you want by assigning new values to the properties of the class
e.g name, password, account number and balance as seen in Figure 1.1.

4
1.

A class gives birth to as many objects as desired by assigning new values and using the
same method as shown in Figure 2.1. A class is like a Mother giving birth to many children
of the same resemblance. By the time you assign new values to the properties of a Class it
becomes an object.

CLASS OBJECT1 OBJECT2 OBJECT3

FIGURE 2.1 Objects derived from a Class Account


One can say that objects are copies or examples of a class. Object has the same structure
as a class but has a name different from the class name. Every object has a unique name
different from other objects. An object is identified by its name. To reference the
properties and method of an object you write Object’s Name dot Property’s name
likewise to reference method of an object you write Object’s Name dot method’s name.
Example object1.name is ARAOYE while object2.name is OLALEKAN. For methods
we have object1.displayBalance, object2.displayBalance and object3.displayBalance
which are expected to show the balance of each object.

2.2 Data Abstraction and Encapsulation

The wrapping up of data and function into a single unit (called class) is known as
encapsulation. Data and 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 direct access by the program is called data hiding
or information hiding.

5
1.

Abstraction refers to the act of representing essential features without including the
background details or explanation. Classes use the concept of abstraction and are defined
as a list of abstract attributes such as height, name, and weight, and function operate on
these attributes. They encapsulate all the essential properties of the object that are to be
created.

2.3 Inheritance

Inheritance is a key concept in OOP where a class can inherit both properties and method
of another class usually such a class is referred to as a sub class to the original class or
mother class. For examples an account class can be sub divided into current account class
and saving account class Student class can be sub divided into undergraduate student class
and postgraduate student class. When a class is derived from another class, the subclass
has access to both the method and properties of the root class which is a concept of
inheritance. Figure 2.2 shows the diagram for inheritance

In OOP, the concept of inheritance provides the idea 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 feature
of both the classes

The real appeal and power of the inheritance mechanism is that it allows the programmer
to reuse a class i.e almost, but not exactly, what he wants, and to tailor the class in such a
way that it does not introduced any undesirable side-effects into the rest of classes.

6
1.

Figure 2.2 Example of Inheritance


From Figure 2.2 object of undergraduate class can inherit the property and method of
student class while saving account class can also inherit the properties and method of the
Account class

7
1.

If u1 is the object name of undergraduate class it is appropriate to write u1.matno and


u1.displayName likewise if c1 is the object name of Current Account class it is
appropriate to write c1.balance and c1.displayBalance. There is no need to write new
methods for sub classes.

2.4 Polymorphism

When a particular operation is being shared by many objects of different classes such
operation exhibits a polymorphism. This is possible in inheritance where all subclasses
shared similar operation. For example a draw operation can be applied on different shape
like triangle, circle, rectangle and square. Each of this shape shared the same interface
irrespective of their instances

Polymorphism is another important OOP concept. Polymorphism, a Greek term, means


the ability to take more than on form. An operation may exhibit different behavior is
different instances. The behavior 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 behaviors in
different instances is known as operator overloading. Different objects responding to the
same message in different ways is called polymorphism.

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 action associated
with each operation may differ.
Polymorphism is extensively used in implementing inheritance.

2.5 Benefits of OOP

1. Through inheritance, we can eliminate redundant code extend the use of existing
• Classes.

8
1.

2. 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 higher productivity.
3. The principle of data hiding helps the programmer to build secure program that
can not be invaded by code in other parts of a programs.

4. It is possible to have multiple instances of an object to co-exist without any


interference.
5. It is possible to map object in the problem domain to those in the program.
6. It is easy to partition the work in a project based on objects.
7. The data-centered design approach enables us to capture more detail of a model
can implemental form.
8. Object-oriented system can be easily upgraded from small to large system.
9. Message passing techniques for communication between objects makes to
interface descriptions with external systems much simpler.
10. Software complexity can be easily managed.

Exercise 2.1

1. Discuss the similarities and differences between class and object


2. Discuss the concept of Inheritance and its benefits
3. Give examples of inheritance
4. Describe polymorphism with example
5. Discuss Data abstraction and encapsulation
6. Describe how to reference properties and method of an object 7. What are the
benefits of OOP?

Features of Java

Following are the notable features of Java:


1. Object Oriented
In Java, everything is an Object. Java can be easily extended since it is based on the
Object model.
2. Platform Independent
9
1.

Unlike many other programming languages including C and C++, when Java is compiled,
it is not compiled into platform specific machine, rather into platform-independent byte
code. This byte code is distributed over the web and interpreted by the Virtual Machine
(JVM) on whichever platform it is being run on.
3. Simple

Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it
would be easy to master.
4. Secure
With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
5. Architecture-neutral
Java compiler generates an architecture-neutral object file format, which makes the
compiled code executable on many processors, with the presence of Java runtime
system.
6. Portable
Being architecture-neutral and having no implementation dependent aspects of the
specification makes Java portable. The compiler in Java is written in ANSI C with a clean
portability boundary, which is a POSIX subset.
7. Robust
Java makes an effort to eliminate error-prone situations by emphasizing mainly on
compile time error checking and runtime checking.
8. Multithreaded
With Java's multithreaded feature it is possible to write programs that can perform many
tasks simultaneously. This design feature allows the developers to construct interactive
applications that can run smoothly.
9. Interpreted
Java byte code is translated on the fly to native machine instructions and is not stored
anywhere. The development process is more rapid and analytical since the linking is an
incremental and light-weight process.
11. High Performance
With the use of Just-In-Time compilers, Java enables high performance.
10
1.

12. Distributed
Java is designed for the distributed environment of the internet.
13. Dynamic
Java is considered to be more dynamic than C or C++ since it is designed to adapt to an
evolving environment. Java programs can carry an extensive amount of run-time
information that can be used to verify and resolve accesses to objects at run-time.

3.3 How to Compile and Run Java Program

Compiling and running a java program is very easy after JDK installation. Following are
the steps −
1. Open a command prompt window and go to the directory where you saved the java
program say your java filename is MyjavaProgram.java. Note your filename must
be the same as your main class name. We shall learnt about this in the later chapter
2. Assume it's C:\. Type 'javac MyJavaProgram.java' and press enter to compile your
code. If there are no errors in your code, the command prompt will take you to the
next line (Assumption: The path variable is set).
3. Now, type ' java MyJavaProgram ' to run your program. You will be able to see
the result printed on the window.
Note the program in this book is compiled using NetBeans IDE 8.0.2. We shall learnt about
NetBeansIDE later in the book
3.5 Java Program Structure
Java generally has the program structure as shown below

Import statements;

Classes declaration;

Main class declaration;

Main method declaration;

Body of main method;

End of the program

11
1.

Figure 3.6: General Structure of Java Program


A simple java structure is what is what is displayed in Figure 3.5 as show below

package draraoyebook;

/**
@author Dr Araoye
*/
public class DRARAOYEBOOK {

public static void


main(String[] args) { // TODO
code application logic here
}

Figure 3.7 Example of Java Simple Structure


Every java program as a main class name which is also the name of java file and a main
method where instructions in Java are written. The name of the class here is
DRARAOYEBOOK and main class syntax is

Public class <classname> where class name is user defined name. The class name is
followed by an open curly brace {. After the brace bracket then the main method name
is declared which is compulsory for every java program The main method is written
thus public static void main(String[] args). This is equally followed by an open brace
bracket as seen in Figure 3.7. Then the body of instructions are written in the main
method and then closed by curly brace brackets which is equivalent to number of open
brace bracket as seen in Figure 3.7. The number of open curly brace is two and the
number of close curly brace is two. Writing of the body of the method is a major we
shall discover in later chapters. Note: The curly braces {} marks the beginning and the
end of a block of code.

3.6 A Simple Java Program

12
1.

public class DRARAOYEBOOK {


public static void main(String[] args) {
System.out.println("You are welcome to Dr Araoye Class");
System.out.println("This is a demonstration of simple Java Program");
}
}

Example of java instruction is shown under main method as listed below.


System.out.println("You are welcome to Dr Araoye Class");
System.out.println("This is a demonstration of simple Java Program");
System.out.println is a statement java that directs output to the display unit. We shall
learnt more about it in the later chapter

3.7 Java rules for assigning naming Components

All Java components require names. Names used for classes, objects, variables, and
methods are called identifiers. In Java, there are several points to remember about
identifiers. They are as follows -
1. All identifiers should begin with a letter (A to Z or a to z), currency character ($)
or an underscore (_).
2. After the first character, identifiers can have any combination of characters.
3. A keyword cannot be used as an identifier.
4. Most importantly, identifiers are case sensitive. Examples of legal identifiers: age,
$salary, _value, __1_value. Examples of illegal identifiers: 123abc, -salary.
5. Class: Names should be in CamelCase. Use nouns because a class is normally
representing something in the real world. CamelCase (also known as Upper

13
1.

CamelCase) is where each new word begins with a capital letter e.g.,
AccountNumber, StudentName, StudentAge
6. Packages: Names should be in lowercase e.g draraoye book as seen in figure 3.7
7. Method : Name is written in mixed case. Mixed case (also known as Lower
CamelCase) is the same as CamelCase except the first letter of the name is in
lowercase (e.g. displayArea(), calculateArea(). showName e.tc
8. Variables: Names should be mixed case
9. Objects: Names should be in mixed case
10. Interface: names should be upper Camelcase
11. Constant: names should be in upper case

Exercise 3. 1

1. Write short history of java


2. List five important features of java
3. Write Java Program Structure
4. Explain a simple syntax structure of java program
5. Write a simple java program
6. Write on how to compile and run java program using C prompt
7. Write on how to use NetBeans IDE
8. Describe the code area of NetBeans IDE
9. Describe the similarity between java file name and main class name
10. What are the identifiers in Java? State the general rules for identifiers in java
11. Is java case sensitive?
12. Describe the following cases with examples Upper Camelcase, mixed case.
13. Describe appropriate case for the following with examples : interface, package,
class, object, constant, variables and methods

14
1.

VARIABLE, DATA TYPES AND COMMENTS

4.1 Introduction

Variables are memory location where data are stored. Every data has a unique memory
address which is normally referred to as a variable. A simple illustration of variable and
data relationship is shown in Figure 4.1

Figure 4.1 variable and data Relationship

The relationship between variable and data is that when you get variable of a data, you can
access the data. When you get A then you can access 5 from Figure 4.1. You need to know
the right variable for your data for easy access.

A variable is an identifier as discussed in Section 3.6 and it must follow the naming
rules. Your variable’s name must be meaningful to avoid confusion.
Variable stores data of different types and are of different sizes.

A data can be numeric or non-numeric. Examples of data that are numeric are 123, 3.142,
3x108 e.t.c. A non- numeric data type consists of characters or combination of characters
e.g “A”, “Total” true, e,tc. You need to know the various data types in java so as to
associate correct data type to a variable.

In Java a variable must specify the type of data it will stores. Variables in java are written
in mixed case as discussed in Section 3.6

4.2 Data Types in Java

Data types are divided into two groups: Primitive data types and Primitive data types
Data types are divided into two groups:

15
1.

Table 4.1 Primitive Data Types in Java


Primitive Data Type Size Description
Byte 1 Byte Stores whole numbers from -128 to 127
Short 2 Bytes Stores whole numbers from -32,768 to 32,767
Int 4 Bytes Stores whole numbers from -2,147,483,648 to
2,147,483,647
Long 8 Bytes Stores whole numbers from - ,223,372,036,854,775,808
to 9,223,372,036,854,775,807

Float 4 Bytes Stores fractional numbers. Sufficient for storing 6 to 7


decimal digits

Double 8 Bytes Stores fractional numbers. Sufficient for storing 15


decimal
Digits
Boolean 1 Bit Stores true or false values
Char 2 Bytes Stores a single character/letter or ASCII values

Non-primitive data types:

String

Arrays

Classes

We shall discuss about non- primitive data types in a later Chapter.

Exercise 4.1
Identify the correct data type for the following data items
1. Serial-number
2. Average score
3. Age
4. Are you a student? (Y/N)
5. Number of items sold in a Super-Market

16
1.

6. Five is greater than Eight


Note. You must write data example before you can assign data type.

4.3 Specifying a Variable of Data Type

In your java program, you must specify that your variable is of data type before you are
allowed to store data into it.
The rule for specifying a variable as a data type:
<data-type><space> <variable-name>;
From class Exercise 4.1, we can specify data type for the data items as
follows: int seriaNumber; double averageScore ; byte age; char
response ; short noItemSold ; boolean reply ;
Note the semi-colon at the end of each line.

Exercise 4.2

Give variable’s names for the following values and specify the most appropriate data
type
1. 3.142
2. 8X1015
3. 45678999
4. B
5. True
6. 20
7. 2x10-6

8. 1234456789456777
9. false
10. 123456
4.4 Writing of Comments in Java

Comments are used to document and describe what a particular part of program is doing
without following the rules of the program. Program compiler ignores comment
statements. A comment s can be single line or multiple lines.

17
1.

4.4.1 Single- Line Comment

For a single line comment java uses double forward slashes (\\) to write the comment.
Example, refer to Figure 3.5 The rule is
\\<Comment>
\\ This is a single line comment
\\ This is a demonstration of my program

4.4.2 Multiple -Lines Comment

Multiple-line comments start with /* and ends with */


For multiple lines comment, the rule is
/*
Body of the comment
*/
Refer to Figure 3.5 to study multiple-Lines comment.
Example
/*
This program is written and Compiled by Dr Araoye O.I.
Institution: Federal Polytechnic, Ado-Ekiti, Ekiti State, Nigeria.
Department: Computer
Science Rank: Chief Lecturer
e-mail:[email protected]
Date:28/06/2022
*/

5.1 print() and println() Methods

Consider the program in Section 3.5 and these statements in the program
System.out.println("You are welcome to Dr Araoye Class");
System.out.println("This is a demonstration of simple Java Program");

These statements print the statements in double quote to the computer monitor. This is an
example of output statement.
18
1.

System is a built-in Java class that contains method, such as out , which is short for
"output". The println() method, short for "print line", is used to print a value to the screen
or a file.
print() and println() method do the same function but the difference is println() method
directs the output to one line per instruction while print() does not insert a new line after a
previous output

5.2 Various ways the println() Method can be used


5.2.1 Directing a String to output. A string is combination of two or more characters in
double quote. Example is "You are welcome to Dr Araoye Class"
The rule for string is
System.out,println (String);
Example
System.out.println("You are welcome to Dr Araoye Class");
Note that class’s name starts with capital letter while method’s name starts with small
letter.

5.2.2 Directing a variable to the output

Example
int a =5;
System.out.println(a);
Here a is an integer variable and not a string and its value is 5.
The rule is
System.out.println(variable’s name);

5.2.3. Output using concatenation operatot “+”

Concatenation operator is used to join two different output on a single line.


The rule is
System.out.println(value1+value2+Value3..+
valuen); Example From 5.2.2. we can write
the output as int a =5;

19
1.

System.out.println(“The value of a
is”+a); Here string and variable are
joined together.
The output will be
The value of a is 5
Consider Program example 5.1 below and the output

Program Example 5.1 public


class ProgramExample5_1{
public static void
main(String[] args) { // a, b,c
variables assigned values
int a=10; int b=20; int
c=a+b;
System.out.println("The value of a is "+a);
System.out.println("The value of b is "+b);
System.out.println("The value of c is "+c);
}
}

Program Output Example 5.1

Exercise 5.1

20
1.

Write java program to do print the following as a single line output.


1. Print a variable assigned a value with the name
2. Print two different variables assigned two different values with their names
3. Print two different strings

5.3 Assignment Statement

The function of assignment statement is to assign a value to a variable; it may be a direct


value or value of an expression. Assignment operator (=) is used in assigning a value to a
variable.
The rule for assignment statement is
<variable-name>=value;
<variable-name>=Expression;

5.3.1 Direct value Assignment Statement

Consider class exercise 4.1, we can assign direct value to the


variables thus int seriaNumber =1; double averageScore = 67.5 ;
byte age = 23 ; char response = “Y” ; short noItemSold = 50 ;
In Program example 5.1, you can identify direct value assignment statements

5.3.2 Assigning the value of an Arithmetic expression to a Variable

An arithmetic expression evaluates to a value which can be assigned to a variable. An


example from Program example 5.1 is int c=a+b; a is added to b and the result is
stored in c.

5.4 Variable and Constant

The difference between a variable and a constant is that variable’s value can be changed
during program execution while constant’s value cannot be changed during program
execution.

5.4.1 How to declare Constant in Java

21
1.

The keyword final is used in conjunction with the variable declaration in order to make
the variable a constant. According to java’s rule, a constant must be written in capital
letter. To convert the variables in Section 5.3.1 to constant the keyword final is added to
them thus:
final int seriaNumber =1;

final double averageScore

= 67.5 ; final byte age =

23 ; final char response =

“Y” ; final short

noItemSold = 50 ;

Program Example 5.2

public class

ProgramExample5_2{

public static void main(String[]


args) { // Author: Dr Araoye, O.
I.
final int
A=50; final
int B =60;
int f = A+1; // Adding 1 to
constant A int g = B+2; //
adding 2 to constant B int
c=A+B;
int e = f+g;
System.out.println("The value of CONSTANT A is "+A);
System.out.println("After 1 is added to CONSTANT A the value is "+f);
System.out.println("The value of CONSTANT B is "+B);
System.out.println("After 2 is added to constant B the value is "+g);

22
1.

System.out.println(" Addition of A and B


is "+c); System.out.println(" Addition of
f ang g is "+e); }
}

5.5 Arithmetic Operators

These are the operators that are used to evaluate arithmetic expression. The operator, its
meaning and example are described in Table 5. 1
Table 5.1 List of Arithmetic Operators
Operator Meaning Example
+ Addition c = a+b;

- Subtraction c = a-b;

/ Division c = a/b

* Multiplication c = a*b;

% Modulus (Gives reminder c =a%b; 5%2 =1


after division)
Consider Program Example 5.3 to study the effects of the operators

Program Example 5.3

public class
ProgramExample5_3 { public
static void main(String[] args)

23
1.

{ // Written by Dr Araoye O.
I.

int a=50; int b = 8 ; double c =


a+b; // Addition operator double d
= a-b; // subtraction operator
double e=a/b; // division operator
double f = a*b; // multiplication
operator double g = a%b; //
modulus operator
System.out.println("The value of a
is "+a);
System.out.println("The value of b is "+b);
System.out.println("The value of c is "+c);
System.out.println("The value of d is "+d);
System.out.println("The value of e is "+e);
System.out.println("The value of f is "+f);
System.out.println("The value of g is "+g);
}
}

Output: Program Example 5.3

5.6 Increment and Decrement Operators

Increment operator is used to increase the value of an object by 1 and it is denoted as ++.
Increment operator can be prefix or postfix on an object. Example of prefix is ++a while

24
1.

example of postfix is a++. The difference in prefix and postfix is that prefix increase the
value of object by 1 before execution while postfix increase the value of an object by 1
after execution. The decrement operator decreases the value of an object by 1 and it is
denoted as --. It can be used as prefix and postfix in the same way as increment operator.
Study Program example 5.4 and
Program Example 5.5 to see the effect of prefix and postfix increment and decrement
operators

Program Example 5.4


public class
ProgramExample5_4 { public
static void main(String[] args)
{ // Written by Dr Araoye O.
I.
int a=50; int b = 30 ; int c =
a++; // postfix increment
operator int e= b--; // postfix
decrement operator
System.out.println("The value of a for postfix increment operator is "+c);
System.out.println("The value of a after postfix increment operator is "+a);
System.out.println("The value of b for postfix decrement operator is "+e);
System.out.println("The value of b after postfix decrement operator is "+b);
}
}

Program Output Example 5.4

25
1.

Program Example 5.5

public class
ProgramExample5_5 { public
static void main(String[] args) {
// Written by Dr Araoye O. I.

int a=50; int b = 30 ; int c


= ++a; // prefix increment
operator int e= --b; // prefix
decrement operator
System.out.println("The value of a for prefix increment operator is "+c);
System.out.println("The value of a after prefix increment operator is "+a);
System.out.println("The value of b for prefix decrement operator is "+e);
System.out.println("The value of b after prefix decrement operator is "+b);
}
}

Program Output Example 5.5

5.7 Scanner Class

Scanner class is the class that has a method called System.in which can be used to get
input from the computer keyboard. Unlike System.out , you have to create object of the
class before you can use the methods of the class. Scanner class is under a package called
util. A package consists of related classes. Under a package, you can import a single class
or all the classes at a time. Java has many in-built packages.

26
1.

Assignment 5.1

List ten packages in Java and their classes

5.7.1 Import Statement

Before you can use an in-built class you have to import it. Import statement is used to
import a class or set of classes. The rules is
Rule 1: To import a class: import java.<package_name.class_name>;
Example: import java.util.Scanner;
Rule 2 : To import all classes in a package: import java.<package_name.*>;
Example import java.util.*;
Remember that package’s name is written in small letters, class’s name begins with
capital letter.

5.7.2 Creating Object of Scanner class

There are two major ways to create object


of a class 1. Declaring object of a class
The rule:
<class_name><space><user_defined_object_name>
Example
Scanner myInput
2. Creating object of the class
To create object of a class the keyword new is used as follows in the rule below
<object_name>= new <class_name>;
To create myInput object of the Scanner, it follows then
myInput = new Scanner (System.in);
The two rules can be combined as a rule thus
<class_name><space><user_defined_object_name>= new <class_name>;
Hence we can create object of a Scanner thus
Scanner myInput = new Scanner (System.in);

5.7.3 Input Methods of Scanner objects

27
1.

Once an object of a scanner is created, the methods of the class be accessed by the
objects as discussed in Section 2.1

There are different Scanner methods for obtaining data from keyboard. The method to be
used depends on the nature of the data. The table below shows data types and methods to
be used for each data type.
Data Type Method Example
Double nextDouble( ) double a = myInput.nextDouble( );
Integer nextInt( ) int b = myInput.nextInt( );
Float nextFloat( ) float c = myInput.nextFloat( );
Byte nextByte( ) byte d = myInput.nextByte( );
Short nextShort( ) short s = myInput.nextShort( );
Long nextLong ( ) long l = myInput.nextLong( );
String nextLine( ) String s =myInput.nextLine( );

Program Example 5.6

This program calculates simple interest I = PRT/100. P(principal), R (Rate) and


T(Time) are declared as double data type and their values taken from keyboard.
import java.util.Scanner;

public class
ProgramExample5_6 { public
static void main(String[] args) {
// Written by Dr Araoye O. I.
double p,r, t, i;
Scanner myInput = new Scanner
(System.in); System.out.println("Enter
Value for Principal"); p=
myInput.nextDouble();
System.out.println("Enter Value for
Rate"); r= myInput.nextDouble();

28
1.

System.out.println("Enter Value for


Time"); t= myInput.nextDouble();
i=p*r*t;
System.out.println("The Interest is "+ i);
}
}

Program Output Example 5.6

Program Example 5.7

This program example captures different


data types import java.util.Scanner; public
class ProgramExample5_7 { public static
void main(String[] args) { // Written by
Dr Araoye O. I.
Scanner myInput = new Scanner (System.in);
System.out.println("enter your name");
String name =
myInput.nextLine();
System.out.println("enter
your age"); int age =
myInput.nextInt();

29
1.

Scanner myInput2 = new Scanner (System.in);


System.out.println("enter your matric number");
String matrno = myInput2.nextLine();
System.out.println("enter your average
score"); double ave = myInput.nextDouble();
System.out.println("enter your department");
String dept = myInput2.nextLine();

System.out.println("Your name is "+name );


System.out.println("Your age is "+age );
System.out.println("Your matric number is "+matrno );
System.out.println("Your department is "+dept );
System.out.println("Your average score is "+ave );
System.out.println("Your Are Welcome "+name );

}
}

Program Output Example 5.7

30
1.

5.8 Java Math Class

The Java Math class has many methods for performing basic numerical operation. Table
5.1 contains various Java Math methods, descriptions and Examples. Math class is in
lang package.

Table 5.1 Java Math Methods, Description and Examples


Java Math methods Descriptions Examples
Math.max(x,y) It returns the highest value of Math.max(10,20)

x and y
Math.min(x,y) It returns the minimum value Math.min(10,20)
of x andy

Math.sqrt(x) It returns the square root of x Math.sqrt(144)


Math.abs(x) It returns absolute (positive) Math.abs(-5.6)
value of x

Math.random() It returns a random number int randomNum =


between 0.0 (inclusive), and (int)(Math.random() * 101); a
1.0 (exclusive) random number between 0
and 100,

Math.acos() It returns the arc cosine of an


angle, in the range of 0.0
through pi.

Math.toRadians() converts an angle measured in Math.toRadians(x);


degrees to an approximately
equivalent angle measured in
radians.

Math.pow(x,y) It returns the value of the first Math.pow(4,2)


argument raised to the power
of the second argument. The
return type of the pow()
method is double.

31
1.

Math.round() It is used round of the decimal


numbers to the nearest value.
Math.log() This method returns the
natural logarithm (base e) of a
double value as a parameter.
Math.log10() The java.lang.Math.log10() is
used to find out
the Logarithmic
of a number
when the base is 10.
This method returns the base
10 logarithms of a double
value.
Math.sin() The java.lang.Math.sin() is
used to return the
trigonometric sine of an angle.
This method returns a value
between -1 to 1.
Math.cos() The java.lang.Math.cos(double
a) returns the trigonometric
cosine of an angle.

Program Example 5.8


The program shows output for various Math
methods public class ProgramExample5_8 {
public static void main(String[] args) { //
Written by Dr Araoye O. I. double x= 10;
double y = 20; double z=144;
System.out.println("Minimum of x and y = "+Math.min(x, y));
System.out.println("Maximum of x and y = "+Math.max(x, y));
System.out.println("Power of x to 2 = "+Math.pow(x, 2));
System.out.println("Square root of z = "+Math.sqrt(z));

}
}

Program Output Example 5.8

32
1.

Exercise 5.2
1. State the difference between a variable and a constant
2. Write java statement to declare a constant
3. What is assignment statement? Give examples of assignment statements
4. Discuss increment and decrement operators
5. Write the output of the program below public static void main(String[] args) {
// Written by Dr Araoye O. I.
int a=44; int b = 45 ; int c =
++a; // prefix increment operator
int e= --b; // prefix decrement
operator
System.out.println("The value of a for prefix increment operator is "+c);
System.out.println("The value of a after prefix increment operator is
"+a);
System.out.println("The value of b for prefix decrement operator is
"+e); System.out.println("The value of b after prefix decrement operator
is "+b);
}

}
6. Write java rules to the following
i. Declaring object of
a class ii. Creating
object of a class
7. In a tabular form, write various methods of scanner object to capture various data
types

8. Write a program to capture your biodata and display them on the computer
monitor

9. Write java program for the following expressions

i. y = a2+2ab+b2

ii. 𝑥 = −𝑏 + √(𝑏2 − 4𝑎𝑐)

33
1.

iii.

iv. 𝑦 = 𝑎(𝑥 − ℎ)2 + 𝑘

v. v = 𝜋𝑟2ℎ
vi.

vii.

SELECTION STATEMENTS
6.1 Introduction

Selection statements are also known as IF statements. They are used to select a statement
out of parallel alternative statements based on its truth condition. It is like an objective
question where only one answer is correct. An application of IF stamen can be found where
a grade is assigned to a score based on the range of a score. Below is an example of range
of scores and grade

Score Range Grade

0-39 F

40-44 E

45-49 D

50-59 C

60-69 B

70-100 A

Figure 6.1: IF Example

34
1.

6.2 Conditional Statements, Relational and Logical Operators

Selection statement uses conditional statement to evaluate its expression. A conditional


statement evaluates to true (1) or false (0). If the condition is true, the expression that
follows the condition will be evaluated otherwise ignored.

Conditional expression uses relational operators and logical operators to evaluate its
condition.
Table 6.1 shows relational operators, their meanings and examples

Table 6.1 Relational Operators in Java


Relational Operators Meaning Example
< Less than a<b
<= Less than or Equal to a<=b
> Greater than a>=b
== Equal to a==b
!= Not Equal to a!=b
Logical operators combines two relational relational expressions. Logical operators are
shown in Table 6.2
Table 6.2 Logical Operators in Java
Logical Operators Meaning Examples
&& Logical AND. E1 &&E2.Where E1 and E2 are relational
expressions This will produce true if both E1 and
E2 are true otherwise false
|| Logical OR E1|| E2. This will produce true if either E1 or E2 is
true or both are true otherwise false

! Logical NOT It reverses current status of a boolean expression.


Exercise 6.1
1. Given that a = 8, b=10. Write answers for the following expressions
i. a<b ii, a<=b iii. a>=b iv. a==b v. a!=b
vi a < b && a<=b vii a>=b&& a!=b viii a==b|| a < b ix a<=b||
a>=b x. ! (a>=b&& a!=b)

35
1.

2. Produce the truth table for Logical AND, OR and NOT

6.3 Various Selection Statements


There are various format of selection statements as explained in the sections below

6.3.1 Simple if Statement

This is a statement with only one path. It evaluates its expression only if the condition is
true otherwise ignores it. The rule is if (conditional_ Statement) {

// block of code to be executed if the condition is true


}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
Consider program example 6.1

Program Example 6.1


public class ProgramExample6_1
{ public static void
main(String[] args) { //
Written by Dr Araoye O. I.
int x = 20; int y = 19; if
(x>y)System.out.println("X is greater
than Y");
}
}

Program Output Example 6.1

In this statement, if X is less than Y, there will not be output.

36
1.

6.3.2 if..else Statement


This statement provides alternative statement to be executed if the first statement is false.
The second statement is taken to be true. The rule is if (conditional_Statement) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Program example 6.2 shows where X is less than Y and the output

Program Example 6.2 public


class ProgramExample6_2{
public static void main(String[]
args) { // Written by Dr
Araoye O. I.
int x = 20; int y = 22; if
(x>y)System.out.println("X is greater
than Y"); else
System.out.println("Y is greater than X ");
}
}

Program Output Example 6.2

6.3.3 if..else if Statement


The statement allows to provide many alternative statements out of which one is true. Once
a true statement is encountered others are ignored. It is first statement that is true that is
executed. The is if (conditional_Statement 1)
{

37
1.

Block of Statements 1
} else if
(conditional_Statement
2)
{
Block of Statements 2
}
else if (conditional_Statement 3)
{
Block of Statements 3
} else if
(conditional_Statement
4)
{
Block of Statements 4
} else if
(conditional_Statement n-
1)
{
Block of Statements n-1
}

else
{
Block of Statements n
}

Consider Figure 6.1, The java statements to print grade is given in program example 6.3

Program Example 6.3


import java.util.Scanner;
public class
38
1.

ProgramExample6_3 { public
static void main(String[] args)
{ // Written by Dr Araoye O.
I.
Scanner myScore = new Scanner (System.in);
System.out.println("Enter your Score"); double score =
myScore.nextDouble(); if ((score>=70)&&(score<100))
System.out.println(" GRADE A"); else if
((score>=60)&&(score<70)) System.out.println(" GRADE
B"); else if ((score>=50)&&(score<60)) System.out.println("
GRADE C"); else if ((score>=45)&&(score<50))
System.out.println(" GRADE D"); else if
((score>=40)&&(score<45)) System.out.println(" GRADE E");
else
System.out.println(" GRADE F");
}
}

Program Output Example 6.3

39
1.

Program Example 6.4


This is a program to calculate quadratic equation ax2+bx+c =0 using quadratic formula

i.
import java.util.Scanner;
public class

40
1.

ProgramExample6_4 { public
static void main(String[] args)
{ //Written by Dr Araoye O.
I.
double a,b,c,r1,r2,d;
Scanner input = new Scanner
(System.in);
System.out.println("Enter value for
a"); a= input.nextDouble();
System.out.println("Enter value
for b"); b= input.nextDouble();
System.out.println("Enter
value for c"); c=
input.nextDouble(); d=b*b-
4.0*a*c; if (d==0) {
r1=-
b/(2*a);
r2=r1;
System.out.println("X1="+r1);
System.out.println("X2="+r2);
}
else if (d>0.0){
r1 =(-b+Math.sqrt(d))/(2.0*a);
r2=(-b-Math.sqrt(d))/(2.0*a);
System.out.println("X1=
"+r1);
System.out.println("X2= "+r2);
} else
System.out.println("COMPLEX ROOT");
}

41
1.

Program Output Example 6.4

6.4 Java Switch Statements

switch statement to select one of many code blocks to be executed.


The rule is switch(expression) { case x: // code block break; case y: //
code block break; default: // code block }

The switch expression is evaluated once.


The value of the expression is compared with the values of each case .
If there is a match, the associated block of code is executed.
The break and default keywords are optional

Program Example 6.5

public class
ProgramExample6_5 { public
static void main(String[] args) {
// Written by Dr Araoye O. I.
int month =
2; switch
(month) {
case 1:

42
1.

System.out.println("Ja
nuary"); break; case
2:
System.out.println("Fe
bruary"); break; case 3:
System.out.println("Ma
rch"); break; case 4:
System.out.println("Ap
ril"); break; case 5:
System.out.println("Ma
y"); break; case 6:
System.out.println("Ju
ne"); break; case 7:
System.out.println("Jul
y"); break; }
}
}

Program Output Example 6.5

6.5 Java Conditional Expression Operator

The conditional operator is also known as the ternary operator. This operator consists of
three operands and is used to evaluate Boolean expressions. The goal of the operator is to
decide; which value should be assigned to the variable. The operator is written as: variable
y = (expression)? value if true: value if false

43
1.

Program Example 6.6 public


class ProgramExample6_6 {
public static void
main(String[] args) { //
Written by Dr Araoye O. I. int
a, b, c ; a = 20; b= 30; c =
(a>b) ? 20: 30;
System.out.println("Value of c is: " + c);
}
}

Program Output Example 6.6

Exercise 6.2

1. Write a java program to calculate cumulative-point based on following conditions


Cumulative-point = course unit x grade-point. Use the table below to calculate
cumulative-point for a single course and print the grade
Score Grade Grade-point
75 and above A+ 4.0
70-74 A 3.5
65-69 AB 3.25
60-64 B 3.0
55-59 BC 2.75
50-54 C 2.5
45-49 D 2.25
40-44 E 2.0

44
1.

Below 40 F 0.0

2. Write the output for the following conditional operators given that a = 40 and b =
60
i. c= (b>a)? 50:100 ii. x= (a>b)? 150:200 iii. y= (a==b)? 250:400

LOOP STATEMENTS

Loop statements are also known as iterative statements. They are used for repeated
execution of a statement or block of statements as long as condition binding the loop is
true. Every loop statement has three major components

1. Initialization of control loop variable known as counter


2. Condition for the loop
3. Update of control loop variable

Various forms of loop statements are discussed in the next sections

7 .1 while Statement
The rule for while statement:
Initialization of control variable;
While (Boolean Condition) {
Block of statements;
Update of control variable;
}
Program Example 7.1
public class
ProgramExample7_1 { public
static void main(String[] args)
{ // Written by Dr Araoye O.
I.

45
1.

int i =
0;
while
(i
<10) {
System.out.println("Value of
i = " +i); i++;
}}}

Program Output Example 7.1

Program Example 7.2


Write a program to calculate the sum of the first fifty integer numbers
1+2+3…+50 public class ProgramExample7_2 { public static void
main(String[] args) { // Written by Dr Araoye O. I.
int sum
=0;
int i = 1;
while (i
<= 50) {
sum =

46
1.

sum + i;
i++;
}
System.out.println ("The sum of the first fifty integer number is "+sum);
}
}

Program Output Example 7.2

7.2 Do…while Loop

The do..while loop is a variant of the while loop. This loop will execute the code block
once, before checking if the condition is true, then it will repeat the loop as long as the
condition is true. The rule is
Control variable
initialization; do {
Block of Statements ;
Update of control variable;
}
while (Boolean Conditions);
The do…while loop version of Program example 7.1 and example 7.2 are written as
example 7.3 and example 7.4 respectively.

Program Example 7.3

47
1.

public class
ProgramExample7_3 { public
static void main(String[] args)
{ // Written by Dr Araoye O.
I. int i = 0; do {
System.out.println("The value of i
is = "+i); i++; } while (i <10);
}
}

Program Output Example 7.3

Program Example 7.4


public class
ProgramExample7_4 { public
static void main(String[] args)
{ // Written by Dr Araoye O.
I.
int
sum
=0;
int i =
1; do {

48
1.

sum =
sum +
i; i++;
}
while
(i
<=50);
System.out.println ("The sum of the first fifty integer number is "+sum);
}
}

Program Output Example 7.4

7.3 For… Statement

The rule is
for (control-variable initialization; Boolean-condition; update of control-
variable) {
Block of statements to be executed;
}// End of for..Statement

Example
for ( i=0; i<10; i++) {
System.out.println (“ The value of I = “ +i);
}
Program Example 7.5 public
class ProgramExample7_5 {
public static void
main(String[] args) { //

49
1.

Written by Dr Araoye O. I. for


(int i = 0; i<10; i++) {
System.out.println ("The value of i = " +i );
}
}
}

Program Output Example 7.5

Program Example 7.6

public class
ProgramExample7_6 { public
static void main(String[] args)
{ // Written by Dr Araoye O.
I. int sum = 0; for (int i =
1; i<=50; i++) { sum = sum +
i;
}
System.out.println ("The sum of first fifty integers is = " +sum);
}
}

Program Output Example 7.6

50
1.

7.4 Nested for Statement

A for statement can be nested in another for statement. The outer statement controls the
inner statement. The inner statement will stop executing when the condition binding the
outer statement expires. Two integer control variables are required for nested for
statement. The rule is
for (control-variable1 initialization; Boolean-condition; update of control-
variable1) { for (control-variable2 initialization; Boolean-condition; update of
control-variable2) { Block of statements to be executed;
}// End of loop2
}// End of loop1

Example
//loop of i for(int
i=1;i<=4; i++){
//loop of j for(int
j=1;j<=3;j++){
System.out.println(
i+" "+j);
}//end of i
}//end of j

Program Example 7.7

public class
ProgramExample7_7 { public
static void main(String[] args)
{ // Written by Dr Araoye O.

51
1.

I. //loop of i for(int i=1;i<=4;


i++){ //loop of j for(int
j=1;j<=3;j++){
System.out.println(i+" "+j);
}//end of i
}//end of j
}
}

Program Output Example 7.7

Program Example 7.8

52
1.

// This is a program to calculate the factorial of a


number (N!) import java.util.Scanner; public class
ProgramExample7_8 { public static void
main(String[] args) { // Written by Dr Araoye O. I.
Scanner myInput = new Scanner
(System.in); System.out.println("Enter
the Factorial number"); int number =
myInput.nextInt(); int i,fact=1;
for(i=1;i<=number;i++){ fact=fact*i;
}
System.out.println("Factoria of "+number+ " is "+ fact );
}
}
Class Exercise 7.1

1. Define a Loop
2. Discuss various form of Loop statements in Java
3. Discuss with program example, the difference between while..do and do..while
4. Write a program to generate the series 1+22+32+42…n2
5. Write a program to print numbers from 1 to 50.
6. Write a program to calculate the sum of first N natural number, where N is
entered through the keyboard
METHODS

8.1 Methods in Java

Methods are subprograms in a main program which can be called t as an entity by its name.
Methods also known as functions are written to perform a particular task. A method can
return a value to a variable or may not return a value which is usually refers to as void
method. A method can be static or public. When it is static, there is no need to create object
of such method and usually written under main class but when it is public there is need to

53
1.

create object of such method and it is written outside main class. We shall look at static
method in this chapter and public method under classes and objects chapter

8.2 Static void method

Static void methods are written before main method and are called within the body of main
method. Static method can have a passing parameters or may not have. Subsequent
examples in this section shows non.passing parameters static void method and passing
parameter static void method. The general syntax structure of void method is
<static><void><method_name>( Parameters) {
Body of the code
}
Example
Void static areaCylinder ( ) {
Body of code
}
To call the method from the main method body, the rule is:
The methods’name followed by
semi colon method_name();
Example areaCylinder ( ); See
program example 8.1 Program
example 8.1 shows a method used
to calculate the area of a cylinder
and the area called in the body of
the main method.

Program Example 8.1 import


java.util.Scanner; public class
ProgramExample8_1 { static void
areaCylinder () { // declaration of method
double radius,height,area; final double pi
=3.142;

54
1.

Scanner myInput = new Scanner


(System.in);
System.out.println("Enter Radius" );
radius = myInput.nextDouble();
System.out.println("Enter Height" );
height = myInput.nextDouble();
area = 2*pi*(radius+height);
System.out.println(" Area of Cylinder is " + area);
}
// End of method and begining of main
method public static void
main(String[] args) { // Written by Dr
Araoye O. I. // Calling of void method
areaCylinder();
}
}

Program Output Example 8.1

8.3 Parameter passing to void Method

When parameters are passed to method, they are called arguments. The arguments passed

in the body of the method are called former parameters while the argument passed in the

body of main method are called actual parameters Program Example 8.2

55
1.

import java.util.Scanner; public class ProgramExample8_2 { static void areaCylinder (


double height, double radius ) { // height and radius are passed as
//parameters final double pi
=3.142; double area =
2*pi*(radius+height);
System.out.println(" Area of Cylinder is " + area);
}
// End of method and begining of main
method public static void
main(String[] args) { // Written by
Dr Araoye O. I.
Scanner myInput = new Scanner (System.in);
System.out.println("Enter Radius" ); double
radius1 = myInput.nextDouble();
System.out.println("Enter Height" ); double
height1 = myInput.nextDouble(); areaCylinder(
radius1,height1); // actual parameters passed
}
}

Program Output Example 8.2

You may pass direct value as argument as seen in Program Example 8.3

Program Example 8.3

56
1.

public class ProgramExample8_3 { static void areaCylinder ( double


height, double radius ) { // declaration of method final double pi =3.142;
double area = 2*pi*(radius+height);
System.out.println(" Area of Cylinder is " + area);
}
// End of method and begining of main
method public static void
main(String[] args) { // Written by Dr
Araoye O. I. // Calling of void method
areaCylinder( 10,5);
}
}

Program Output Example 8.3

8.4 Static Return Method

This is a method that returns the value of its expression to a variable of its type. The
syntax structure of return method is:
<static><return_datatype><method_name>(
Parameters) { Body of the code; return expression; }

Example:
static int areacylinder (double radius, double
height) { double area =
2*pi*radius*(radius+height); return (area);
}

57
1.

Let us look at the implementation of this example with passing parameters and without
passing parameters in Program examples 8.4 and 8.5 respectively

Program Example 8.4 public class ProgramExample8_4 { static double


areaCylinder ( double height, double radius ) { // declaration of method
final double pi =3.142; double area = 2*pi*(radius+height); return (area);
}
// End of method and beginning of main
method public static void
main(String[] args) { // Written by Dr
Araoye O. I.
// Calling of return method with actual arguments 7 and
5 double areal = areaCylinder( 7,5);
System.out.println(" Area of Cylinder is " + areal);
}
}

Program Output Example 8.4

Program Example 8.5


import java.util.Scanner;
public class
ProgramExample8_5 {
static double areaCylinder ( ) { // declaration of method
Scanner myInput = new Scanner
(System.in);
System.out.println("Enter Radius" );
double radius =
58
1.

myInput.nextDouble();
System.out.println("Enter Height" );
double height =
myInput.nextDouble(); final double
pi =3.142; double area =
2*pi*(radius+height); return (area);
}
// End of method and begining of main
method public static void
main(String[] args) { // @author Dr
Araoye O. I.
// e-mail: [email protected]
double areal = areaCylinder( ); // Calling of return method without passing parameters
System.out.println(" Area of Cylinder is " + areal);
}
}

Program Output Example 8.5

Program Example 8.6

This is a program that swap two integer numbers. IF A = 4 and B =7, at the end of
execution, A will be 7 and B will be 4.
public class ProgramExample8_6 { static void
swap ( int a, int b ) { // declaration of method

59
1.

int temp = a ; a = b; // b replaces a b = temp ;


// a replaces b
System.out.println("The value of a after swapping is "+a );
System.out.println("The value of b after swapping is "+b );
}
// End of method and begining of main
method public static void
main(String[] args) { // @author Dr
Araoye O. I.
// e-mail:
[email protected]
int a= 4; int b = 7;
System.out.println("The value of a before swapping is "+a );
System.out.println("The value of b before swapping is "+b );
swap(a,b); // swapping process
}
}

Program Output Example 8.6

Class Exercise 8.1

1. Write a program to calculate the product of the series: 1.2.4.6.8.10…n


2. Write a program to calculate the following without using keyboard input
i. 8C5 ii 10!

60
1.

3. Write a program to return the minimum of three integer numbers through


keyboard input.
4. Write a program to find permutation P given that

P= , n= 8 and r =2

61

You might also like