0% found this document useful (0 votes)
6 views155 pages

Java Programming 3

Java is a high-level, platform-independent programming language developed by Sun Microsystems in 1995, known for its object-oriented features and security. It supports various applications, including enterprise and mobile, and is characterized by its simplicity, robustness, and dynamic capabilities. Additionally, Java utilizes concepts such as inheritance, polymorphism, and encapsulation, making it a versatile choice for developers across different platforms.

Uploaded by

calebbett8076
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views155 pages

Java Programming 3

Java is a high-level, platform-independent programming language developed by Sun Microsystems in 1995, known for its object-oriented features and security. It supports various applications, including enterprise and mobile, and is characterized by its simplicity, robustness, and dynamic capabilities. Additionally, Java utilizes concepts such as inheritance, polymorphism, and encapsulation, making it a versatile choice for developers across different platforms.

Uploaded by

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

JAVA PROGRAMMING

OVERVIEW OF JAVA

oJava is a high-level programming language


originally developed by Sun Microsystems and
released in 1995.
oIt runs on a variety of platforms, such as
Windows, Mac OS, and the various versions of
UNIX. 1
Benefits/Advantages of Java
1.Object Oriented − In Java, everything is an Object. This comes
with many advantages including modularity, inheritance among
others.

2.Platform Independent − Unlike many other programming


languages, when Java is compiled, it is not compiled into
platform specific machine, rather into platform independent byte
code which is distributed over the web and interpreted by the
Virtual
3.
Machine (JVM) on whichever platform it is being run on.

2
3. Simple − Java is designed to be easy to learn. If you
understand the basic concept of OOP, it would be easy to
master.

4. Secure − it enables one 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. 3
6. Portable − Being architecture-neutral and having no
implementation dependent aspects of the specification
makes Java portable. It can be run on different types of
computers

7. Robust − it eliminate error prone situations by


emphasizing mainly on compile time error checking and
runtime checking.

4
Applications of Java Programming
The latest release of the Java Standard Edition is Java SE
8.
With the advancement of Java and its widespread
popularity, multiple configurations were built to suit
various types of platforms. For example: J2EE for
Enterprise Applications, J2ME for Mobile Applications.
The new J2 versions were renamed as Java SE, Java EE,
and Java ME respectively.
5
 Multithreaded − 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.
 Interpreted − Java byte code is translated on the fly to
native machine instructions and is not stored anywhere.
 High Performance − With the use of Just-In-Time
compilers, Java enables high performance.

6
 Distributed − Java is designed for the distributed

environment of the internet.

 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 extensive amount

of run-time information that can be used to verify and

resolve accesses to objects on run-time.


7
INTRODUCTION TO OBJECT
ORIENTED CONCEPTS
1. Class – it is a template for defining objects. It specifies
the names and types of variables that can exist in an
object, as well as "methods” -procedures for operating
on those variables.
2. Object – is a member or an instance of a particular class or
subclass with the class's own methods or procedures and data
variables.

Copyright©2023 by Mbaluka S. All 8


rights reserved.
9
Copyright©2023 by Mbaluka S. All
rights reserved.
A class can be visualized as a three-compartment box, as

illustrated:

oClassname (or identifier): identifies the class.

oDataMembers or Variables (or attributes, states, fields):

contains the static attributes of the class.

oMemberFunctions (or methods, behaviors, operations):

contains the dynamic operations of the class.


10
Copyright©2023 by Mbaluka S. All
rights reserved.
Copyright©2023 by Mr. Mbaluka S. 11
All rights reserved.
12
Copyright©2023 by Mbaluka S. All
rights reserved.
Copyright©2023 by Mbaluka S. All 13
rights reserved.
Characteristics of objects
1. An object has identity (each object is a distinct
individual).

2. An object has state (it has various properties, which


might change).

3. An object has behaviour (it can do things and can


have things done to it).

14
Copyright©2023 by Mbaluka S. All
rights reserved.
Phases of Object oriented
methodology
1. Object oriented analysis – problem
formulation, identification of user requirements
& building a model

2. Object oriented design - system and object


design

3. Object oriented implementation and testing –


codes developed and tested 15
Principles/ characteristics of
Object oriented systems
 Abstraction – concept of showing only the essential
attributes hiding unnecessary information
 Encapsulation – combining data and methods in a unit/
object
 Modularity – decomposing a system into a set of
