1. Intro…
3-1
Java was conceived to develop advanced software
for a wide variety of network devices and systems.
The language drew from a variety of languages such
as C++, Eiffel, SmallTalk, Objective C. The result is a
language platform that has proven suitable for
developing secure, distributed, network-based end-
user applications in environments ranging from
network embedded devices to the World-Wide Web
and the desktop. Java attempts to provide a platform
for the development of secure, high performance,
robust applications on multiple platforms in
heterogeneous, distributed networks. Java does that
by being architecture neutral, portable, and
dynamically adaptable.
2. What is Java?
3-2
Java is an Object Oriented programming language.
This means that Java is a language which can model
every day real objects. The code that is written to
model an every day object is called a class.
Just as real day objects are composed of other
objects so can classes be composed of other classes.
If we consider a dog, then its state is - name, breed,
color, and the behavior is - barking, wagging,
running
3. What is Object Oriented Programming
(OOP)?
3-3
OOP is software design method that models
the characteristics of real or abstract objects
using software classes and object
Classes and Objects
A class is a template/blue print that describes
the behaviors/states that object of its type
support.It is a piece of the program’s source
code that describes a particular type of
objects. OO programmers write class
definitions.
4. Objects
3-4
An object is an instance of a class. A program can
create and use more than one object (instance) of
the same class.
Objects have states and behaviors. Example: A dog has
states - color, name, breed as well as behaviors -
wagging, barking, eating.
Can model real-world objects
Can represent GUI (Graphical User Interface)
components
Can represent software entities (events, files, images,
etc.)
Can represent abstract concepts (for example, rules
of a game, a particular type of dance, etc.)
5. Java is an Object-Oriented Language.
As a language that has the Object Oriented
feature, Java supports the following
fundamental concepts:
Polymorphism
Inheritance
Encapsulation
Abstraction
Classes
Objects
Instance
Method
Message Parsing
5
6. OOP
3-6
An OO program models the application
as a world of interacting objects.
An object can create other objects.
An object can call another object’s (and
its own) methods (that is, “send
messages”).
An object has data fields, which hold
values that can change while the
program is running.
7. Class vs. Object
3-7
A piece of the
program’s source
code
Written by a
programmer
An entity in a
running program
Created when the
program is running
(by the main
method or a
constructor or
another method)
8. Class vs. Object
3-8
Specifies the
structure (the
number and types)
of its objects’
attributes — the
same for all of its
objects
Specifies the
possible behaviors
of its objects
Holds specific values
of attributes; these
values can change
while the program is
running
Behaves
appropriately when
called upon
9. The three OOP Principles
3-9
Inheritance is the process by which one class
acquires the properties of another class. The parent
class called Superclass and the inherited class is
called Subclass. The subclass inherit method,
objects, constructors and variables of a super class.
Encapsulation is the process of hiding the field
and methods of a class by making it private. the
mechanism binds together code and the data it
manipulates, and keeps both safe from outside
interference and misuse..
Polymorphism is mechanism a program is able to
take more than one form, it is a mechanism of
assigning different behavior or value in subclass to
some thing that was in super class(parent class).
10. The Characteristics Of Java:
3-10
Simple: The fundamentals are learned quickly;
programmers can be productive from the very
beginning.
Familiar: Java looks like a familiar language C++,
but removes some of the complexities of C++
Object oriented: so it can take advantage of
modern software development methodologies.
Programmers can access existing libraries of tested
objects, which can be extended to provide new
behavior.
Portable: Java is designed to support applications
capable of executing on a variety of hardware
architectures and operating systems.
11. 3-11
The architecture-neutral and portable language
platform of Java is known as the Java Virtual
Machine
Multithreaded: for applications with many
concurrent threads of activity.
Interpreted: for maximum portability and
dynamic capabilities.
Robust and Secure: Java provides extensive
compile-time and run-time checking. There are no
explicit pointers, and the automatic garbage
collection eliminates many programming errors.
Sophisticated security features have been
designed into the language and run-time system.
12. Development Process with Java
Java source files are written as plain text
documents. The programmer typically writes Java
source code in an Integrated Development
Environment (IDE) for programming. An IDE
supports the programmer in the task of writing
code, e.g. it provides auto-formating of the source
code, highlighting of the important keywords, etc.
At some point the programmer (or the IDE) calls
the Java compiler (javac). The Java compiler
creates the bytecode instructions. These
instructions are stored in .class files and can be
executed by the Java Virtual Machine.
12
13. Creating a Java Program
3-13
The standard way of producing and
executing a program is:
Edit the program with a text
editor; save the text with an
appropriate name.
Compile: the program to produce the
object code
Link: the object code with some
standard functions to produce an
executable file
Execute (run): the program
14. A Java program is both compiled
and interpreted
3-14
with the compiler, a Java program is
translated into an intermediate
platform-independent language called
Java bytecodes
with an interpreter, each Java bytecode
instruction is interpreted and run on the
computer. Compilation happens just
once; interpretation occurs each time
the program is executed
16. Types of Java Programs
3-16
There are two classes of Java programs
Java stand-alone applications: they
are like any other application written in
a high level language
Java applets: they are special purpose
applications specifically designed to be
remotely downloaded and run in a
client machine
17. public class SomeClass
3-17
Fields
Constructors
Methods
}
Attributes / variables that define the object’s
state; can hold numbers, characters, strings,
other objects
Procedures for constructing a new
object of this class and initializing its
fields
Actions that an object of this
class can take (behaviors)
{
Class header
SomeClass.java
import ... import statements
18. Components of a Java program
3-18
Comments
// Object oriented programming
// Written 10/09/2013
// OUR java program!
public class ClassName{
public static void main() {
System.out.println(“ MY OUTPUT");
}
}
19. 3-19
The program starts with a comment:
//Object oriented programming
// Written 10/09/2013
// OUR java program!
all the characters after the symbols // up to
the end of the line are ignored; they do not
change the way the program runs, but they
can be very useful in making the program
easier to understand; they should be used to
clarify some part of a program, to explain
what a program does and how it does it.
There could also be comments beginning with
a /* and continue, possibly across many
lines, until a */ is found, like so:
20. Import statements
In Java you have to access a class always
via its full-qualified name, e.g. the package
name and the class name.
in Java if a fully qualified name, which
includes the package and the class name, is
given then the compiler can easily locate the
source code or classes. Import statement is
a way of giving the proper location for the
compiler to find that particular class.
Example import java.util.Scanner;
20
21. 3-21
A class definition: Java programs include at
least a class definition such as public class
A class can be define as the blueprint or
prototype that defines the field and methods
common to all objects of certain kind
ClassName. The class extends from the first
opening curly brace { to the last closing curly
brace }
The main() method: a method is a
collection of programming statements that
have been given a name and that execute
when called to run. Methods are also
delimited by curly braces.
22. The main() method
3-22
All Java applications (not applets) must have a
class (only one) with a main() method where
execution begins;
Each application needs at last one main method to
execute:When you run the "java" executable, you
specify the class you wish to run. The Java Virtual
Machine then looks for a main method in the class
if it does not find one it will complain.
programming statements within main() are
executed one by one, until its termination;
the main() method is preceded by the words
public static void called modifiers;
23. 3-23
The main() method always has a list of
command line arguments that are
passed to the program main(String[]
args) (which we are going to ignore for
now)
24. Statements
3-24
Statements are instructions to the computer
to determines what to do end with a
semicolon ';' (a terminator, not a separator)
In this example there is only one statement
System.out.println(" MY OUTPUT "); to
print a message and move the cursor to the
next line, by using the method
System.out.println() to print a constant
string of characters and a newline. Within a
method the statements are executed in
sequential order: sequential execution.
25. Reserved words
3-25
class, static, public, void have all been
reserved by the designers and they can't be
used with any other meaning. (For a complete
list see the prescribed book.)
Case sensitive
Java compilers are case sensitive, meaning that
they see lower case and upper case differently.
Upper / lower case should be used so
programmers can better read the code. Any
literal used for identification of an entity is
called an identifier. In Java, the identifiers
aString AString ASTRING are all different:
26. 3-26
Running a Java Program
% javac ClassName.java // compilation
% java ClassName // running by interpreter
MY OUTPUT // output
the compiler javac produces a file called
ClassName.class;
this file is to be interpreted by the interpreter java;
you use the .java extension when compiling a file, but
you do not use the .class extension when calling the
interpreter to run the program;
IMPORTANT: if a class, such as ClassName above, is
declared public, it must be compiled in a file called
ClassName.java. Otherwise the compiler will give an
error.
27. Programming Style
3-27
Adhering to a style makes programs easier to read
for humans. There are rules that most Java
programmers follow, such as:
One statement per line
Indentation: 3 spaces. Indicates dependency
between statements.
Comments should be added to clarify code sections
that are not obvious
Blank lines: should be used to separate different
logic sections of the code
Naming (identifiers): we did in c and c++(recal)
28. Programming Errors
3-28
Programming errors can be divided into:
Compilation time errors: are detected by the
compiler at compilation time. The executable is not
created. i.e instructing the computer to do what
cannot be done by the machine.
Syntax errors: appear when the program runs i.e
when a rule of programming is violated. Typically
execution stops when an exception such as this
happens, it is possible to handle these errors
Logical errors: the program compiles and runs
with no problems but gives out wrong results due
to wrong formulae.
29. Variables
A variable is a programming concept of a
location in the memory for storing a value that
may change from time to time. However, the
values that can be stored in a variable must be
of the same data type. A program must store
the values it is using for computation in
variables or other advanced storage locations.
29
30. Declaration of variables
Declaring a variable instructs the computer to allocate a
memory space for storing a value of that type.Example
The following statement instructs the computer to declare a
variable named x, for storing an integer (whole number)
int x;
Initialization of variables
You can give a variable some initial value during declaration
(also known as initializing a variable). For example to
initialize floats a, b, and c to zero during declaration, we
write
double a=0, b=0, c=0;
To initialize only b, we write
float a, b=0, c; 30
31. Variable rules /naming conventions
a) A variable must be declared before being
used.
b) A variable can not be declared more than
once
c) A variable can be declared anywhere in the
program I.e. it’s not a must to declare it at
the beginning of a Class. We can declare it
at the middle of other statements or
Methods.
d) A library key word must not be used when
declaring a variable e.g. public, private etc.
31
32. Java Basic Data Types
Variables are nothing but reserved memory locations
to store values. This means that when you create a
variable you reserve some space in memory.
Based on the data type of a variable, the operating
system allocates memory and decides what can be
stored in the reserved memory. Therefore, by
assigning different data types to variables, you can
store integers, decimals, or characters in these
variables.
There are two data types available in Java:
Primitive Data Types
Reference/Object Data Types 32
33. Primitive Data Types:
There are eight primitive data types supported by Java.
Primitive data types are predefined by the language and
named by a keyword. Let us now look into detail about the
eight primitive data types.
byte:
Byte data type is an 8-bit signed two's complement integer.
Minimum value is -128 (-2^7)
Maximum value is 127 (inclusive)(2^7 -1)
Default value is 0
Byte data type is used to save space in large arrays, mainly
in place of integers, since a byte is four times smaller than
an int.
Example: byte a = 100 , byte b = -50
33
34. short:
Short data type is a 16-bit signed two's complement integer.
Minimum value is -32,768 (-2^15)
Maximum value is 32,767 (inclusive) (2^15 -1)
Short data type can also be used to save memory as byte
data type. A short is 2 times smaller than an int
Default value is 0.
Example: short s = 10000, short r = -20000
int:
Int data type is a 32-bit signed two's complement integer.
Minimum value is - 2,147,483,648.(-2^31)
Maximum value is 2,147,483,647(inclusive).(2^31 -1)
Int is generally used as the default data type for integral
values unless there is a concern about memory.
The default value is 0.
Example: int a = 100000, int b = -200000 34
35. Long:
Long data type is a 64-bit signed two's complement integer.
Minimum value is -9,223,372,036,854,775,808.(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive).
(2^63 -1)
This type is used when a wider range than int is needed.
Default value is 0L.
Example: long a = 100000L, int b = -200000L
Float:
Float data type is a single-precision 32-bit IEEE 754 floating
point.
Float is mainly used to save memory in large arrays of floating
point numbers.
Default value is 0.0f.
Float data type is never used for precise values such as
currency.
Example: float f1 = 234.5f
35
36. Double:
double data type is a double-precision 64-bit IEEE 754
floating point.
This data type is generally used as the default data type for
decimal values, generally the default choice.
Double data type should never be used for precise values
such as currency.
Default value is 0.0d.
Example: double d1 = 123.4
Boolean:
boolean data type represents one bit of information.
There are only two possible values: true and false.
This data type is used for simple flags that track true/false
conditions.
Default value is false.
Example: boolean one = true
36
37. Char:
char data type is a single 16-bit Unicode character.
Minimum value is 'u0000' (or 0).
Char data type is used to store any character.
Example: char letterA ='A'
Reference Data Types:
Reference variables are created using defined constructors of
the classes. They are used to access objects. These variables
are declared to be of a specific type that cannot be changed.
For example, Employee, Puppy etc.
Class objects, and various type of array variables come under
reference data type.
Default value of any reference variable is null.
A reference variable can be used to refer to any object of the
declared type or any compatible type.
Example: Animal animal = new Animal("giraffe"); 37
38. Types of variables
There are three kinds of variables in
Java:
1. Local variables
2. Instance variables
3. Class/static variables
38
39. Local variables:
Local variables are declared in methods, constructors,
or blocks.
Local variables are created when the method,
constructor or block is entered and the variable will be
destroyed once it exits the method, constructor or
block.
Access modifiers cannot be used for local variables.
Local variables are visible only within the declared
method, constructor or block.
Local variables are implemented at stack level
internally.
There is no default value for local variables so local
variables should be declared and an initial value should
39
41. Instance variables:
Instance variables are declared in a class, but outside a
method, constructor or any block.
When a space is allocated for an object in the heap, a slot
for each instance variable value is created.
Instance variables are created when an object is created
with the use of the keyword 'new' and destroyed when the
object is destroyed.
Instance variables hold values that must be referenced by
more than one method, constructor or block, or essential
parts of an object's state that must be present throughout
the class.
Instance variables can be declared in class level before or
after use.
Access modifiers can be given for instance variables.
41
43. Class/static variables:
Class variables also known as static variables are declared
with the static keyword in a class, but outside a method,
constructor or a block.
There would only be one copy of each class variable per class,
regardless of how many objects are created from it.
Static variables are rarely used other than being declared as
constants. Constants are variables that are declared as
public/private, final and static. Constant variables never
change from their initial value.
Static variables are stored in static memory. It is rare to use
static variables other than declared final and used as either
public or private constants.
Static variables are created when the program starts and
destroyed when the program stops.
43
45. Constants/Literals
A constant just like a variable, is used to
store values in memory. A constant’s value
however, may not change. Constants are
used to store values that do not change in
any run of the program including the pi of a
circle, the tax of a payroll processing
program, the pass mark in an examination
processing program, etc.
45
46. Java - Methods
A Java method is a collection of statements that
are grouped together to perform an operation.
When you call the System.out.println method, for
example, the system actually executes several
statements in order to display a message on the
console.
Now you will learn how to create your own
methods with or without return values, invoke a
method with or without parameters, overload
methods using the same names, and apply method
abstraction in the program design.
46
48. Modifiers: The modifier, which is optional, tells the compiler
how to call the method. This defines the access type of the
method.
Return Type: A method may return a value. The
returnValueType is the data type of the value the method
returns. Some methods perform the desired operations without
returning a value. In this case, the returnValueType is the
keyword void.
Method Name: This is the actual name of the method. The
method name and the parameter list together constitute the
method signature.
Parameters: A parameter is like a placeholder. When a method
is invoked, you pass a value to the parameter. This value is
referred to as actual parameter or argument. The parameter list
refers to the type, order, and number of the parameters of a
method. Parameters are optional; that is, a method may contain
no parameters.
Method Body: The method body contains a collection of
48
49. Calling a Method:
In creating a method, you give a definition
of what the method is to do. To use a
method, you have to call or invoke it. There
are two ways to call a method; the choice is
based on whether the method returns a
value or not.
When a program calls a method, program
control is transferred to the called method. A
called method returns control to the caller
when its return statement is executed or
when its method-ending closing brace is
reached. 49
52. Mathematics in Java
To assist you with various types of calculations,
the java.lang package contains a class named
Math. In this class are the most commonly
needed operations in mathematics.
The java.lang.Math class contains methods
for performing basic numeric operations such
as the elementary exponential, logarithm,
square root, and trigonometric functions.
The Minimum and Minimum of Two Values
52
56. Question
Write a Java program that computes
compound interest (compounded yearly)
using following formula A=P(1+r)n. P is
original amount invested, r is annual
interest, n is number of years, A is amount
at end of nth year. The user enters P, r and
n and results for various years are
displayed on the screen.
56
57. Classes and Source Files
3-57
Each class is stored in a separate file
The name of the file must be the same
as the name of the class, with the
extension .java
public class Car
{
...
}
Car.java By convention, the name
of a class (and its source
file) always starts with a
capital letter.
(In Java, all names are case-sensitive.)
58. Libraries
3-58
Java programs are usually not written from
scratch.
There are hundreds of library classes for all
occasions.
Library classes are organized into packages.
For example:
java.util — miscellaneous utility classes
java.awt — windowing and graphics toolkit
javax.swing — GUI development package
59. import
3-59
Full library class names include the
package name. For example:
java.awt.Color
javax.swing.JButton
import statements at the top of the
source file let you refer to library
classes by their short names:
import javax.swing.JButton;
JButton go = new JButton("Go");
Fully-qualified
name
60. import (cont’d)
3-60
You can import names for all the
classes in a package by using a wildcard
.*:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
java.lang is imported automatically into
all classes; defines System, Math,
Object, String, and other commonly
Imports all classes
from awt, awt.event,
and swing packages
61. Java Basic Operators
3-61
An operator is used in a program to manipulate
data types values. It combines two operands in
an expression.
i.e. z = x + y
Unary and Binary operators.
Unary operator takes only one operand while
Binary operator takes two operands. e.g. +, - are
Binary while ++, -- are Unary operators.
Evaluation of an expression.
An expression is evaluated from the left to the right
hand side.
63. 1.Arithmatic Operators.
An Arithmatic operator operates on two
operands in an expression to produce a
value (number). The possible Arithmatic
operators are:-
Operator Meaning
+ Addition
- Substraction
* Multiplication
/ Division
% Modulus 63
64. 2.Relational Operators/ Conditional
Operators.
Relational operators are used in Boolean expression to
compare the values of the two operands which produce a
value of either True or False. A Boolean expression is an
expression whose value can either be True or False.
Operator Meaning
> Greater than
> = Greater than or equal to
< Less than
< = Less than or equal to
= = Equal to
! = Not equal to 64
65. 3.Logical Operators
Logical opeartors are used to combine
two Boolean expressions into a compound Boolean
expression. The truth table rules are used to test the
Truth or False of a compound expression depending
on the truth and false of each expression in the
compound expression.
Operator Meaning
&& And
// Or
! Not(Negation)
65
67. 4.Assignment Operator (=)
The assignment operator is used to assign the variable on
the left hand side the value of expression which is on the
right hand side.
Examples
a = b means “Take the value of b and store it in a
variable a”
x = x + 1 means “Take the value of x, i.e. increment the
value of x by one or just increment x”
67
68. 5.Short-cut Operators
Java has shortcuts for writting some expressions. The shortcut operators
include the following + +,- -,+ =, * =, / =. These operators will be
explained by using examples below.
Examples;
a=b; Means ”Take the value of b and Store it in a Variable a”
x=x+1; Means”Take the Value of x, add one to it, and store results back
to a variable x;
x=x-1; Means”Take the Value of x, subtract one to it, and store
results back to a variable x;
Expression Equivalent to
x+ + x = x + 1
x- - x = x - 1
x + = y x = x + y
x - = y x = x - y
x * = y x = x * y
68
69. 6.Ternary Operators/Conditional Operator ( ? : ):
This is used in decision making. It takes the
following:-
Expression 1 ? Expression 2: Expression 3
variable x = (expression) ? value if true : value
if false
Expression 1 is evaluated if it is True, then
Expression 2 is evaluated and becomes the
value of the whole expression. Otherwise
Expression 3 is evaluated and becomes the
value of the expression.
Example.. 69
71. Precedence of Java Operators:
Operator precedence determines the grouping of terms
in an expression. This affects how an expression is
evaluated. Certain operators have higher precedence
than others; for example, the multiplication operator
has higher precedence than the addition operator:
For example, x = 7 + 3 * 2; here x is assigned 13, not
20 because operator * has higher precedence than +,
so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at
the top of the table, those with the lowest appear at
the bottom. Within an expression, higher precedence
operators will be evaluated first.
71
73. CONTROL STRUCTURES
Control structures are structures used to control the
execution of programs statements. They include decision
making and repetition.
Sequential execution alone is not enough to solve typical
read word problems because of the following reasons.
-Need for decision making
-Need for repetition
(a)What is decision making?
Decision making is selection of the various alternatives in
other words; we select which alternative path to follow
depending on the outcome of some conditions.
(b)If we have two alternatives.
Here, we test he Boolean condition and choose one path to
follow. If the condition is true, or the other path if the
condition is False. 73
74. (c)If we have more than two alternatives.
Here, we do multiple testing of conditions, each time
choosing a path to follow. If there are many
alternatives in a problem, we have sequence of
conditions to be tested, but each result to either
True or False value.
Structures used in Java programming.
Three decision making structures used in Java
programming are:-
The if……. else structure
The nested if..else structures
The Switch structure
Ternary structure/Condition
74
75. (a)The if…. else structure.
The If ….else structure basically means “if a
condition is True, then do something (True
statement), else do something else (False statement)
Syntax
If(condition)
{
Path1 (True statement)
}
Else
{
Path2 (False statement)
}
75
76. Steps in execution
Test condition
If it is true, then execute path1 (True
statement)if it is False, then execute
path2(False statement)
Go to what follows the if……else structure
N. B The condition must be Boolean
76
77. TEST TABLE.
The test table is the programmer’s tool for testing the
algorithm as well as the code/program for logical
correctness.
Example 2
Design and write a program that reads in the age of
a person and outputs an appropriate message based
on;
If age<18 print “Below 18 years” and If
age>=18 print “Issue an ID”
77
78. Example 3
Assume that every employee gets 20% house
allowance. Assume also that those earning at least
10,000 pay some tax at the rate of 10%. Design
and Write algorithm and code to input the net salary
N.B Net Salary = salary+house allowance-tax
78
79. EXAMPLE 1
Design and Write the program that
allow the user to enter the marks for
Maths, English and Kiswahili it then
compute the mean to output “PASS”
if the mean of three Subjects is
more or equal to 50 and
output”FAIL”if the mean is less than
50.
79
80. (b) Nested if…..else structures.
Nesting of if…..else statement is applied when you have more than
one condition to test and the condition depends on the outcome of the
previous one
Syntax
if(condition1)
{
True statement1;
}
else if (condition2);
{
True statement2;
}
.
.
else
{
True statementn;
}
80
81. Examples 1
Design and Write the program that allow the user to
enter the marks for Maths, English and Kiswahili it
then compute the mean and the grade obtained in an
exam depends on the mean mark of three subjects as
shown below.
Mean mark Grade
At least 70 up to 100……......………..............A
At least 60 up to less than 70…………………...B
At least 50 but less than 60…………….………..C
Below 50……………………………………….………..F
81
82. Design and write a java program that
allow the user to enter the mass(in kg)
and Height( in metres), the program
then compute the body mass index
(BMI) of patient in hospital and output
appropriate interpretation using the
following table.
N.B the formular is.
82
84. (c) The switch structure
A switch statement allows a variable to be
tested for equality against a list of constant
values. Each value is called a case, and the
variable being switched on is checked for
each case.
The constant value that must be integer or
character constant value.
84
87. The value of a variable y depends on the
value of variable x as shown below;
X y
1 0.1
2 0.2
Other value 0
Write down a switch structure for the
problem
87
Example 1
88. Example 2
Write a Java program using the switch
statement that will ask the user to enter a
value between 1 and 7 and will print out the
day of the week based on the number
chosen i.e. as in 1 for Monday to 7 for
Sunday
88
89. (d) Ternary Operators/Conditional Operator
This is used in decision making. It takes the
following:-
Expression 1 ? Expression 2: Expression 3
variable x = (expression) ? value if true : value
if false
Expression 1 is evaluated if it is True, then
Expression 2 is evaluated and becomes the
value of the whole expression. Otherwise
Expression 3 is evaluated and becomes the
value of the expression.
Example.. 89
91. Repetition
Repetition is simply repeated execution of some
task i.e. sequence of statements. Thus, we execute
the task and then go back to the beginning and
start another execution and so on.
There may be a situation when we need to execute
a block of code several number of times, and is
often referred to as a loop.
Java has very flexible three looping mechanisms.
You can use one of the following three loops:
while Loop
do...while Loop
for Loop
91
92. Loops
Four things that are a must when using
any loop.
1. Initialization of Counter(Initialization).
2. Testing the condition(condition).
3. Changing the value of the
counter(Counter_change).
4. The loop’s body(statements).
92
93. (a) The while Loop:
Syntax
while(Condition)
{
//Statement(s);
}
Steps
a) Evaluate Condition.
b) If it is true,
Execute Statement(s)
Repeat from(a)
Else(if it is false),
Exit and go to what follow the loop.
93
94. When executing, if the Condition
(boolean_expression) result is true, then
the actions inside the loop will be executed.
This will continue as long as the expression
result is true.
Here, key point of the while loop is that the
loop might not ever run. When the
expression is tested and the result is false,
the loop body will be skipped and the first
statement after the while loop will be
executed.
94
98. Notice that the Condition (Boolean
expression) appears at the end of the
loop, so the statements in the loop
execute once before the Boolean is
tested.
If the Boolean expression is true, the
flow of control jumps back up to do,
and the statements in the loop execute
again. This process repeats until the
Boolean expression is false.
98
101. (c) The for Loop
Syntax
for(initialization; Condition; Counter_change) {
//Statement(s);
}
Steps
a) Initialize the Counter(Initialization)
b) Test Condition.
c) If it is true, Continue from(d)
Else(if it is false, go to what follows the last step i.e exit the
loop)
d) Execute Statement(s)
e) Do Change the counter value(counter_change),then
f) Repeat from(b) above. 101
102. Here is the flow of control in a for loop:
The initialization step is executed first, and only once. This
step allows you to declare and initialize any loop control
variables. You are not required to put a statement here, as
long as a semicolon appears.
Next, the Boolean expression is evaluated. If it is true, the
body of the loop is executed. If it is false, the body of the
loop does not execute and flow of control jumps to the next
statement past the for loop.
After the body of the for loop executes, the flow of control
jumps back up to the update statement. This statement
allows you to update any loop control variables. This
statement can be left blank, as long as a semicolon appears
after the Boolean expression.
The Boolean expression is now evaluated again. If it is true,
the loop executes and the process repeats itself (body of
loop, then update step, then Boolean expression). After the
Boolean expression is false, the for loop terminates.
102
104. Void and Non void Methods
Non Void method is a method that returns a
value to when called or invoked.
Example:
Here is the source code of the above defined
method called max(). This method takes two
parameters num1 and num2 and returns the
maximum between the two:
104
106. Void method is a method that does not
returns a value to when called or invoked.
public class nonvoid{
public void mymethod(){
system.out.println(“my output”);
}
public static void main(string[]args){
nonvoid myobject=new nonvoid();
myobject. mymethod();
}
}
106
107. Constructors in Java
9-107
A constructor is a procedure for creating objects
of the class and initializing its fields/variables.
Rules for a constructor
Constructors do not have a return type (not
even void) and they do not return a value.
All constructors in a class have the same
name — the name of the class.
Constructors may take parameters.
If a class has more than one constructor, they
must have different numbers and/or types of
parameters.
108. Constructors (cont’d)
9-108
Programmers often provide a “no-args”
constructor that takes no parameters
(a.k.a. arguments).
If a programmer does not define any
constructors, Java provides one default
no-args constructor, which allocates
memory and sets fields to the default
values.
The syntax for a constructor is:
access NameOfClass (parameters) {
initialization code }
110. Inheritance
110
Inheritance can be defined as the process where one
object acquires the properties of another. With the
use of inheritance the information is made
manageable in a hierarchical order.
Inheritance is a mechanism to reuse code.
Java uses extends keyword for inheritance.
Example: class CR extends Trainee { }
A class can inherit only one class at a time.
Multiple inheritance is not supported in Java.
By inheriting, we get three benefits:
Use already available functions
Add more functions
If necessary, modify the available function (method
overriding)
111. Inheritance
3-111
In OOP a programmer can create a new
class by extending an existing class
Superclass
(Base class)
Subclass
(Derived class)
subclass extends
superclass
112. A Subclass...
3-112
inherits fields and methods of its
superclass
can add new fields and methods
can redefine (override) a method of
the superclass
must provide its own constructors,
but calls superclass’s constructors
does not have direct access to its
superclass’s private fields
113. 3-113
public class Superclass{
public void printMethod(){
System.out.println(“IM IN SUPERCLASS”);
}}
Public class SubClass extends Superclass{
//override printmethod in superclass
public void printMethod(){
super. printMethod();
System.out.println(“IM IN SUBCLASS”);
Public static void main(String [ ] args){
Subclass Object= new Subclass();
Object. printMethod();
}}
114. Encapsulation
9-114
Encapsulation is the process of Hiding
the implementation details of a class by
making all fields and helper methods
private.
Encapsulation helps in program
maintenance: a change in one class does
not affect other classes.
A client of a class interacts with the class
only through well-documented public
constructors and methods; this facilitates
team development.
115. Access Control Modifiers:
Modifiers are keywords that you add to those
definitions to change their meanings.
java provides a number of access modifiers to
set access levels for classes, variables,
methods and constructors. The four access
levels are:
No modifiers are needed-Visible to the
package, the default.
Private-Visible to the class only
Public -Visible to the world.
Protected-Visible to the package and all
subclasses .
115
116. 3-116
Constructors and methods can call
other public and private methods of the
same class.
Constructors and methods can call only
public methods of another class.
Class X
private field
private method
Class Y
public method public method
117. Class’s Client
9-117
Any class that uses class X is
called a client of X
Class X
private fields
private methods
public
methods
public
constructor(s)
Class Y A client
of X
Constructs
objects of X
and/or calls
X’s methods
118. Public vs. Private
9-118
Public constructors and methods of a
class constitute its interface with classes
that use it — its clients.
All fields are usually declared private —
they are hidden from clients.
Static constants occasionally can be
public.
“Helper” methods that are needed only
inside the class are declared private.
119. Public vs. Private (cont’d)
9-119
A private field is accessible anywhere
within the class’s source code.
Any object can access and modify a
private field of another object of the
same class.
public class Fraction
{
private int num, denom;
...
public multiply (Fraction other)
{
int newNum = num * other.num;
...
120. Polymorphism
120
Polymorphism means, taking more than one form, it is a
characteristics of being able to assign a different behaviour
or value in sub class to something that was in parent class
(superclass).
Types of polymorphism
1.Method overriding a situation where the name of the
method remain common in the same class or a
subclass have same parameter list and method
Signatures.
2.Method oveloading a situation where the name of
the method remain common in the same class or a
subclass but have different parameter list or different
method Signatures.
121. 3-121
public class Superclass{
public void printMethod(){
System.out.println(“IM IN SUPERCLASS”);
}}
Public class SubClass extends Superclass{
//override printmethod in superclass
public void printMethod(){
super. printMethod();
System.out.println(“IM IN SUBCLASS”);
Public static void main(String [ ] args){
Subclass Object= new Subclass();
Object. printMethod();
}}
122. Constructor Overloading
3-122
Is a technique in Java where a class can
have more that one constructor with
the same name but different parameter
list
123. 3-123
public class Classname{
//declaration of fields or variable
int value1;
int value2;
//constructor
Public Classname(){
int value1=5;
int value2=6;
System.out.println(“inside a constructor 1st”);
}
public Classname ( int a, int b){
int value1=a;
int value2=b;
System.out.println(“inside a constructor 2nd”);
}
124. 3-124
public Classname( int a,){
int value1=a;
System.out.println(“inside a constructor 3rd”);
}
Public void mymethod(){
System.out.println(“Value one is”+value1);
System.out.println(“Value one is”+value2);
}
Public static void main(String [ ] args){
Classname method1 = new Classname ();
Classname method2 = new Classname(30);
Classname method3 = new Classname(30,40);
Method1. mymethod();
Method2. mymethod();
Method3. mymethod();
}}
125. Characteristics of Objects
125
Identity
makes an object different from other objects created
from the same class.
State
defined by the contents of an object’s attributes.
Objects state vary during the execution of program.
Behavior
Defined by the messages (functions/methods) an
object provides.
127. Object Creation
127
Objects are created by instantiating a class.
ClassName object = new ClassName();
Object creation involves three actions:
Declaration
Declaring the type of data
Instantiation
Creating a memory space to store the object
Initialization
Intializing the attributes in the object.
128. Object Usage
128
Using an object we can
get information about it
change its state
ask it to perform some actions
This done by
Manipulating / inspecting its variables
Calling its methods
129. Object Disposal
129
The Java runtime automatically deletes objects when
they are no longer referenced.
This process is called garbage collection.
130. Finalization
130
Before objects are deleted by the runtime system, they
are given a chance to clean up.
This is implemented by the object’s finalize method.
Typical tasks done by object during finalization are:
Free system resources like files and sockets
Drop references to other objects, if any.
131. Java Data Types
131
Two major data types
Primitive
Because java program has to run on different
architecture and OS, the size of the data should
remain same. Otherwise, on different machines
the output will be different
Reference
All objects are of type reference data type. Java
doesn’t allow directly to access memory. But
objects are refered by pointers only.
132. Reference Data Types
132
Examples:
Arrays
Strings
Objects
Interfaces
The name reference means a pointer in the memory.
All objects are referred by their memory location only.
But user cannot directly access memory location.
Memory management is taken care by JVM itself.
133. Java - Arrays
Java provides a data structure, the array,
which stores a fixed-size sequential collection
of elements of the same type. An array is
used to store a collection of data, but it is
often more useful to think of an array as a
collection of variables of the same type.
Instead of declaring individual variables, such
as number0, number1, ..., and number99,
you declare one array variable such as
numbers and use numbers[0], numbers[1],
and ..., numbers[99] to represent individual
variables.
133
134. Declaring Array Variables:
To use an array in a program, you must
declare a variable to reference the array,
and you must specify the type of array the
variable can reference. Here is the syntax
for declaring an array variable:
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not
preferred way.
134
135. The style dataType[] arrayRefVar is preferred.
The style dataType arrayRefVar[] comes from
the C/C++ language and was adopted in Java to
accommodate C/C++ programmers.
Example:
int [] myList;
Creating Arrays:
You can create an array by using the new operator
with the following syntax:
arrayRefVar = new dataType[arraySize];
The above statement does two things:
It creates an array using new dataType[arraySize];
It assigns the reference of the newly created array
to the variable arrayRefVar. 135
136. Declaring an array variable, creating an
array, and assigning the reference of the
array to the variable can be combined in one
statement, as shown below:
dataType[] arrayRefVar = new
dataType[arraySize];
Alternatively you can create arrays as follows:
dataType[] arrayRefVar = {value0, value1, ...,
valuek};
The array elements are accessed through the
index. Array indices are 0-based; that is,
they start from 0 to arrayRefVar.length-1.
136
137. Example:
Following statement declares an array
variable, myList, creates an array of 10
elements of double type and assigns its
reference to myList:
double[] myList = new double[10];
137
138. Following picture represents array myList.
Here, myList holds ten double values and the
indices are from 0 to 9.
138
139. Processing Arrays:
When processing array elements, we often
use either for loop or foreach loop because
all of the elements in an array are of the
same type and the size of the array is
known.
Example:
Here is a complete example of showing how
to create, initialize and process arrays:
139
141. import java.util.Scanner;
import java.util.ArrayList;
public class Arrray {
public static void main(String[] args) {
int[] a= new int[5];
Scanner sc=new Scanner(System.in);
System.out.println("Please enter numbers...");
for(int j=0;j<5;j++)
{
a[j]=sc.nextInt();
}
for (int i = 0; i < a.length; i++) {
System.out.println(a[i] + " ");
}
}
}
141
142. Graphical User Interface(GUI) in Java
Recall That you already used the class scanner
to input data into a program from the Keyboard,
and you used the object.out to output the
results to the screen.
Another way to gather input and output results
is the use of GUI.
JOpationPane Class
The class JOptionPane is contained in the package
javax.swing.The two methods of this class that
we use are; ShowInputDialog and
ShowMessageDialog
142
143. ShowInputDialog-Allows the user to input a string from
the keyboard.
ShowMessageDialog-Allows the programmer to display
the results.
Syntax;
Str =JOptionPane.ShowInputDialog(StringExpression);
Where= Str is a Variable, StringExpression is an expression
evaluating the string.When this statement executes,
adialog box containing stringExpression appears on the s
Example;
143