Java Programming 3
Java Programming 3
OVERVIEW OF JAVA
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
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
illustrated:
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
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
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.
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.
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 {
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
name?
o It should be saved as
'MyFirstJavaProgram.java'
46
o public static void main(String args[])
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:
48
3. A key word cannot be used as an identifier.
50
Types of Variables
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:
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
62
Operator Description Example
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--) );
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.
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.
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
b)negating an expression
79
Java Unary Operator Example: ++ and --
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
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.
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
86
1. If Statement:
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) {
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
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
ii.By method
iii.By constructor
127
1) Initialization through reference
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
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
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
143
public class Main {
int x;
public Main(int y) {
x = y;
}
and subclasses.
Non-Access Modifiers
oFor classes, you can use either final or abstract:
Modifier Description
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