cohesive and loosely coupled modules
 Hierarchy (is-a & part-of) – reusability or inheritance
of properties from one class to another. 16
Inheritance - process of creating a new class that derives
properties from an existing class but also extends or adds
its own properties. Such a class is called a derived class.
Its said to "inherit" its properties and functionality from the
original class.

17
Copyright©2023 by Mbaluka S. All
rights reserved.
Copyright©2023 by Mr. Mbaluka S. 18
All rights reserved.
Copyright©2023 by Mr. Mbaluka S. 19
All rights reserved.
 Polymorphism - Polymorphism means "multiple

forms". In OOP these refer to multiple forms of the same

method, where the exact same method name can be used

in different classes, or the same method name can be

used in the same class with slightly different parameters.

Copyright©2023 by Mbaluka S. All 20


rights reserved.
There are two forms of polymorphism, over-riding and over-loading.

Over-riding is the term used to describe the situation where the same
method name is called on two different objects and each object
responds differently.

It allows different kinds of objects that share a common behaviour to


be used in code that only requires that common behaviour.

21
Copyright©2023 by Mbaluka S. All
rights reserved.
Over-riding allows:
oA more straightforward Application Programming
Interface (API) where we can call methods the same name,
even though these methods have slightly different
functionality.
oA better level of abstraction, in that the implementation
mechanics remain hidden.

Copyright©2023 by Mbaluka S. All 22


rights reserved.
The over-ridden draw() method.

Copyright©2023 by Mbaluka S. All 23


rights reserved.
o In this case Car inherits from Vehicle and from this
class Car, there are further derived
classes SaloonCar and EstateCar.

o If a draw()method is added to the Car class, it’ll be


required to draw a picture of a generic vehicle.

o This method will not adequately draw an estate car, or


other child classes.
24
Copyright©2023 by Mbaluka S. All
rights reserved.
o Over-Riding allows us to write a
specialised draw() method for the EstateCar class

o There is no need to write a new draw() method for


the SaloonCar class as the Car class provides a suitable
enough draw() method.

Copyright©2023 by Mbaluka S. All 25


rights reserved.
Copyright©2023 by Mr. Mbaluka S. 26
All rights reserved.
Over-Loading
oOver-Loading is the second form of polymorphism. The
same method name can be used, but the number of
parameters or the types of parameters can differ, allowing
the correct method to be chosen by the compiler.
oFor example:

add (int x, int y)

add (String x, String y)

Copyright©2023 by Mbaluka S. All 27


rights reserved.
Two different methods with the same name and the
same number of parameters. However, when we
pass two String objects instead of two int variables
then we expect different functionality. When we
add two int values we expect an intresult: for
example 8 + 7 = 15. However, if we passed
two String objects we would expect a result of “8"
+ "7" = “87". In other words the strings should be
concatenated. Copyright©2023 by Mbaluka S. All
28

rights reserved.
Assignment:
1. Using examples differentiate between method
overloading over-ridding (6mks)
2. Use short codes in any JAVA language to
depict the following principles of OOP
(12mks)
(i) Inheritance
(ii) Polymorphism
(iii) Encapsulation
3. Explain the concept of abstraction as used in
OOP (2mks)
29
INTERGRATED DEVELOPMENT
ENVIRONMENT (IDE) FOR JAVA CODING
o NetBeans - openSource
o Eclipse – creates cross platform applications for use on mobile,
web, desktop and enterprise domains.
o IntelliJ IDE Community edition – free Java IDE. To unlock all
the features you may need to buy License.
o Android Studio – from Google freely available under the Apache
2.0
o Enide Studio 2014
o DrJava
o JDeveloper
o Jsource
o jGRASP
o jEDIT Copyright©2023 by Mr. Mbaluka S. 30
All rights reserved.
Popular Java Editors
Notepad − one of the most common editor for
windows
Netbeans − A Java IDE that is open-source and free
which can be downloaded
from https://www.netbeans.org/index.html.
Eclipse − A Java IDE developed by the eclipse
open-source community and can be downloaded
from https://www.eclipse.org/. 31
Java Development Kit (JDK)
oIt is a software development environment used for
developing Java applications and applets.
oIt includes the Java Runtime Environment (JRE),
an interpreter/loader (java), a compiler (javac), an
archiver (jar), a documentation generator (javadoc)
and other tools needed in Java development .
oThe SDK for Java is called as JDK.
32
Java Virtual Machine [JVM]
o It is an engine/ program whose purpose
is to execute other programs.
oIt is a specification that provides
runtime environment in which java
bytecode can be executed.

33
The JVM performs following operation:
oLoads code
oVerifies code
oExecutes code
oProvides runtime environment

34
JVM provides definitions for the:
oMemory area
oClass file format
oRegister set
oGarbage-collected heap
oFatal error reporting

35
FIRST PROGRAM/APPLET
oOpen a Java online compiler
oWrite the following code statements
oThen click the run button to see the
effect

36
class HelloWorld {

public static void main(String[] args)


{ System.out.println(“Glad to run my First JAVA
code!");

System.out.println("Expect more!");
System.out.println("You'll have fun!");

37
How to save the file, compile, and
run the program.
oOpen notepad and add the code as
above.
oSave the file as:
MyFirstJavaProgram.java.
oOpen a command prompt window and
go to the directory where you saved the
class. Assume it's C:\.
38
o Type 'javac MyFirstJavaProgram.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).
o Now, type ' java MyFirstJavaProgram ' to run
your program.
o You will be able to see ' the output' printed on the
39
window.
C++ vs Java
A list of top differences between C++ and
Java are as follows:

40
Comparison C++ Java
Index
Platform-independent C++ is platform-dependent. Java is platform-independent.
Mainly used for C++ is mainly used for system Java is mainly used for application
programming. programming. It is widely used in
Windows-based, web-based,
enterprise, and mobile applications.

Design Goal C++ was designed for systems and Java was designed and created as an
applications programming. It was an interpreter for printing systems but
extension of the C programming later extended as a support network
language computing. It was designed to be easy
. to use and accessible to a broader
audience.
Goto C++ supports the goto Java doesn't support the goto
statement. statement.
Multiple inheritance C++ supports multiple inheritance. Java doesn't support multiple
inheritance through class. It can be
achieved by using interfaces in java
.
Operator Overloading C++ supports operator overloading Java doesn't support operator
. overloading.
Pointers C++ supports pointers Java supports pointer internally.
. You can write a pointer program in However, you can't write the pointer
C++. program in java. It means java has
restricted pointer support in java.
Compiler and Interpreter C++ uses compiler only. C++ is Java uses both compiler and
compiled and run using the compiler interpreter. Java source code is
which converts source code into converted into bytecode at
machine code so, C++ is platform compilation time. The 41 interpreter
dependent. executes this bytecode at runtime and
Structure C++ supports Java doesn't support structures and unions.
and structures and unions.
Union
Thread C++ doesn't have Java has built-in thread
Support built-in support for support.
threads. It relies on
third-party libraries for
thread support.
Documen C++ doesn't support Java supports documentation comment (/**
tation documentation ... */) to create documentation for java
comment comments. source code.
Virtual C++ supports virtual Java has no virtual keyword. We can
Keyword keyword so that we override all non-static methods by default.
can decide whether or In other words, non-static methods are
not to override a virtual by default.
function.
unsigned C++ doesn't support Java supports unsigned right shift >>>
right >>> operator. operator that fills zero at the top for the
shift negative numbers. For positive numbers, it
>>> works same like >> operator.
Inheritan C++ always creates a Java always uses a single inheritance tree
ce Tree new inheritance tree. because all classes are the child of the
Object class in Java. The Object class
42 is the
root of the inheritance
Basic Syntax
oCase Sensitivity − Java is case sensitive, which
means identifier Hello and hello would have
different meaning in Java.
oClass Names − For all class names the first letter
should be in Upper Case. If several words are used
to form a name of the class, each inner word's first
letter should be in Upper Case.
43

Example: class MyFirstJavaClass


o Method Names − All method names should

start with a Lower Case letter. If several

words are used to form the name of the

method, then each inner word's first letter

should be in Upper Case.

Example: public void myMethodName() 44


o Program File Name − Name of the program file
should exactly match the class name.
o When saving the file, you should save it using the
class name and append '.java' to the end of the
name
o NB: In case you do not have a public class present
in the file then file name can be different from
class name. It is also not mandatory to have a
public class in the file. 45
o Assuming 'MyFirstJavaProgram' is the

class name, what should be the file

name?

o It should be saved as

'MyFirstJavaProgram.java'
46
o public static void main(String args[])

Java program processing starts from the


main() method which is a mandatory part
of every Java program.

47
Java Identifiers
oAll Java components require names. Names used for
classes, variables, and methods are called identifiers.
oIn Java, the following identifier rules should be observed:

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.

48
3. A key word cannot be used as an identifier.

4. Most importantly, identifiers are case


sensitive.
oExamples of legal identifiers: age, $salary,
_Num, __1_value.
oExamples of illegal identifiers: 123abc, -
salary.
Copyright©2023 by Mr. Mbaluka S. 49
All rights reserved.
Java Variables
oA variable is the name of a reserved area
allocated in memory.

50
Types of Variables

There are three types of variables


in Java:

i.local variable

ii.instance variable

iii.static variable 51
Local Variable
oA variable declared inside the body of the
method is called local variable.
oIt can only be used within that method and
the other methods in the class aren't even
aware that the variable exists.
oIt cannot be defined with "static" keyword.
52
Instance Variable
oIt’s a variable declared inside the class but
outside the body of the method.
oIt is not declared as static
oIts value is instance-specific and is not
shared among instances.

53
Static variable
oIt is declared as static.
oIt cannot be local.
oA single copy of the static variable can be created
and shared among all the instances of the class.
oMemory allocation for static variables happens
only once when the class is loaded in the memory.

54
Example 1
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
55
}//end of class
Example 2
class Simple{
public static void main(String[] args){
int a=10;
int b=10;
int c=(a+b);
System.out.println(c);
}
}
56
Data Types in Java
oData types specify the different sizes and values that can
be stored in the variable. There are 2 types:

1.Primitive data types: The primitive data types include


boolean, char, byte, short, int, long, float and double.

2.Non-primitive data types: User defined data types


declared by the user. The non-primitive data types
include Classes, Interfaces, and Arrays.

57
58
Java Primitive Data Types
oThey are the building blocks of data
manipulation.
oThese are the most basic data types available
in Java language.
oJava is a statically-typed programming
language meaning all variables must be
59
Data Defa Defau Description
Type ult lt size
Valu
e
Boolea false 1 bit Used to store only 2 values: true
n false. It tracks false/ true conditions
Char '\ 2 byte Its value-range lies between '\u0000'
u000 0) to '\uffff' (or 65,535 inclusive).
0'
char data type is used to store characte
Byte 0 1 byte Used to save memory in large arr
because it is 4 times smaller than
integer. Can be used in place of
data type. Value range lies betwee
128 to 127
Short 0 2 byte Value range lies between -32,768
32,767. It is 2 times smaller than
Operators in Java
Operator in Java is a symbol that is used to
manipulate variables. These include:
oUnary Operator
oArithmetic Operator
oShift Operator
oRelational Operator
oBitwise Operator
oLogical Operator
oTernary Operator and
oAssignment Operator.
61
1. The Arithmetic Operators

oArithmetic operators are used in mathematical


expressions in the same way that they are used in
algebra.
oAssume integer variable A holds 10 and variable
B holds 20, then to interpret the following
examples:

62
Operator Description Example

Adds values on either side of


+ (Addition) the operator. A + B will give 30

Subtracts right-hand operand


- (Subtraction) from left-hand operand. A - B will give -10

Multiplies values on either side


* (Multiplication) of the operator. A * B will give 200

Divides left-hand operand by


/ (Division) right-hand operand. B / A will give 2

Divides left-hand operand by


% (Modulus) right-hand operand and returns B % A will give 0
remainder.

Increases the value of operand


++ (Increment) B++ gives 21
by 1.
Decreases the value of operand
-- (Decrement) by 1. B-- gives 19
public class Test {

public static void main(String args[]) {


int a = 10;
int b = 20;
int c = 25;
int d = 25;

System.out.println("a + b = " + (a + b) );
System.out.println("a - b = " + (a - b) );
System.out.println("a * b = " + (a * b) );
System.out.println("b / a = " + (b / a) );
System.out.println("b % a = " + (b % a) );
System.out.println("c % a = " + (c % a) );
System.out.println("a++ = " + (a++) );
System.out.println("a-- = " + (a--) );

// Check the difference in d++ and ++d


System.out.println("d++ = " + (d++) );
System.out.println("++d = " + (++d) );
}
} 64
a + b = 30
a - b = -10
a * b = 200
b/a=2
b%a=0
c%a=5
a++ = 10
b-- = 11
d++ = 25
++d = 27

65
2. The Relational Operators
oThere are following relational operators
supported by Java language.
oAssume variable A holds 10 and variable B
holds 20, then:

66
Operator Description Example
Checks if the values of two operands are
== (equal to) equal or not, if yes then condition becomes (A == B) is not true.
true.

Checks if the values of two operands are


!= (not equal to) equal or not, if values are not equal then (A != B) is true.
condition becomes true.

Checks if the value of left operand is greater


> (greater than) than the value of right operand, if yes then (A > B) is not true.
condition becomes true.

Checks if the value of left operand is less than


< (less than) the value of right operand, if yes then (A < B) is true.
condition becomes true.

Checks if the value of left operand is greater


>= (greater than than or equal to the value of right operand, if
(A >= B) is not true.
or equal to) yes then condition becomes true.

Checks if the value of left operand is less than


<= (less than or or equal to the value of right operand, if yes
(A <= B) is true.
equal to) then condition becomes true. 67
public class Test {

public static void main(String args[]) {


int a = 10;
int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
} 68
Output
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false

69
3. The Logical Operators
oThe following table lists the logical
operators.
oAssume Boolean variables A holds true
and variable B holds false

70
Operator Description Example
Called Logical AND operator.
If both the operands are non-
&& (logical (A && B) is
zero, then the condition
and) false
becomes true.

Called Logical OR Operator. If


any of the two operands are (A || B) is
|| (logical or) non-zero, then the condition
true
becomes true.

Called Logical NOT Operator.


Reverses the logical state of its
! (logical operand. If a condition is true then !(A && B) is
not) Logical NOT operator will make it 71
true
Example:
public class Test {

public static void main(String args[]) {


boolean a = true;
boolean b = false;

System.out.println("a && b = " + (a&&b));


System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}
}
Copyright©2023 by Mbaluka S. All 72
rights reserved.
Output
a && b = false
a || b = true
!(a && b) = true

Copyright©2023 by Mbaluka S. All 73


rights reserved.
4. The Assignment Operators
oFollowing are the assignment
operators supported by Java
language

Copyright©2023 by Mbaluka S. All 74


rights reserved.
Operator Description Example

Simple assignment operator. C=A+B


Assigns values from right side will assign
=
operands to left side operand. value of A +
B into C
Add AND assignment C += A is
operator. It adds right operand equivalent
+=
to the left operand and assign to C = C +
the result to left operand. A
Subtract AND assignment
C -= A is
operator. It subtracts right
equivalent
-= operand from the left
to C = C –
75
operand and assign the
Modulus AND assignment
C %= A is
operator. It takes modulus
equivalent
%= using two operands and
to C = C %
assign the result to left
A
operand.
C <<= 2 is same
<<= Left shift AND assignment operator.
as C = C << 2

C >>= 2 is same
>>= Right shift AND assignment operator.
as C = C >> 2

C &= 2 is same
&= Bitwise AND assignment operator.
as C = C & 2
76
bitwise exclusive OR and assignment C ^= 2 is same
Example

Copyright©2023 by Mr. Mbaluka S. 77


All rights reserved.
Java Operator Precedence

Operator Type Category Precedence

Unary postfix expr++ expr--


prefix ++expr --expr +expr -
expr ~ !
Arithmetic multiplicative */%
additive +-
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
78
Assignment assignment = += -= *= /= %= &=
Java Unary Operator
oThe Java unary operators require only one
operand. Unary operators are used to perform
various operations i.e.:

a)incrementing/decrementing a value by one

b)negating an expression

c)inverting the value of a boolean

79
Java Unary Operator Example: ++ and --

public class OperatorExample{

public static void main(String args[]){

int x=10;

System.out.println(x++);//10 (11)

System.out.println(++x);//12

System.out.println(x--);//12 (11)

System.out.println(--x);//10

}} 80
Output:
10
12
12
10

81
Java Left Shift Operator Example

public class OperatorExample{

public static void main(String args[]){

System.out.println(10<<2);//10*2^2=10*4=40

System.out.println(10<<3);//10*2^3=10*8=80

System.out.println(20<<2);//20*2^2=20*4=80

System.out.println(15<<4);//15*2^4=15*16=240

}}

82
Java Right Shift Operator
The Java right shift operator >> is used to move the value
of the left operand to right by the number of bits specified
by the right operand.

Java Right Shift Operator Example

public OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}} 83
JAVA CONTROL STATEMENTS

oJava compiler executes the code from top to


bottom.
oThe statements in the code are executed
according to the order in which they appear.
oHowever, Java provides statements that can
be used to control the flow of Java code.
84
Java provides three types of control flow
statements.
1.Decision Making statements
o if statements
o switch statement
2.Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3.Jump statements
o break statement 85
o continue statement
DECISION-MAKING STATEMENTS:
oThey decide which statement to execute and when.
oDecision-making statements evaluate the Boolean
expression and control the program flow depending
upon the result of the condition provided .

86
1. If Statement:

In Java, there are four types of if-statements given below:

oSimple if statement

oif-else statement

oif-else-if ladder

oNested if-statement

87
a) Simple if statement:
oIt evaluates a Boolean expression and enables the program
to enter a block of code if the expression evaluates to true.
oSyntax of if statement:

if(condition) {

statement 1; //executes when condition is true

88
Example:
public class Student {
public static void main(String[] args) {
int x = 15;
int y = 22;
if(x+y > 40) {
System.out.println("x + y is greater than 40");
}
}
}
89
b) if-else statement
oIts an extension to the if-statement.
oThe else block is executed if the condition of the
if-block is evaluated as false.

90
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}

91
Example:
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 10");
}
}
}
92
c) if-else-if ladder
oIt contains the if-statement followed by multiple else-if
statements.
oIt is the chain of if-else statements that create a decision
tree where the program may enter in the block of code
where the condition is true.
oAn else statement can be defined at the end of the chain.

93
Syntax of if-else-if statement:
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 3; //executes when all the conditions are false
}

94
Example:
public class Student {
public static void main(String[] args) {
String city = “Nakuru";
if(city == “Mombasa") {
System.out.println("city is Mombasa");
}else if (city == “Kisumu") {
System.out.println("city is Kisumu");
}else if(city == “Nairobi") {
System.out.println("city is Nairobi");
}else {
System.out.println(“Newest City is ”, city);
}
}
95
}
d) Nested if-statement
oThe if statement can contain a if or if-else statement inside
another if or if-else statement.
Syntax of Nested if-statement:
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 3; //executes when condition 2 is false
}
} 96
//Nested-if Java program with if conditions only
public class NestedIfExample {
public static void main(String args[]) {
//declare 2 variables and store some values in it
int num1 = 23;
int num2 = 45;
//if the number 1 is 23
if( num1 == 23 ) {
//if number is 45
if( num2 == 45 ) {
System.out.print("Number 1 is :"+ num1 +" and Number 2 is :"+
num2);
} // end of if condition 2
} //end of if condition 1
} //end of main method 97
Output:

98
public class NestedIfExample {
public static void main(String args[]) {
//declare 2 variables and store some values in them
int num1 = 23;
int num2 = 45;
//if the number 1 is 23
if( num1 == 23 ) {
//if number is 45
if( num2 == 45 ) {
System.out.print("Number 1 is :"+ num1 +" and Number 2 is :"+ num2);
} // end of if condition 2
else
{
System.out.print("Number 2 is not 45");
}//end of else condition
} //end of if condition 1
} //end of main method
99
} //end of class
Develop a java program that accepts total
marks scored in an exam. The program
should remark as follows based on the
total marks:
Total marks Remark

>=500 Distinction

>=400 Credit

>=300 Pass 100


2. Switch Statement:
oIn Java, Switch statements are similar to if-else-if
statements.
oIt contains multiple blocks of code called cases
and a single case is executed based on the variable
which is being switched.
oIts easier to use instead of if-else-if statements.
oIt also enhances the readability of the program.
101
Note:
oCases cannot be duplicated
oBreak statement terminates the switch block when the
condition is satisfied.
oThe case variables can be int, short, byte, char, or
enumeration. String type is also supported since version 7
of Java
oDefault statement is executed when any of the case doesn't
match the value of expression. It is optional.
oWhile using switch statements, we must notice that the
case expression will be of the same type as the variable.
oHowever, it will also be a constant value.

102
The syntax to use the switch statement:
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
} 103
public class Student implements Cloneable {
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
104
}
Output:
2

105
LOOP STATEMENTS
oAre used to execute the set of instructions in a repeated
order.
oThe execution of the set of instructions depends upon a
particular condition.
oThere are three types of loops that execute similarly:

1.for loop

2.while loop

3.do-while loop
106
1. For loop
o It enables us to initialize the loop variable, check
the condition, and increment/decrement in a
single line of code.
o We use the for loop only when we exactly know
the number of times, we want to execute the
block of code.

107
for(initialization, condition, increment/decrement) {

//block of statements

108
109
public class Calculation {
public static void main(String[] args) {
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural num
bers is " + sum);
}
}
110
Output:
The sum of first 10 natural numbers is 55

111
2. While loop
oIf the number of iterations is not known in advance, it is
recommended to use a while loop.
oUnlike for loop, the initialization and increment/decrement doesn't
take place inside the loop statement in while loop.
oThe condition is checked at the start of the loop making it an entry
controlled loop.
oIf the condition is true, then the loop body will be executed;
otherwise, the statements after the loop will be executed.

112
The syntax:
while(condition){
//looping statements
}

113
The flowchart:

114
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 1;
System.out.println("Printing the list of first 5 od
d numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2;
}
}
}
115
3. do-while loop
oIt checks the condition at the end of the loop after
executing the loop statements.
oWhen the number of iteration is not known and we
have to execute the loop at least once, we can use
do-while loop.
oIt is also known as the exit-controlled loop since
the condition is not checked in advance.
116
Do while Syntax:
do
{
//statements
} while (condition);

117
Flowchart:

118
public class Calculation {
public static void main(String[] args) {
int i = 2;
System.out.println("Printing the list of first 5 ev
en numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}

119
JUMP STATEMENTS
oJump statements are used to transfer the control of the
program to the specific statements.
oThey transfer the execution control to the other part of the
program.
oThere are two types of jump statements in Java, i.e.

(i) break

(ii) continue.

120
1. Break Statement
o It is used to break the current flow of the
program and transfer the control to the next
statement outside a loop or switch statement.
o However, it breaks only the inner loop in the
case of the nested loop.
o The break statement cannot be used
independently in the Java program, i.e., it can
only be written inside the loop or switch
statement.

121
public class BreakExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
}
}
}
}

122
break statement example with labeled for loop:
public class Calculation {
public static void main(String[] args) {
a:
for(int i = 0; i<= 10; i++) {
b:
for(int j = 0; j<=15;j++) {
c:
for (int k = 0; k<=20; k++) {
System.out.println(k);
if(k==5) {
break a;
}
}
}
}
} 123
2. Continue statement
oUnlike break statement, the continue
statement doesn't break the loop,
oIt skips the specific part of the loop and
jumps to the next iteration of the loop
immediately.

124
public class ContinueExample {
public static void main(String[] args) {
for(int i = 0; i<= 2; i++) {
for (int j = i; j<=5; j++) {
if(j == 4) {
continue;
}
System.out.println(j);
}
}
}
}
125
Output:
0
1
2
3
5
1
2
3
5

126
WORKING WITH OBJECTS IN JAVA

3 Ways to initialize object

There are 3 ways to initialize object in Java.

i.By reference variable

ii.By method

iii.By constructor

127
1) Initialization through reference

Initializing an object means storing data into the object.

Example in the next slide:

128
class Student{
String id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=MKU001;
s1.name="ONESMUS";
System.out.println(s1.id+" "+s1.name);//
printing members with a white space
}
} 129
Output:

MKU001 ONESMUS

We can also create multiple objects and store information


in it through reference variable.

130
class Student{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=MKU001;
s1.name="ONESMUS";
s2.id=MKU002;
s2.name="MIKE";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
131
}
Output:
MKU001 ONESMUS
MKU002 MIKE

132
2) Initialization through method Example
oIn this example, we are creating the two
objects of Student class and initializing the
value to these objects by invoking the
insertRecord method.
oHere, we are displaying the state (data) of
the objects by invoking the
133
displayInformation() method.
class Rectangle{
int length;
int width;
void insert(int l, int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle2{
public static void main(String args[]){
Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects
r1.insert(12,5);
r2.insert(4,15);
r1.calculateArea();
r2.calculateArea();
}
134
}
• Create a class named circle
• Declare radius
• Use a method named CircleArea to
compute and display the area of the
circle using c1 object
• Can use a subclass named
Circleexample

Copyright©2023 by Mr. Mbaluka S. 135


All rights reserved.
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,“Tom");
s2.insertRecord(222,“Abby");
s1.displayInformation();
s2.displayInformation();
136
}
3. Initialization through a constructor
In the following example employee
records are maintained.

137
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,“Simon",45000);
e2.insert(102,“Ryan",25000);
e3.insert(103,“Jackline",55000);
e1.display();
e2.display();
e3.display(); 138
}
Output:
101 Simon 45000.0
102 Ryan 25000.0
103 Jackline 55000.0

139
3. Initialization of objects
through a constructor
oA constructor in Java is a special method that is used to
initialize objects.
oThe constructor is called when an object of a class is
created.
oIt can be used to set initial values for object attributes:

140
// Create a Main class
public class Main {
int x; // Create a class attribute

// Create a class constructor for the Main class


public Main() {
x = 10; // Set the initial value for the class attribute x
}

public static void main(String[] args) {


Main myObj = new Main(); // Create an object of class Main (This
will call the constructor)
System.out.println(myObj.x); // Print the value of x
}
} 141
Note:
oThe constructor name must match the class name
oThe constructor is called when the object is
created.
oAll classes have constructors by default: if you do
not create a class constructor yourself, Java creates
one for you (then you are not able to set initial
values for object attributes).
142
Constructor Parameters
oConstructors can also take parameters, which is used to
initialize attributes.
oThe following example adds an int y parameter to the
constructor.
oInside the constructor we set x to y (x=y).
oWhen we call the constructor, we pass a parameter to the
constructor (10), which will set the value of x to 10:

143
public class Main {
int x;

public Main(int y) {
x = y;
}

public static void main(String[] args) {


Main myObj = new Main(10);
System.out.println(myObj.x);
}
}
144
You can have as many parameters as you want:
public class Main {
int modelYear;
string modelName;

public Main(int year, String name) {


modelYear = year;
modelName = name;
}

public static void main(String[] args) {


Main myCar = new Main(2010, “Passat");
System.out.println(myCar.modelYear + " " + myCar.modelName);
}
145
}
JAVA MODIFIERS

oModifiers (e.g. the keyword Public) are used to set


the access level for classes, attributes, methods and
constructors.
oThey are divided into two groups:

a)Access Modifiers - controls the access level

b)Non-Access Modifiers - do not control access


level, but provides other functionality
146
Access Modifiers
oFor classes, you can use either public or default:
Modifier Description

public The class is accessible by any other


class

default The class is only accessible by classes


in the same package. This is used when
you don't specify a modifier
147
For attributes, methods and constructors, you can use
one of the following:
Modifier Description

public The code is accessible for all


classes
private The code is only accessible within the
declared class
default The code is only accessible in the same
package. This is used when you don't
specify a modifier.
protected The code is accessible in the same package
148

and subclasses.
Non-Access Modifiers
oFor classes, you can use either final or abstract:

Modifier Description

final The class cannot be inherited by


other classes

abstract The class cannot be used to


create objects (To access an
abstract class, it must be
inherited from another class. 149
For attributes and methods, you can use one of the following:

Modifier Description
final Attributes and methods cannot be
overridden/modified
static Attributes and methods belongs to the class, rather
than an object
abstract Can only be used in an abstract class, and can only be
used on methods. The method does not have a body,
for example abstract void run();. The body is
provided by the subclass (inherited from).
transient Attributes and methods are skipped when serializing
the object containing them
synchronized Methods can only be accessed by one thread at a time
150
volatile The value of an attribute is not cached thread-locally,
Example: Static modifier:
oA static method means that it can be
accessed without creating an object of the
class, unlike public:
oAn example to demonstrate the differences
between static and public methods:

151
public class Main {
// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}
// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
// Main method
public static void main(String[ ] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would output an error
Main myObj = new Main(); // Create an object of Main
myObj.myPublicMethod(); // Call the public method
}
}
152
User input codes
The following example demonstrates
to add two numbers with user input:

153
import java.util.Scanner; // Import the Scanner class
class MyClass {
public static void main(String[] args) {
int x, y, sum;
Scanner myObj = new Scanner(System.in); // Create a Scanner
object
System.out.println("Type a number:");
x = myObj.nextInt(); // Read user input

System.out.println("Type another number:");


y = myObj.nextInt(); // Read user input

sum = x + y; // Calculate the sum of x + y


System.out.println("Sum is: " + sum); // Print the sum
} 154
155

You might also like