You are on page 1of 123

Java

Fundamentals of software engineering

Any activity in this world can be done in two ways:


1. Manual way
2. Automated way.

Out of these two ways automated process is more preferred by business people.
Reasons:
1. Machine is faster
2. Machine is more accurate
3. Machine is more efficient
4. Machine makes less number of mistakes

Where exactly software development is involved?


Software development is involved while converting manual process to automated
process.

What is software?
Set of programs that generate instructions to the machine for doing/completing one or
more activities of a business automatically.

How do we develop software?


By using programming languages like C, C++, Java or .NET

Activity Activity

Data

Activity Activity
JVM Architecture
JVM Environment

Source file Class Loader Java Class


Byte Code Library
Verifier

Java Byte
code J
Java Just in time V
Java move Interpreter Compiler
Compiler locally or M
through
network Runtime System

Java
Byte code
Class Operating System

Hardware

➢ The Java Virtual Machine is called “virtual” because it is an abstract computer


defined by a specification but to run a Java program, a concrete implementation
of the abstract specification is needed.

What is Java Virtual Machine?


The three things should understand about JVM are:
The abstract specification
A concrete implementation
A runtime instance

➢ The abstract specification is a concept, which has a powerful mechanism to


support java features
➢ Concrete java features implementation, which exists on many platforms and
come from many vendors, are either all software or a combination of software
and hardware
➢ A runtime instance hosts a single running java application
Each java application runs inside a JVM runtime instance, of some
concrete implementation of the abstract specification of the JVM

The life time of Java Virtual Machine


When a java application
Starts: A runtime instance is born
Completes: The instance dies
If you start three java applications at the same time, on the same computer, using the
same concrete implementation, you’ll get three virtual machine instances (check in task
manager)

A JVM instance starts running its application by invoking the main() method of some
internal class [ The main () method must be public, static, returns void and accept one
parameter : a String array]

One real world example of a JVM implementation is the Java program from Oracle’s java
2 SDK
Class loader
The Architecture of JVM subsystem

Method Heap Java PC Native


area Stacks registers methods
stacks

Execution Native Native


engine method method
interface libraries
Method Area and Heap

Class Class object


object
data data

Class
Class object
data
data

Class Class
object object
data data
Method Area Heap
Method area is also called class context Heap
It contains Whenever a class instance is created in
➢ The class, interface, array or a running java application the memory
enum type for the new object is allocated from the
➢ The method information heap
➢ The class data

Java Stack

Thread 1 Thread 1 Thread 2 Thread 3 Thread 3


Stack Stack Stack
frame frame frame
Thread 2
Stack Stack
frame frame
Native
Thread 3 Stack method
frame stacks
Java Stacks

A Java Stack stores a thread’s state


The JVM only performs two operations directly on java stack
➢ It push and pops frames

When a new thread is launched, the JVM executes a new java stack from the thread

The class loader subsystem


The part of a Java Virtual Machine implementation that takes care of finding and
loading types (class, interface, array or enums) is the class loader subsystem
Object Oriented Programming

These concepts describe developing based on objects (software objects)

What is an object?
➢ Any physical representation is called object
➢ Any object in this world occupies space

What is a software object?


➢ Software object is a representation to the real time object and it will be created
in the computer memory cell called RAM.

Physical representation forms


➢ Solid
➢ Liquid
➢ Gas
Properties ➔ occupies space

Software objects will be used by the machine for doing different activities. This process
is called automated process.

Manual Process Automated Process

Human does the work Machine does the work

By using real time objects By using software objects

What is a class?
➢ Class is a plan of software object.
➢ Class is not a physical representation
➢ Class is an imaginary representation (planning representation)

What is an object?
➢ Physical representation of a class (Instance of a class)
➢ Software object is a representation of a real time object.
➢ Software object will be created in the computer memory called RAM. The
memory area in RAM where we are creating software objects is known as Heap
Memory.
➢ Software object is a collection of variables and Methods.
What is the difference between class and object?
➢ Planning Vs Physical
➢ Imaginary representation Vs Real Representation

What is the difference between objects?


➢ Whenever we compare two different objects in the RAM their memory locations
will be compared. Because the memory addresses are always different the
objects are always different.
➢ Objects might be looking similar or may not be looking similar. But the
fundamental difference is their memory locations are always different.
➢ By using a simple class we can construct ay number of software objects
depending on the availability of memory space in the RAM.

What is the difference between class and object?

Planning representation Vs Physical representation


Imaginary representation Vs Real representation

What does a class contain?


Class is having variables and methods. Because class is plan of object, object also
contains variables and methods.

Important Note: Object is a collection of variables and methods

What is the difference between objects?


Any two objects in this world are always differentiated by their location.

What is the difference between two software objects?


Any two software objects in our computers are always compared by using their
memory address.
1001 s/w obj 1
1002
:
:
: s/w obj2
:
Because the two memory address of these 2 objects are different, the two
software objects are always different. Almost maximum 2 software objects may look
similar but their locations are always different.
By using a single class (plan) we can construct any number of software objects.

What is data?
The value stored in a variable is called data.

What is data corruption?


Changing a variable value by applying wrong logic is called data corruption.

Understanding the concept variables


We can access a memory cell from our program by giving a name to it.
RAM

In our program x

We can store a value in the memory cell from our program by using the name given to
the memory cell RAM

10 In our program x = 10

At any point of time we can change the value in the memory cell by using the name
given to this memory cell in our program
Because we are changing (varying) the value in the memory cell using the name, the
name is called variable. RAM

In our program x = 20
20

What kind of values we can store in these memory cells?


➢ We can store numbers and letters.

Types of variables based on supported values


What is Data?

➢ The Value stored in a variable is called Data.

Data Types
Because the numbers are infinite and infinite range cannot be stored in the
memory, in java numbers are classified from smallest to biggest number range.

byte (8 bit) Number Range: -128 to 127


short (16 bit) Number Range: -32718 to 32767
int (32 bit) Number Range: -2147483648 to 2147483647
long (64 bit) Number Range: -9223372036854775808 to
9223372036854775807
float (32 bit) IEEE 754 floating point standard
double (64 bit) IEEE 754 floating point standard
boolean (1 bit)

Variable Declaration
Data type followed by variable name is called variable declaration.

Eg: int x;

Meaning: Reserve memory for the data type int in the RAM and access this memory
using the name X from our program. We can store only integer value in that memory.
RAM

In our program int x;


4 bytes (32 bit) are reserved for integer in RAM.
This memory can be accessed by using the name x
from our program. Using the name x we can store
only integer values in that memory.

Types of operators
1. Assignment operator
2. Arithmetic operator
3. Unary operator
4. Equality operator
5. Relation operator
6. Conditional operator
7. Bitwise operator
8. Bit shift operator

Assignment operator =
Eg : int age = 28;

Arithmetic operator
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder

Unary operator

+= count + = 1;
-= count - = 1;
++ count ++; ++ count;
-- count --; -- count;

Equality operator
== equal to
!= not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to

Conditional operator
&& conditional – AND
|| conditional – OR

Bitwise and Bit shift operator


& bitwise AND
^ bitwise exclusive OR
| bitwise inclusive OR
~ unary bitwise complement
<< signed left shift
>> signed right shift
>>> unsigned right sift
Variable Declaration
int x; double d; boolean b;
float f; char ch; long l;

Variable Assignment
int x = 95; double d = 23.75
float f = 23.57 incorrect float f = 23.57f
char ch= ‘A’ boolean b = true;
long l = 275;

split up notation shortcut notation


int x; int x = 10;
x = 10

What is initialization?
➢ Assigning a value to a variable for the first time is called initialization

Type Casting
➢ Type casting mean converting one data type to another data type within the
allowed conversion list.

int x = ‘A’

➢ In this example the letter ‘A’ wont be stored in the variable x, instead the letter
‘A’ is converted to its ASCII value 65 and then the value 65 will be stored in the
variable x

Types of type casting


1. Implicit Type Casting
2. Explicit Type Casting

Implicit Type Casting: If our program is converting one data type to another data type
automatically is called implicit type casting.
Here the programmer need not specify any extra syntax in our program for this
conversion.
Eg : int x = ‘A’;

Explicit Type Casting: If we indicate at our program for converting one data type into
another data type, it is called as explicit type casting
Eg: char ch = (char) 65;
This is an indication that the number 65 should be converted to charter. Now 65 will be
treated as ASCII value and converted to its equivalent character ‘A’.
Pre & Post Increment
Pre Increment Post Increment
int x; int x;
x = 10; x= 10;
++x; // x = x +1 x++; // x = x + 1
print (x); print (x);
The difference between pre and post increment cannot be observed when we are using
split-up notation.

We can understand their difference during short-cut notation only.

Pre Increment Post Increment


int x; int x;
int y; int y;
x = 10; x= 10;
y = ++ x y= x ++;
print (x); print (x);
print (y); print (y);

x= x+1 y=x
y= x x = x+1
11 11
11 10

What is pre increment?


When pre increment is used in short cut notation the increment statement
should be used first and then other statement should be executed.
x = x+ 1
y= x

What is the meaning of post increment?


When we use post increment in a shortcut notation the other statement should
be executed first and then only the increment statement should be executed.
y = x ++
y= x;
x= x + 1;
Pre Increment Post increment
int x; int x;
x = 10; x = 10;
print ( ++x); print (x++);
11 10
Eg: Eg:
int x; int x = 10;
x=10; int y = 11;
x= x +++ x; int z = x +++y;
print (x); print (x);
x = 21 print(y);
print (z);
11 11 21
z = (x++) + y

Equality Operator
This operator compares both the sides of an equation one is LHS and other is
RHS. The equality operator returns true if both LHS and RHS are having the same value.
Equality operator returns false if both LHS and RHS are having different values.

int x = 10;
int y = 20;
boolean b = (x ==y);
10 == 20
= false;
Conditional Operator
if (condition 1 && condition 2)

Will be executed may or may not be executed


always its execution depends on first one

Condition 2 will always be executed only when condition one is successful.


Condition 2 will not be executed only when condition 1 fails.
If both conditions are true then operator returns true.
If condition 1 is false this operator returns false without executing condition 2.

Conditional Operator OR (||)

if (condition 1 || condition 2)

Will be executed may or may not be executed


always its execution depends on first one
If first condition is true second condition will not be executed.
If first condition is false then second condition will be executed.
This operator returns false only when both the conditions are false, otherwise it returns
true.

Methods
➢ Methods are called as functions in C programming language.
➢ Method or functions are nothing but activities in business.
➢ The characteristics of activity in diagrammatic representation

Name

Input Steps Output

Example
Add
Parameters Number 1 Sum = num 1
+ num 2 Sum
Input Number 2 (return value output)

Programming representation of an activity with example

Input parameters
Indicates the
type of the
result int add ( int num 1 , int num 2)
(return type)
{
int sum = num 1 + num 2; steps
return sum; return type of O/P
}

Method is having two parts

1. Method signature (Method definition)


2. Method implementation (Method body)
Example

int add ( int x , int y)


{
int sum = x + y;
return sum ;
}

Method signature contains


1. Name (eg add) 2. Parameters ( eg x & y) 3. Return type ( eg int)

Method implementation contains


1. Some statements ( functionality ) with in open and closed curly braces
2. The last statement should be return statement.

Calling add method from some other place in our program:

int value = add ( 15,20);


The values we are passing to the method parameters are called as arguments. In this
example 15 and 20 are called as arguments.

Following are the return types supported by methods:


1. Void
2. boolean
3. char
4. byte
5. short
6. int
7. long
8. float
9. double
10. Any object.

Program execution mechanism


1. Write a program by using any one of the English languages like C, C++ , Java, .NET
2. Convert the English language program into machine language program by
compiler
3. Execute the machine code ( Program)

What happens when we execute a program?


➢ Every program will execute and run under the control of the operating system.
➢ Operating system allots some memory in the RAM
➢ Operating system allots some resources for our program eg: CPU Cycle, Network
Connections, Database Connections, I/O Streams etc.
➢ Operating system allots a program execution control to our program.
➢ A program execution control is a responsible mechanism for executing our
program
➢ A programs execution control always enters into the main method in the
program.
➢ Program execution control executes all the lines in the main method one by one.
➢ Once the main method is completed the execution control come out of the main
method and informs the operating system that it has completed its task.
➢ Now the operating system cleans up the memory allotted to our program and
removed the resources allotted to the program so that they can be reused by
other programs.

What is the meaning of method’s return type integer?


➢ It indicates a program execution control should complete the task in that
method and then come out of that method by carrying an integer value and
hand it over to the calling method.

What is the meaning of the method’s return type character?


➢ It indicates a program execution control should complete the task in that
method and then come out of that method by carrying character value and hand
it over to the calling method.

What is the meaning of the method’s return type void?


➢ This return type indicates that the program execution control should complete
the task defined in that method and then come out of that method without
carrying any value and then it does not hand over any value to the calling
method.

While Loop For Loop


int x = 10 int x = 10
int count = 1 for (int count = 1; count <= 10; count ++)
while ( count < = 10) {
{ print (x);
print (x); }
count ++
}

What is data Abstraction?


Hiding the variables from unauthorized functions is called data abstraction.
Design meaning of a call (second meaning of class)
➢ Design meaning of class describes how to write a class
➢ Grouping similar (related) variables and methods together is called design
meaning of a class.

By applying design meaning of a class, the above program can be divided into the
following classes.

class Arithmetic class NonArithmetic


{ {
int a = 1, b = 2; int c = 10, d = 20;
int add ( ) void swap ( )
{ {
return a + b; c = c + d;
} d = c – d;
int sub ( ) c = c – d;
{ }
return a – b; }
}

}
Fundamental principal – 1
Encapsulation
Achieving data abstraction (hiding the variables)
How?
➢ By combining similar variables and methods together
➢ Using access modifiers.

A Class declaration in java and C# . NET

class <class name>


{
Variable declaration;
Method declaration;
Constructor declaration;
}

Constructors
Constructor is place defined for initializing variables during object creation.
➢ A place supplies values to the variables.
➢ Should be used during object creation.
➢ Constructor is used only once per object.
➢ A constructor can be used for several objects.
➢ Constructor initializes the variables.

Important Note: Without using a constructor object creation is impossible.

Understanding constructor – Real-time usage


Constructor is place defined for initializing the variables with business rules and
these rules should be applied while constructing objects.

What are business rules?


The values suggested by the business area (where we are developing our
software) are known as business rules.

Constructor declaration rules


➢ Constructor look like method
➢ Constructor does not have return types
➢ Constructor name should be same as class name
First Class

class SimpleArithmetic
{ Variable
int a, b; declaration
simplearithmetic ( )
{ Constructor
a = 10; declaration
b = 20;
}
int add ( )
{ Method
return a + b; declaration
}
}

Usage meaning of class (third meaning of Class)


A class should be used as a data type. Because a class can be written by a programmer,
class can be called as user defined data type.

Object construction process


Object of SimpleArithmetic
at memory location 2255
(simpleobj)
a = 10; 2255
b = 20;
add ( )

Datatype Variable or object

SimpleArithmetic simpleobj // int x;


simpleobj = new SimpleArithmetic ( ); // x = 5;

➢ The new operator creates an object in the computer memory by using


constructor.
➢ The new operator returns a reference (memory location) to the object it created.
➢ New operator followed by constructor always creates an object.
In the above diagram the variable simpleobj can be called object reference
An object reference always stores the memory address of an object.
Object reference -----------> simpleobj

new<constructor> -------> creates an object in the memory and returns the


memory address of that object.
Because object is a collection of variable and methods, an object reference can
access it’s variables and methods by using another operator called . (dot).

Example:
Simplearithmetic simpleobj = new SimpleArithmetic ( );
int x = simpleobj.a;
int y = simpleobj.b;
int sum = simpleobj.add( );
// print statement in java

System.out.println(sum);

//main method in java


public static void main (String [ ] args)
{
// write the main method code
}

First Java program


//SimpleArithmetic.java
class SimpleArithmetic
{
int a, b;
SimpleArithmetic ( )
{
a = 10;
b = 20;
}
int add ( )
{
return a + b;
}
public static void main (String [ ] arr)
{
SimpleArithmetic simpleobj = new SimpleArithmetic ( );
int sum = simpleobj.add ( );
System.out.println(sum);
}
}

Compiling the Java program

Javac SimpleArithmetic.java
After successful compilation we get a new file called SimpleArithmetic.class
After successful compilation of .NET program we get a new file called
SimpleArithmetic.exe

Note: This class file is having the program written in the intermediate language. The
name of the java’s intermediate language is Byte code.
The name of the .NET intermediate language is MSIL (Microsoft Intermediate Language)
Execution of class file
Java SimpleArithmetic

Real-time Execution

Object of SimpleArithmetic
at memory location 2255
(simpleobj)
a = 10; 2255
b = 20;
add ( )
Sum = 30

Global variable will be stored inside the object. Local variables will be store
outside the object.

Global and Local Variables


What are Global Variables?
Variables declared outside the method are called Global Variables.

Variable declaration means: Data type followed by variable name


In the above program we have declared two global variables a and b.

What are local variables?


Variables declared inside the method are called local variables.
In the above program the local variables are Sum, Simpleobj and arr.

Assigning values to different data types


int x = 10;
char ch = ‘a’;
float f = 10.73f;
double d = 77.123;
String s = “LearnSoft”

class Chair
{
int legs;
String color;
String material;

void chair ( )
{
legs = 4;
color = "blue";
material = "plastic";
}
void printChairDetails ( )
{
System.out.println (legs);
System.out.println (color);
System.out.println (material);
}
}

class House
{
String color;
String window;

House ( )
{
color = "red";
window = "designed";
}
String getHouseColor()
{
return color;
}
String getWindowModel ( )
{
return window;
}
void printHouseDetails()
{
System.out.println (color);
System.out.println (window);
}
}

class ClassRoom
{
int students;
String faculty;
String Board;
int chairs;

ClassRoom ( )
{
students = 50;
faculty = "Pratap";
Board = "White";
chairs = 50;
}
int getStudentCount ( )
{
return students;
}
void printFacutlyName ( )
{
System.out.println (faculty);
}
void printClassBelongings ( )
{
System.out.println ("board color = " + Board );
System.out.println (chairs);
}
}
Type of constructors for initializing the variables in an object
For initializing the variables in an object, constructors can be divided into 2 types.
➢ Zero argument constructor ( Zero parameter constructor)
➢ More argument constructor (Parameterized constructor)

Zero argument constructor: A constructor not having any parameters is called as Zero
argument constructor.
Example:
SimpleArithmetic ( )
{
a = 10;
b = 20;
}
➢ Zero argument constructors can also be called as Zero parameter constructor.
➢ Zero argument constructors always help in creating similar objects.
class SimpleArithmetic
{
int a, b;
SimpleArithmetic ( )
{
a = 10;
b = 20;
}
int add ( )
{
return a + b;
}
public static void main (String [ ] arr)
{
SimpleArithmetic simpleobj1 = new SimpleArithmetic ( );
int sum1 = simpleobj1.add ( );
System.out.println(sum1);
SimpleArithmetic simpleobj2 = new SimpleArithmetic ( );
int sum2 = simpleobj2.add ( );
System.out.println(sum2);
}
}

Output:
30
30

Object of SimpleArithmetic
at memory location 2255 (simpleobj1)
a = 10; 2255
b = 20;
add ( )
Sum1 = 30

Object of SimpleArithmetic
at memory location 2580 (simpleob2j)
a = 10; 2580
b = 20;
add ( )
Sum2 = 30

More argument constructor


A constructor that is having parameters is called as more argument constructor
or parameterized constructor.
Example:
SimpleArithmetic ( int x, int y)
{
a = x;
b = y;
}

➢ More argument constructor always helps in creating dissimilar objects. That


means the variables in these objects should have same names but different
values.

class SimpleArithmetic
{
int a, b;
SimpleArithmetic (int x, int y )
{
a = x;
b = y;
}
int add ( )
{
return a + b;
}
public static void main (String [ ] arr)
{
SimpleArithmetic simpleobj1 = new SimpleArithmetic (10,20);
int sum1 = simpleobj1.add ( );
System.out.println(sum1);
SimpleArithmetic simpleobj2 = new SimpleArithmetic (70,12);
int sum2 = simpleobj2.add ( );
System.out.println(sum2);
}
}

Output:
30
82

Runtime Execution

Object of SimpleArithmetic
at memory location 2255 (simpleobj1)
a = 10; 2255
b = 20;
add ( )
Sum = 30

Object of SimpleArithmetic
at memory location 2580 (simpleobj2)
a = 70; 2580
b = 12;
add ( )
Sum = 82
What is constructor overloading?
A class is having more than one constructor but differentiated based on their
parameters is called as constructor overloading.

class SimpleArithmetic
{
int a, b;
SimpleArithmetic ( )
{
a = 10;
b = 20;
}
SimpleArithmetic (int x, int y)
{
a = x;
b = y;
}

int add ( )
{
return a + b;
}
public static void main (String [ ] arr)
{
SimpleArithmetic simpleobj1 = new SimpleArithmetic ( );
SimpleArithmetic simpleobj2 = new SimpleArithmetic ( );
SimpleArithmetic simpleobj3 = new SimpleArithmetic (9,11);
SimpleArithmetic simpleobj4 = new SimpleArithmetic (99,100);

int sum = simpleobj1.add ( );


System.out.println("sum= " + sum);
int m = simpleobj2.a ;
System.out.println("value of a = " + m);
System.out.println("value of b before changing = " + simpleobj3.b);
simpleobj3.b = 25;
System.out.println ("value of b after changing = " + simpleobj3.b);
int s= simpleobj4.a + simpleobj4.b;
System.out.println("value of a +" + s);
}
}

Output:
sum= 30
value of a = 10
value of b before changing = 11
value of b after changing = 25
value of a +199

class SimpleArithmetic
{
int a, b;
SimpleArithmetic ( )
{
a = 10;
b = 20;
}
SimpleArithmetic (int y)
{
a = 10;
b = y;
}
SimpleArithmetic (int x, int y)
{
a = x;
b = y;
}

public static void main (String [ ] arr)


{
SimpleArithmetic simpleobj1 = new SimpleArithmetic ( );
SimpleArithmetic simpleobj2 = new SimpleArithmetic ( );
SimpleArithmetic simpleobj3 = new SimpleArithmetic (10);
SimpleArithmetic simpleobj4 = new SimpleArithmetic (15);
SimpleArithmetic simpleobj5 = new SimpleArithmetic (10,20);
SimpleArithmetic simpleobj6 = new SimpleArithmetic (11,20);
SimpleArithmetic simpleobj7 = new SimpleArithmetic (15,30);
SimpleArithmetic simpleobj8 = new SimpleArithmetic (80,40);
}
}

Write a class house


Sting color = color of house
String window = model of window
Write three constructors
1. Should find value for both color and window
2. Should find value for window model but accept the value from the user for
building color.
3. Should accept the values from the users for both building color and window
model.
Write three methods
1. A method to get the color value
2. A method to get window model value
3. A method to print both values of color and model
Create the following objects
1. Two house objects by using zero argument constructor for rajesh and Mahesh.
2. One house object by using one argument constructor for vinky
3. One house object for using two argument constructor for pinky.
Other requirements
Vinky wants to know the color of his house.
Pinky wants to print all the values.
Mahesh wants to know the window model.

class House
{
String color;
String window;
House ( )
{
color = "Red";
window = "round";
}
House (String x)
{
color = "yellow";
window = x;
}
House (String a, String b )
{
color = a;
window = b;
}
String getColor()
{
return color;
}
String getWindow()
{
return window;
}
public static void main (String [ ] arr)
{
House rajesh = new House ( );
House mahesh = new House ( );
House vinky = new House ("wooden " );
House pinky = new House ("blue", "square" );
System.out.println(vinky.getColor());
System.out.println(pinky.getColor() +" " + pinky.getWindow());
System.out.println(mahesh.getWindow());
}
}
Output:
yellow
blue square
round

What happen if you doesn’t declare constructor?


The java and C# compiler automatically provides a no-argument default
constructor for any class not having any constructor (created by the user)
Example:
//Class without a constructor
class SimpleArithmetic
{
int a, b;
int add()
{
return a + b;
}
public static void main (String [ ] arr)
{
SimpleArithmetic simpleobj = new SimpleArithmetic ( );
int sum = simpleobj.add ( );
System.out.println (sum);
}
}
Output a = 0, b = 0, sum = 0

Run time execution

Object of simpleArithmetic
at memory location 2255 (simpleobj)
a = 0; 2255
b = 0;
add ( )
Sum = 0
Default values for the data types:
Data type Default value
byte 0
short 0
int 0
long 0
float 0.0f
double 0.0
boolean flase
char ‘\u0000’ space
String (or any ref obj) null

Understanding spit up and short-cut notation

int x; int x = 10;


x = 10;
split up notation short cut notation

An example that converts split up notation into short cut notation.


SimpleArithmetic simpleobj;
simpleobj = new SimpleArithmetic ( );
int sum = simpleobj.add( );
System.out.println (sum);

Ref obj actual obj

SimpleArithmetic simpleobj = new SimpleArithmetic ( );


int sum = simpleobj.add ( )
System.out.println (sum)
int sum = (new SimpleArithmetic ( ) ) . add ( );
System.out.println (sum);
System.out.println (new SimpleArithmetic ( ) ) . add ( );

Using shortcut notation create simplearithmetic obj and access its add method and it’s a
variable.

class SimpleArithmetic
{
int a, b;
SimpleArithmetic ( )
{
a = 10;
b = 20;
}
int add ( )
{
return a + b;
}
public static void main (String [ ] arr)
{
SimpleArithmetic simpleobj = new SimpleArithmetic ( );
int sum = simpleobj. add ( );
System.out.println (sum);
int sum2= new SimpleArithmetic ( ). add ( );
System.out.println (sum2);
}
}

Output:
30
30

Run time execution


Object of simpleArithmetic
at memory location 2255
(simpleobj)
a = 10; 2255
b = 20;
add ( )
Sum = 30

Object of SimpleArithmetic
at memory location 2580
a = 10;
b = 20;
add ( ) Sum = 30

In the above diagram the obj created at the memory location 2255 is having an
object reference, so that their obj can be accessible further in the program at main
method.
The obj created at the memory location 2580 does not have obj reference,
because it is created by using the shortcut notation. Such kind of obj are accessible only
once, that to during obj creation.
This second obj can’t be useful further in our program because it is not having
object reference. Such kinds of objects are called as unused object. This obj is eligible for
deletion from garbage collection.

Access modifiers (access specifiers)

Access modifiers are used to control what our class objects can access or cannot
access its’ own variables or methods if they (our object) are created in some other
objects.

List of access modifiers.


1. Public 2. Private 3. Default (No modifier) 4. Protected

What is the meaning of defining the access modifier public?


This permission indicates an objected can access its own public variables and
public methods, if our objects are created in some other class.

What is the meaning of defining the access modifier private?


This permission indicates an object cannot access its own private variables and
private methods if that object is created in some other class.

If an objected is created with the same class the object can access its own
private variables and private methods because access modifiers are not applicable if
objects are created in the same class.

Parent child relation No parent child relation

A
A
Same dir diff dir
B
B

Dir are called as ……….. in java


Dir are called as assemblers or main spacer in C #

Industry rules should be followed while writing a class.


➢ Variables should be declared as private
➢ Methods should be declared as public
➢ Constructors should be declared as public
➢ Class should be declared as public
There are two ways we can access the variable of an object by using object reference.
1. Direct approach: It indicated accessing a variable by using object reference.
2. Indirect approach: It indicates access variables of an object using a method
defined in the same object. Now access the method by using that object’s
reference, that means object reference is accessing the method and internally
the method is accessing the variable, so it is called indirect approach.
Accessing the variables directly by using the object reference is not safe because
any mistake made by the programmer may corrupt the data. Accessing the variables
through methods is always safe because any number of times you access the method,
the same code will be executed.

Access modifier
Example:
public class SimpleArithmetic
{
private int a, b;
public SimpleArithmetic ( )
{
a = 10;
b = 20;
}
public int add ( )
{
return a + b;
}
}
Types of variables in java
Local Variables
➢ The variables declared in the method body
➢ They will be created only during method execution and deleted from the
memory soon after the computation of the method.
➢ Accessible only during method call
➢ They are also called temporary variables.
Example:
int sum = simpleobj.add( );

Parameters
➢ The variables declared in the method signature.
➢ They will be created only during the method call and deleted from the memory
after the completion of the method.
➢ They are also called temporary variables
Example:
public static void main (String [ ] args)
The args is variable in the parameter to this method.

Instance Variables
➢ They will be created during object creation
➢ Each object maintains its own variables
➢ They are called non static variables

Class Variables
➢ They will be created first time when we access/use the class
➢ These variables are shared by all objects
➢ A class variable is any field declared with the keyword static

Example:
private static int count;
You can access static variables without creating an object and by using class name
Syntax:
<class name> . <static variable>;
program1.count;
Program1 is class name and count is variable.

An example to understand the difference between instance variables and class


variables.

public class SimpleStaticProg


{
private int a;
public static int count = 0;
public SimpleStaticProg ( )
{
a = 10;
}
public void change ( )
{
a = a + 1;
System.out.println (a);
}
}
public class SimpleTest
{
public static void main (String [ ] args)
{
SimpleStaticProg simpleobj1 = new SimpleStaticProg ( );
simpleobj1.change();
SimpleStaticProg.count = SimpleStaticProg.count + 1;
System.out.println (SimpleStaticProg.count);
SimpleStaticProg simpleobj2 = new SimpleStaticProg ( );
simpleobj2.change( );
SimpleStaticProg.count = SimpleStaticProg.count + 1;
System.out.println (SimpleStaticProg.count);
}
}

Output:
11 1 11 2

Runtime diagram
I II III count = 0 IV count = 1
count = 0 Simpleobj1 simpleobj1 SimpleStaticProg.co
A = 10 a = 11 unt =
simpleobj1.change( SimpleStaticProg.co
) unt + 1
V count = 1 VI count = 1 VII count = 2
simpleobj1 a = 11 simpleobj1 a = 11 SimpleStaticProg.co
simpleobj2 a = 10 simpleobj2 a = 11 unt =
Each obj maintains simpleobj2.change( ) SimpleStaticProg.co
it’s own variables unt + 1
Q) How many ways we (programmer) can access a class variables?
A) 3 ways – using class name, through constructor (during object creation), through
method (after object creation)

Q) How many ways an object can access class variables?


A) 2 ways – through constructor (during object creation) and through method (after
object creation)

Note: We can also access a class variable by using object reference in java, but it is not
recommended in software industry.

An example for accessing class variables by using object during their creation.
public class SimpleStaticProg
{
private int a;
public static int count;
public SimpleStaticProg ( )
{
a = 10;
count = 0;
}
public void change ( )
{
a = a + 1;
System.out.println (a);
}
}
public class SimpleTest
{
public static void main (String [ ] args)
{
SimpleStaticProg simpleobj1 = new SimpleStaticProg ( );
simpleobj1.change();
SimpleStaticProg.count = SimpleStaticProg.count + 1;
System.out.println (SimpleStaticProg.count);
SimpleStaticProg simpleobj2 = new SimpleStaticProg ( );
simpleobj2.change( );
SimpleStaticProg.count = SimpleStaticProg.count + 1;
System.out.println (SimpleStaticProg.count);
}
}
Output:
11 1 11 1

Runtime Execution
I II III count = 0 IV count = 1
count = 0 simpleobj1 SimpleStaticProg.c
count = 0 Simpleobj1 a = 11 ount =
a = 10 simpleobj1.change( ) SimpleStaticProg.c
ount + 1
V count = 0 VI count = 0 VII count = 1
simpleobj1 a = 11 simpleobj1 a = 11 SimpleStaticProg.cou
simpleobj2 a = 10 simpleobj2 a = 11 nt =
Each obj maintains simpleobj2.change( ) SimpleStaticProg.cou
it’s own variables nt + 1
Constant:
➢ Whose value cannot be changed
➢ Should be declared globally
➢ Only once copy should be created for all object (static behaviour)
➢ Can be accessible using class name
➢ Constants must be initialized during their declaration itself.
Syntax:
public static final float pi = 3.14f;

17.6.14
Read only variables: It is instance variable whose value cannot be changed after
initializing the variable because it is an instance variable (read only), each object
maintains its own copy and its own value in that copy of the read only variable.
If ‘r’ is read only variable the object diagram can be described as shown below:
r=5
Read only variable
Java → final
C# .NET → readonly
Syntax:
private final int r;
//ReadOnlyDemo.java
public class ReadOnlyDemo
{
private final int r;
public ReadOnlyDemo ( )
{
r = 5;
}
public ReadOnlyDemo (int read)
{
r = read;
}
public void print ( )
{
System.out.println(r);
}
public static void main (String [ ] args)
{
ReadOnlyDemo rd1 = new ReadOnlyDemo ( );
ReadOnlyDemo rd2= new ReadOnlyDemo ( );
ReadOnlyDemo rd3= new ReadOnlyDemo (8);
ReadOnlyDemo rd4 = new ReadOnlyDemo (22);
rd1.print ( );
rd2.print ( );
rd3.print ( );
rd4.print ( );
}
}
Output -- 5 5 8 22

What is the output of the following program?


//SimpleConstantProg.java
public class SimpleContastantProg
{
public int a;
public static final float pi;
}
public SimpleConstantProg( );
{
a = 10;
pi = 3.14f;
}
}
//SimpleTest.java
public SimpleTest
{
public static void main (String [ ] args)
{
System.out.println (SimpleContstantProg.pi)
}
}
Output:
This program will result as compilation error because constant must be initialized
during the declaration but not in the constructor.

Static Method
➢ Any method declared with the keyword Static
➢ Static methods should be accessed (invoked) by using the class name
➢ Static methods can be accessible without creating the object

Example:
public static void print pi ( )
{
------
}
public class SimpleStaticMethodProg
{
private int a;
private static final float pi = 3.14f;
public SimpleStaticMethodProg ( )
{
a = 173;
}
public void printData( )
{
System.out.println (a);
}
public static void printpi ( )
{
System.out.println (pi);
}
public static void main (String [ ] args)
{
SimpleStaticMethodProg.printpi( );
}
}
Output --- 3.14

What is the output of the following program?


public class SimpleStaticMethodProg
{
private int a;
private static final float pi = 3.14f;
public SimpleStaticMethodProg ( )
{
a = 173;
}
public void printData( )
{
System.out.println (a);
}
public static void printpi ( )
{
System.out.println (pi);
System.out.println (a);
}
public static void main (String [ ] args)
{
SimpleStaticMethodProg obj = new SimpleStaticMethodProg ( );
SimpleStaticMethodProg.printpi( );
}
}

We get compilation error during the following rules:


➢ Static methods cannot access instance variables or instance methods directly
➢ Because at the time of loading static methods, instance variables and instance
method are not available in the memory
➢ Static methods can access static variables and static method directly.
➢ Instance methods can also access static variables and static methods
➢ Static methods and static variable will be loaded into the memory before the 1 st
object creation itself.
➢ Static method and static variables and even constants are not stored inside the
object
➢ Instance variables(including read only variables) and instance methods are
stored inside the object
The revised definition of what an object is having
Object is a collection of instance variables and instance methods.

Object at 2233 Obj ref


2233
Instance variables
Instance methods
How do you access them?
Ans: By object reference

Can we access local variables or parameters by using object reference → No

Global Variables (instance variables) Vs Local Variables or parameters with same name
Whenever we declare a global variable and local variable with the same name
within a method or constructor, in that method or constructor the variable will be tread
as local variable.
class SimpleArithmetic
{
private int a , b;
public SimpleArithmetic()
{
a = 10;
b = 20; simpleobj at 2299
}
public SimpleArithmetic(int a, int b) a = 0;
{ Local b = 0;
a = a; Variables add ()
b = b;
System.out.println(a);
System.out.println(b);
}
public int add() Instance
{ Variables
return a + b;
}
public static void main (String [] args)
{
SimpleArithmetic simpleobj = new SimpleArithmetic (21,6);
System.out.println(simpleobj.add());
}
}
Output: 21 6 0

In the above program the more argument constructor is not initializing the instance
variables due to this reason Java and .NET are assigning the default values as zero for
both integers a and b (instance variables).

THIS keyword

In both Java and .NET every object will be having their own self references and
these self references are names as “this”.

➢ “This” is a keyword in both java and .NET


➢ “This” always refers the object that is currently executing in our program.
➢ Every object we create will be having its own “this” keyword (self reference)
➢ “This.var” will always be treated as instance variable

public class SimpleArithmetic


{
private int a , b;
public SimpleArithmetic()
{
a = 10;
b = 20;
}
public SimpleArithmetic(int a, int b)
{
this.a = a;
this.b = b;
System.out.println(this.a);
System.out.println(this.b);
}
public int add()
{
return a + b;
}
public static void main (String [] args)
{
SimpleArithmetic simpleobj = new SimpleArithmetic (21,6);
System.out.println(simpleobj.add());
}
}

Output: 21 6 27

Using “this ()” with constructor


Within a constructor you can use the “this ()” to call another constructor in the
same class, doing so is called ‘explicit constructor invocation’

Constructor to constructor communication:


➢ With the same class one constructor can invoke another constructor. This
concept is named as explicit constructor invocation
➢ One constructor can call another constructor within the same class by using this ()
method representation.
➢ This() must be written in the first line of a constructor, when we are calling
another constructor.

Example:
public class SimpleArithmetic
{
private int a , b;
public SimpleArithmetic()
{
this (10, 20);
}
public SimpleArithmetic(int a, int b)
{
this.a = a;
this.b = b;
System.out.println(this.a);
System.out.println(this.b);
}
public int add()
{
return a + b;
}
public static void main (String [] args)
{
SimpleArithmetic sa = new SimpleArithmetic ();
System.out.println(sa.add());
}
}
Output
10
20
30

Method Overloading:
➢ Having more than one method with the same name by differentiating based on
their parameters is called as method overloading.
➢ Method overloading can also be called as static polymorphism
➢ Method overloading can be categorized in two ways:
➢ Method can be based on the no of parameters.
void m1 ()
void m1 (char ch)
void m1 (char ch, char ch2)
Methods can be differentiated with having equal number of parameters but with
different data type.
void m1(float f1, float f2)
void m2 (float f1, int x)
void m3 (int x, char ch)
void m4 (char ch, int x)
Note: Method differentiation based on order of the parameters is a subset of method
overloading type having different based on the type of the parameter.

Reusability
The main usage of reusability is reducing the development cost and reducing the
maintenance cost.
In order to support reusability under object orientation programming
technologies two concepts are developed. Inheritance and Runtime polymorphism or
dynamic polymorphism.

Class design:
Before applying reusability After applying reusability
Class A Class B Class AB
int a, b, c, d int a, b, x, y int a, b
void m1() void m1() void m1()
void m2() void m2() void m2()
void m3() void m4()

Class A Class B
int c, d int x, y
void m3() void m4()
Object creation before/after class design change

Objects of class A
a a a
b b b
c c c
d d d
m1() m1() m1()
m2() m2() m2()
m3() m3() m3()
➢ Class design can be changed in such a way for eliminating the duplicating
information, but creating the original object as it is.
➢ The above diagram describes changes in the class design for eliminating the
duplicate information, but using any of class designs we are able to create the
object exactly the same way.
➢ In order to eliminate the duplicate information the technique says move the
common information to a common class and move the individual information to
the individual classes.

What is parent class?


The class that is having common properties is called as parent class. Parent class
can also be called as base class or super class.

What is a child class?


The class that is having individual properties and reusing the parent class is
called as child class. Child class is also called as derived class or sub class.

What is inheritance?
Inheritance is a process of creating a child object by reusing parent class
variables and methods along with child class variables and methods.

➢ Child object is collection of parent class instance variables, parent class instance
methods, child class instance variables and child class instance methods.

Parent class and child class representation diagram is known as class hierarchy diagram.
Java syntax for writing parent and child classes:
Parent class <parent class name>
{
parent class variables;
parent class constructor;
parent class methods;
}
child class <child class name> extents <parent class name>
{
child class variables;
child class constructor;
child class methods;
}
Write a java program for creating a child object and accessing parent variables, parent
methods, child variables and child methods from this child object.

//Parent.java
public class Parent
{
public int p = 1;
public void printp ()
{
System.out.println("parent value =" + p);
}
}

//child.java
public class child extends Parent
{
public int c = 2;
public void printc ()
{
System.out.println("child value =" + c);
}
}

//Test.java
public class Test
{
public static void main (String [] args)
{
child obj = new child ();
System.out.println(obj.p);
obj.printp();
System.out.println(obj.c);
obj.printc();
}
}

Compilation and Execution:


Javac parent.java
Javac child.java
Javac Test.java
Java Test
Output:
1
parent value = 1
2
child value = 2

public class SimpleArithmetic


{
private int a , b;
public SimpleArithmetic()
{
a = 10;
b = 20;
System.out.println(this.a);
System.out.println(this.b);
}
public SimpleArithmetic(int a, int b)
{
this.a = a;
this.b = b;
System.out.println(this.a);
System.out.println(this.b);
}
public int add()
{
return a + b;
}
}

public class BasicArithmetic extends SimpleArithmetic


{
private int c, d;
public BasicArithmetic(int c, int d)
{
this.c = d;
this.d = d;
System.out.println(this.c);
System.out.println(this.d);
}
public int sub()
{
return c - d;
}
public static void main (String [] args)
{
BasicArithmetic basicobj = new BasicArithmetic (200,100);
System.out.println(basicobj.add());
System.out.println(basicobj.sub());
}
}

Output:
10
20
200
100
30
100

➢ While creating the child objects the child constructor must call the parent
constructor for initializing the parent values.
➢ Child constructor should call parent constructor before executing child
constructor code
➢ If programmer didn’t write the code for calling the parent class constructor from
the child class constructor, then the compiler write the code for calling the
parent class zero argument constructor.
➢ Calling parent class constructor from the child class constructor should be first
and before execution of the child constructor code.

Runtime execution:

Step I Object creation

a basicobj
b
c
d
add()
sub()
Step II Child constructor is called but parent class constructor is initialized because child
class constructor calls parent class constructor

a = 10;
b = 20; basicobj
c
d
add()
sub()

Step III Child values are initialized

a = 10; basicobj
b = 20;
c = 200;
d = 100;
add()
sub()

Step IV
a = 10;
b = 20; basicobj
c = 200;
d = 100;
add()
sub()

What happens if we comments zero argument constructor in the class


SimpleArithemtic in the above program?
We get compilation error while compiling the class BasicArithmetic.

Invoke (calling) parent class constructor from child class constructor:

The syntax for calling a parent class constructor:


Super();
Super (parameters);
➢ Invocation of parent class constructor should be written first in the child class
constructor.
➢ With super(); the parent class no argument constructor is called.
➢ With super (parameter list) the parent class constructor with matching
parameter is called.
➢ If a child class constructor does not invoke (call) a parent class constructor, the
java compiler writes the code for calling the no-argument constructor of the
parent class using super();

Note: In the above case, if the parent class does not have no-argument constructor you
will get compile-time error.

public class SimpleArithmetic


{
private int a , b;
public SimpleArithmetic(int a, int b)
{
this.a = a;
this.b = b;
System.out.println(this.a);
System.out.println(this.b);
}
public int add()
{
return a + b;
}
}

public class BasicArithmetic extends SimpleArithmetic


{
private int c, d;
public BasicArithmetic(int c, int d)
{
super (c,d);
this.c = c;
this.d = d;
System.out.println(this.c);
System.out.println(this.d);
}
public int sub()
{
return c - d;
}
public static void main (String [] args)
{
BasicArithmetic basicobj = new BasicArithmetic (200,100);
System.out.println(basicobj.add());
System.out.println(basicobj.sub());
}
}

Output:
200
100
200
100
300
100

Run time Execution:

Step I Step II Step III


a a = 200; a = 200;
b b = 100; b = 100
c c c = 200;
d d d = 100;
add() add() add()
sub() sub() sub()

super(c,d) child constructor


parent constructor executes executes

//BasicArithmetic.java
public class BasicArithmetic extends SimpleArithmetic
{
private int c, d;
public BasicArithmetic(int a, int b, int c, int d)
{
super (a, b);
this.c = c;
this.d = d;
System.out.println(this.c);
System.out.println(this.d);
}
public int sub()
{
return c - d;
}
public static void main (String [] args)
{
BasicArithmetic basicobj = new BasicArithmetic (50, 90, 200,100);
System.out.println(basicobj.add());
System.out.println(basicobj.sub());
}
}

Output:
50
90
200
100
140
100

What can you do in a sub class?


➢ You can declare new fields in the subclass that are not in the superclass.
➢ You can declare new methods in the subclass that are not in the super class.
➢ You can write a subclass constructor that invokes the constructor of the
superclass, either implicitly or by using super()
➢ You can declare a field in the sub class with the same name as the one in the
superclass, thus hiding it (not recommended)
➢ The parent class methods can be accessed directly from the child class methods
if access modifiers are permitted.
➢ The parent class variables can be accessed directly from the child class methods
if access modifiers are permitted.
Access Modifiers
Class A
Private
Fields
Methods

Class B Class X

Package defining access

Class D Class C

Class Y

Package inherits access

Other Packages

Class A
Fields
Methods
Default
Class B Class X

Package defining access

Class D Class C

Class Y

Package inherits access

Other Packages
Class A
Protected
Fields
Methods

Class B Class X

Package defining access

Class D Class C

Class Y

Package inherits access

Other Packages

Class A
Fields
Public Methods

Class B Class X

Package defining access

Class D Class C

Class Y

Package inherits access

Other Packages
All the above diagrams are describing where the class A object can access its own
variables or methods depending on the access modifier defined for there variables and
methods.

Override
Having an instance method in a child class with the same method signature as an
instance method in the parent class, but with different functionality is called override.

public class parent


{
public void printEdu()
{
System.out.println("parent's Edu: B.Sc");
}
}

public class child extends parent


{
public void printEdu()
{
System.out.println("child's Edu: B.Tech");
}
}

public class Test


{
public static void main (String [] args)
{
child obj = new child ();
obj.printEdu();
}
}
Super keyword in Java

Using super keyword super class methods can be access from sub class.

public class parent


{
public void m1()
{
System.out.println("parent name: parent");
}
}

public class child extends parent


{
public void m1()
{
System.out.println("child name: child");
super.m1();
}
}

class Test
{
public static void main (String [] args)
{
child obj = new child();
obj.m1();
}
}

Rules from reasoning concepts:


Animals = Dogs
Parent child
Parent parent reference = new child ();
➢ A parent reference can point to parent object.
➢ A parent reference can also point to child object, this scenario is called Runtime
Polymorphism

Important point about child object.


➢ Child object is a collection of inherited methods, overridden methods and child
specific methods.

Run time Polymorphism


I II Object of child class
Parent
Inherited method () Inherited method () Parent
Overridden method () Overridden method () reference
Child specific method ()

Child III
Overridden method ()
Parent reference.overridden method();
Child Specific method ()

➢ Get any child class name at runtime


➢ Create this child object at runtime using reflection mechanism
➢ Assign this child object’s memory address to parent reference
➢ Using this parent reference access overridden methods

Abstract Class
➢ Abstract class is class that supports in writing child classes but it is not a
complete class for creating object.
➢ An abstract class is a class that is declared with key word abstract
Eg: public abstract class Animal
➢ We should not create objects for an abstract class
➢ We should write only child classes for an abstract class
➢ An abstract class may or may not include abstract method.
➢ If a class includes abstract method, the class must be declared abstract
➢ The child class should provide implementation to all of the abstract methods of
its parent class. If it dose not, the child class must also be declared abstract

Abstract Methods
An abstract method is a method
➢ That is not is not having method implementation (body)
➢ That is having only method signature (definition)
➢ That method signature should terminate with semicolon
Eg: public abstract void speak ();
We can create an object reference to the abstract class so tat it can refer to the child
object.

public abstract class Animal


{
public abstract void speak ();
}
public class Dog extends Animal
{
public void speak()
{
System.out.println("Bow..Bow..");
}
public static void main (String [] args)
{
Animal obj = new Dog();
obj.speak();
}
}

Class type Can we create object Can we create child class


Concrete Yes Yes
Abstract No Yes
Final Yes No

Packages
Physical grouping of classes and interfaces as conceptually you can think, packages are
similar to folders in computer.
To create a package you choose a name for the package
package <packagename>;
eg: package maths;

The package statement (for example, package maths;) must be the first line in the
source file.
There can be only one package in each source file.
Package names are written in all lowercase.
Companies use their reserved internet domain to begin their package name
Eg: package com. LearnSoft.maths;

Example
//SimpleArithemtic.java
package com. LearnSoft.maths;
public class SimpleArithemtic
{
private int a, b;
public SimpleArithemtic ()
{
a = 10;
b = 20;
}
public SimpleArithemtic (int a, int b)
{
this.a = a;
this.b = b;
}
public int add ()
{
return a + b;
}
}

Compilation using package


Javac –d <directory> <java class name>
-d <directory> specify where to place generated class files including the packages.
Eg: javac –d.SimpleArithemtic.java
-d . specifies the generated class files including packages to be placed in the
current directory.

//SimpleTest.java
package com. LearnSoft.maths;
public class SimpleTest
{
public static void main (String [] args)
{
com. LearnSoft.maths.SimpleArithematic simpleobj = new
com. LearnSoft.maths.SimpleArithematic ();

int sum = simpleobj.add();


System.out.println (sum);
}
}

➢ Referring a class including the package name is called fully qualified name
➢ Referring a class by excluding its package name is called simple name

➢ Import statement allows our program accessing a class without using package
name
Syntax: import <package name> . <class name>;
Eg: import comp. LearnSoft.maths.SimpleArithmetic;
➢ Once we import the class can be used without a package name in our program
thereafter
➢ Import statement can be used at the beginning of the file but after the package
statement if the package statement exists

Eg:
//SimpleTest.java
import com. LearnSoft.maths.SimpleArithematic;
pubic class SimpleTest
{
public static void main (String [] args)
{
SimpleArithematic simpleobj = new SimpleArithematic ();
int sum = simpleobj.add();
System.out.println (sum)
}
}

Importing an entire package


➢ To import all the classes and interfaces contained in a particular package, use
import statement with asterisk (*) wildcard.

Executing the class defining the package


//SimpleTest.java
package com. LearnSoft.maths;
import com. LearnSoft.maths.*;
public class SimpleTest
{
public static void main (String [] args)
{
SimpleArithematic simpleobj = new SimpleArithematic ();
int sum = simpleobj.add();
System.out.println (sum)
}
}

Execution
Java –d . SimpleArithematic.java
Java – d . SimpleTest.java
Java com. LearnSoft.maths.SimpleTest

Class Object
➢ The class object is an immediate base class by default, if your class does not
extend from any other class.
➢ The class object is defined in the java.lang package
➢ Every class you write (every object we create) inherit the instance methods of
object

Object as Super class


➢ The object class in the java.lang package sits at the top of the class hierarchy
➢ Every class is a sub class either directly or indirectly to object class
A simple class hierarchy diagram for some of the important classes defined in java.lang
package

Boolean

Character

Class

Class loader

Double
Math
Float
Number
Integer
Process
Long
Object Runtime

Security Manager

String

String Buffer

System
Thread
Thread Death

Thread Group Error java lang


Some of the object class methods

protected object clone() throws clone not supported exception created another copy of
this object and returns its reference

public boolean equals (object obj) Compares the memory address of the method’s
object reference with the memory address of object reference passing to this method
parameter. If both reference are same it returns true, otherwise it returns false.
Java is recommending all chid classes, override this method and write the code
for comparing the values. That means if the objects are similar override method should
return true otherwise, it should return false.

protected void finalize() throws throwable called by the garbage just before deleting
the object from memory

public final class get class() Returns the runtime class of the object

public int hashcode() returns the hash code value of the object

public String tostring () Return the string representation of the object having format
<class name > @ hash code value converted to hexadecimal format>
child class should override this method and return a meaningful string for this object

eg: //Data.java
public class Data
{
private int a , b;
public Data (int a, int b)
{
this.a = a;
this.b = b;
}
public void printData ()
{
System.out.println("a = " + a);
System.out.println("b = " + b);
}
public static void main (String [] args)
{
Data dataobj = new Data (100,67);
dataobj.printData();
System.out.println(dataobj.toString());
}
}

Output:
a = 100
b = 67
Data @ 3c25a5

What is super most parent class in java?


Java.lang.Object

What happens when we print object reference?


The code will be executed as object reference.toString()

//Data3.java
import java.lang .*;
public class Data3 extends Object
{
private int a , b;
public Data3(int a , int b)
{
this.a = a;
this.b = b;
}
public void printData()
{
System.out.println("a = " + a);
System.out.println("b = " + b);
}
public static void main (String [] args)
{
Data3 dataobj = new Data3 (100,67);
System.out.println (dataobj.toString());
System.out.println (dataobj.hashCode());
//printing object reference – what happens??
System.out.println(dataobj);
}
}

Output:
Data3@1034bb5
16993205
Data3@1034bb5

//Data4.java
//override toString() method
import java.lang .*;
public class Data4 extends Object
{
private int a , b;
public Data4(int a , int b)
{
this.a = a;
this.b = b;
}
public String toString()
{
return ("a = " + a + "\n" +"b = " + b);
}
public static void main (String [] args)
{
Data4 dataobj = new Data4 (100,67);
System.out.println (dataobj.toString());
System.out.println (dataobj.hashCode());
//printing object reference – what happens??
System.out.println(dataobj);
}
}

a = 100
b = 67
10542297
a = 100
b = 67
String class in java.lang package
String is a sequence of characters
Constructors:

I public String(char [] array)


char [] helloArray = {‘H’, ‘E’, ‘L’, ‘L’, ‘O’};
String helloString = new String (helloArray);
System.out.println(helloString);

II public String(String)
String helloString = new String(“hello”);
System.out.println(helloString);

III The most direct way to create a string is


String greeting = “Hello LearnSoft”;
“Hello LearnSoft” is String literal

String Literal – A series of characters in your code that is enclosed in double quotes.
➢ Whenever there is a string literal in our code, the compiler converts the string
literal into a string object at the time of compilation.

public class StringDemo


{
public static void main (String [] args)
{
String str1 = new String ("Hello");
String str2 = new String ("Hello");
if (str1 == str2)
{
System.out.println("Equal");
}
else
{
System.out.println("Not Equal");
}
}
}

Output:

Not Equal

Runtime Execution

Object of String at 2233 str1 Object of String at 3355 str2


2233 3355
Hello Hello

str1 = = str2
2233 ≠ 3355

public class StringDemo


{
public static void main (String [] args)
{
String str1 = new String ("Hello");
String str2 = new String ("Hello");
if (str1.equals(str2))
{
System.out.println("Equal");
}
else
{
System.out.println("Not Equal");
}
}
}

Output:

Equal

➢ The equals() method is defined in the String class


➢ It is a override method
➢ The equals() method compares the values in both the String Objects (but not
object reference)
➢ If the values are similar, it returns true otherwise it returns false.

public class StringDemo


{
public static void main (String [] args)
{
String str1 = "Hello";
String str2 = "Hello";
if (str1 == str2)
{
System.out.println("Equal");
}
else
{
System.out.println("Not Equal");
}
}
}
Output:

Equal
String Literal Pool
String Literal Pool
String str1 = “Hello”; String str1 = new String(“Hello”)
Hello

String str2 = “Hello”; str2 = str1

String str1 = “Hello”; String str1 = new String ();


String str2 = “Hello”; String str2 = new String ();

String Object at 2277 str1 String Object at 2277 str1


2277 2277
Hello Hello

3355
String Object at 3355 str2
str2 3355
Hello
➢ The java compiler performs some tricky while instantiating (creating object)
String Literal to increase performance and decrease memory overload.

➢ To cut down the number of String objects created, the string class keeps a pool
of strings

➢ Each time your code creates a string literal, the JVM instructions generated at
compilation checks the string literal pool first.
If the string does not exist in the pool, a new string object instantiate,
then is placed in the pool.
If the string already exists in the pool, a reference to the pool instance
returns.

➢ Java made this optimization because strings are immutable and can be shared
without fear of data corruption

// Test1.java
public class Test1
{
String str = "Hello";
}
//Test2.java
public class Test2
{
String str = "Hello";
}
public class Test
{
public static void main (String [] args)
{
Test1 obj1 = new Test1();
Test2 obj2 = new Test2();
if (obj1.str == obj2.str)
{
System.out.println("Equal");
}
else
{
System.out.println("Not Equal");
}
}
}

Output

Equal

Object of Test1 at 2222 Object of Test2 at 4444


str1 str2
3333 3333

2222 Object of String at 3333 4444


Hello
obj1 obj2

public class StringDemo


{
public static void main(String [] args)
{
Constant
String str1 = "Hel" + "lo"; Expressions
String str2 = "He" + "llo";
if (str1 == str2)
{
System.out.println("Equal");
}
else
{
System.out.println("Not Equal");
}
}
}
Output

Equal

public class StringDemo


{
public static void main(String [] args)
{ Constant Expressions
String s = "llo";
String str1 = "He" + s; Variable Expression
String str2 = "He" + "llo"; Constant Expression

if (str1 == str2)
{
System.out.println("Equal");
}
else
{
System.out.println("Not Equal");
}
}
}

Output

Not Equal

Note: Variable expression are not considered for the string literal pool

Rules of string literal pool


➢ Literal strings(likewise) with in the same class represent reference to the same
string object
➢ Literal strings(likewise) within different classes in the same package represent
reference to the same object
➢ Literal strings(likewise) within different classes in the different package
represent reference to the same object
➢ Strings computed by constant expressions are computed at compile time and
then treated as they were literals
➢ Strings computed by variable expressions are computed at run time and they are
treated as new string objects so they have different reference values

Write a program for finding the length of the given string and display a
character at the 8th index.
public class StringDemo1
{
public static void main (String [] args)
{
String str = new String("Hello LearnSoft ");
int len = str.length();
System.out.println("The length of the string = " + len);
char ch = str.charAt(8);
System.out.println("The Character at 8th index = " + ch);
}
}
Output The length of the string = 12
The Character at 8th index = o

Write a program to concat two strings


public class StringDemo2
{
public static void main (String [] args)
{
String str1 = new String ("Hello");
String str2 = new String (" LearnSoft ");
//concat 2 strings and get new string
//str1 and str2 will not be modified as they are immutable
String str3 = str1.concat (str2);
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
}
}
Output : Hello
LearnSoft
Hello LearnSoft
Write a program to display the digit by digit in the given number.

public class StringDemo3


{
public static void main (String[] args)
{
int num = 1122334455;
String str = String.valueOf(num);
int len = str.length();

for(int i = 0; i<len; i++)


{
char ch = str.charAt(i);
System.out.println(ch);
}
}
}
Output:
1
1
2
2
3
3
4
4
5
5

Verify the given string

1. If the string starts with “Learn” display the message as “Learn Soft”

2. If the string ends with “Soft” display the message as “Software”

3. If the string starts with “Learn” and ends with “Soft” display the message as
“Learn Soft from Mahendra”

public class StringDemo4


{
public static void main(String [] args)
{
String str = "leartalksoffSoft";
if (str.startsWith("Learn") && str.endsWith("Soft"))
{
System.out.println("Learn Soft from Mahendra ");
}
else if ( str.startsWith("Learn"))
{
System.out.println("New App");
}
else if (str.endsWith("Soft"))
{
System.out.println("Application");
}
else
{
System.out.println("No condition is satisfied");
}
}
}

Create a string object, if the 4th index in the string is ‘o’ then replace all the ‘o’ in the
string with ‘p’ and convert all the letters to uppercase and display the string.

public class StringDemo5


{
public static void main (String[] args)
{
String str = "Hello LearnSoft";
int a = str.indexOf('o',4);
if (a ==4)
{

String str1= str.replace('o','p');


String str2 = str1.toUpperCase();
System.out.println(str2);
}
}
}
Output:

HELLP NEPAPP

public class StringDemo5


{
public static void main (String[] args)
{
String str = "Hello LearnSoft";
char ch = str.charAt(4);
if (ch =='o')
{
String str1= str.replace('o','p');
String str2 = str1.toUpperCase();
System.out.println(str2);
}
}
}

Output:

HELLP NEPAPP

Arrays
int ➔ integer datatype
int[] ➔ integer Array

Syntax: int [] intarray = new int [5];

➢ Array is a sequence of elements of same type having fixed size


➢ Every element in the array can be accessed by using index
➢ The starting index of an array is 0 (zero)

Array variable declaration


Syntax: <datatype> [] <variable name>;
Example: int [] intarray;
char [] chararray;
String [] stringarray;

Note: Arrays are objects in java

We can create array object by using the syntax:


new<array size including the indications of its datatypes>
Example: int Array = new int [5];
String Arrray = new String [5];

Accessing an element in an array


We can access an element in an array by using its name and index together as
int Array[0]; int Array [1]; etc
int [] intArray = new int [5];
intArray[0] = 7;
intArray[1] = 10;
intArray with size 5 at memory location 2255

7 10
2255
intArray[0] intArray[4]

Size of an array intlen = intArray.lenght;


Note: Length is a built in properly (attribute) of an Array.

Array supports homogeneous elements


The name of array elements are generated internally based on the names of
array

Write a program for creating an Integer Array with size 5 and sum all the elements

public class ArrayDemo1


{
public static void main(String [] args)
{
int [] arr = new int [5];

arr[0] = 10;
arr[1] = 25;
arr[2] = 91;
arr[3] = 121;
arr[4] = 15;

int sum = 0;
for (int i = 0; i<arr.length; i++)
{
sum = sum + arr[i];
}
System.out.println("Sum of array elements = " + sum);
}
}
Output:
Sum of array elements = 262

Write a program to create an integer array with size 10 and display all the odd
numbers in that array

public class ArrayDemo2


{
public static void main(String [] args)
{
int [] arr = new int [10];

arr[0] = 10;
arr[1] = 25;
arr[2] = 91;
arr[3] = 121;
arr[4] = 15;
arr[5] = 22;
arr[6] = 23;
arr[7] = 37;
arr[8] = 55;
arr[9] = 28;

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


{
int x = arr[i] %2;
if(x ==1)
{
System.out.println("The odd numbers are = " + arr [i]);
}
}
}
}

The odd numbers are = 25


The odd numbers are = 91
The odd numbers are = 12
The odd numbers are = 15
The odd numbers are = 23
The odd numbers are = 37
The odd numbers are = 55

Array execution by shortcut notation


int [] arr; ➔ declaration
arr = new int[0] ➔ instantiation (object creation) split up
notation
arr [0] = 10; ➔ initialization

Shortcut notation includes declaration, instantiation and initialization

int [] arr = {10,15,12,25,10,36};

Write a program having int array with size 6, the elements should have values 77, 99,
220, 3, 19 and 4, use shortcut notation for creating this array. Print all the elements in
array.

public class ArrayDemo3


{
public static void main(String [] args)
{
int [] arr = {77, 99, 220, 3, 19, 4};
for (int i = 0; i < arr.length; i ++)
{
System.out.println(arr[i]);
}
}
}

Output:
77
99
220
3
19
4
Write a program with int array 15, initializing all the elements in the array according to
Fibonacci Series

public class ArrayDemo4


{
public static void main (String [] args)
{
int [] arr = new int [15];
arr [0] = 0;
System.out.println(arr[0]);
arr [1] = 1;
System.out.println(arr[1]);

for(int i = 2; i<arr.length; i++)


{
arr[i] = arr[ i-2] + arr [ i-1];
System.out.println(arr[i]);
}
}
}

Output:
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
Write a program for splitting a string based on an expression, splitting a date string
(dd-mm-yyyy) based on the expression “-“, print day, month and year.

public class StringDemo6


{
public static void main (String [] args)
{
String date = "11-05-2003";
String [] arr = date.split ("-");
System.out.println("Date = " + arr[0]);
System.out.println("Month =" + arr[1]);
System.out.println("Year = "+ arr[2]);
}
}
Output:

Date = 11
Month = 05
Year = 2003

Write a program to reverse a string

public class StringDemo7


{
public static void main(String[] args)
{
String original = "Hyderabad";
int len = original.length();
char [] arr = new char [len];
for (int i = 0; i<len; i ++)
{
arr[i] = original.charAt(len -1-i);
}
String reverse = new String(arr);
System.out.println(reverse);
}
}

Output:
dabaredyH

Substring
String class is having two methods overloading function related to substring
String substring(int start index, int end index)
- Returns a substring for start index (including) until before end index(excluding
end index)
String substring(int start index)
- Returns a substring for start index till the end of the string(including last
character of string)

Write a program to get the substring from 4th index (include) to 16th index. Another
substring from 6th index until end of the string

public class StringDemo8


{
public static void main(String[] args)
{
String str = new String ("Hello LearnSoft Technologies pvt ltd");
String str1 = str.substring (4,17);
String str2 = str.substring (6);
System.out.println(str1);
System.out.println(str2);
}
}

Output:

o LearnSoft Tech
LearnSoft Technologies pvt ltd

String filepath = "/home/LearnSoft/index.html";


Output Extension = html
Filename = index
Path = /home/LearnSoft

public class StringDemo9


{
public static void main(String[] args)
{
String filepath = "/home/LearnSoft/index.html";
int dot = filepath.lastIndexOf('.');
String Extension = filepath.substring(dot+1);
System.out.println ("Extension = " + Extension);
int hash = filepath.lastIndexOf('/');
String Filename = filepath.substring(hash+1, dot);
System.out.println ("Filename = " + Filename);
String Path = filepath.substring(0, hash);
System.out.println("Path = " + Path);
}
}

Output:

Extension = html
Filename = index
Path = /home/LearnSoft

Command Line Arguments


Main Method()

public static void main (String [] args)


Access Class Return type main String array parameter
Modifier Method is void method data type name

➢ The main method is static because JVM is accessing the main method by using its
class name
➢ This method is public so that main method can be accessible by using its class
name
➢ The method return type void indicates main method should not return any value
after the method compilation
➢ The method parameter is having a type String[] which indicates that JVM should
pass a String[] as an argument to this method at time of calling this method

How do JVM gets this String[] object?


➢ JVM should get the strings from the command prompt at the time of executing
the java program
➢ The size of the String[] should be based on the number of strings we are
supplying at the time off executing the program

Example: java Test Hello LearnSoft

In this example the size of the String[] is 2

Example: java Test Hello LearnSoft World

In this example the size of the String[] is 3

➢ The size of the String[] would be 0 (Zero) if you are not passing any strings and
JVM sends a null value to the main method at the time of execution

public class StringDemo


{
public static void main(String[] args)
{
//this program requires two arguments on the command line
if(args.length ==2)
{
String concatstring = args [0].concat(args[1]);
System.out.println(concatstring);
}
else
{
System.out.println("This program requires two command line
arguments");
}
}
}

javac StringDemo.java
java StringDemo Hello LearnSoft

Output:

HelloLearnSoft

String Builder
➢ String Builder is a mutable sequence of characters

➢ String Builder objects are like String Objects, except that they can be modified

➢ At any point, the length and content of the sequence can be changed through
method invocation

➢ This class provides an API compatible with String Buffer with no guarantee of
synchronization

Constructors

public String Builder ()


constructs a String Builder with no characters in it and an initial capacity of 16
characters

Example: StringBuilder sb = new StrinngBuilder(); //creates empty builder, capacity 16


sb.append(“Greetings”) // add 9 characters string at beginning

This object produces a string builder with a length of 9 and a capacity of 16

G r e e t i n g s

Length = 9 Capacity = 16

StringBuilder (int capacity)


Constructs a string builder with no characters in it and an initial capacity
specified by the capacity argument

StringBuilder(String str)
Constructs a string builder initialized to content of the specified string
The initial capacity of the string builder is 16 plus the length of the string
argument

public class StringBuilderDemo


{
public static void main (String [] args)
{
StringBuilder sb = new StringBuilder ("Hello");
StringBuilder tempsb = sb.append("LearnSoft");
System.out.println(sb.toString());
System.out.println(tempsb.toString());
if (sb ==tempsb)
{
System.out.println("Having same references");
}
else
{
System.out.println("Having different references");
}
}
}

object of StringBuilder at 2233 object of StringBuilder at 2233


sb sb
2233 Hello 2233append(LearnSoft) Hello
sb
2233 object of StringBuilder at 2233
append(LearnSoft)
Hello
tempsb LearnSoft
2233

Output: Hello LearnSoft


Hello LearnSoft
Having same references

Write a program to reverse a string

public class StringBuilderDemo


{
public static void main (String[] args)
{
String original = "Hyderabad";
StringBuilder sb = new StringBuilder(original);
sb.reverse();
System.out.println(sb);
}
}

Output: dabaredyH

Wrapper Classes
➢ The meaning of wrap is enclose or bind or cover or envelope
➢ Java platform provides wrapper classes for each of the primitive data type
➢ These classes wrap the primitive in an object

Wrapper classes are immutable and are in java.lang package


Wrapper classes
Byte Short Integer Double Float
Long Character String Boolean

All numeric wrapper classes are derived from the instance class Number in java.lang
package

Number

Byte Double Float


Integer Short

Wrapper Class Integer

Integer is a final class

Constructors
Integer (int value) – constructs a new Integer object with int value
Integer (String s) – constructs a new Integer object with String representation of int
value

Converting a String representation of Integer to int


public static int parseInt(String s)
Eg: int empId = Integer.parseInt(“6211”)

To get int primitive value


int intValue()

Wrapper Class Double


Double is a final class

Constructors
Double (double value) – constructs a new Double object with double value
Double (String s) – constructs a new Double object with String representation of double
value
Converting a String representation of Double to double
public static int parseDouble(String s)
Eg: double amount = Double.parseDoubld(“123.52”)

To get double primitive value


double doubleValue()
public class ArithmeticDemo
{
public static void main(String[] args)
{
//this program requires two arguments (String representation of Integers)
on command line
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);

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


System.out.println("sub = " + (a-b));
System.out.println("mul = " + (a*b));
System.out.println("div = " + (a/b));
System.out.println("remainder = " + (a%b));
}
}
javac ArithmeticDemo.java
java ArithmeticDemo 5 2

Output:
sum = 7
sub = 3
mul = 10
div = 2
remainder = 1
Boxing and Unboxing

Boxing
Integer iobj = 12;

Wrapper Class
Primitive Object

int i = iobj
Unboxing
➢ If we treat any wrapper class object like a box, assigning its primitive value into
that object is called as boxing

➢ Getting the value from this object is called as unboxing

➢ Boxing and Unboxing system looks like the operations we are performing on the
primitive variables

Example: Integer Xobj, Yobj

Xobj = 12;
Boxing
Yobj = 15;

At the time of compilation java compiler converts this code


Xobj = new Integer(12);
Yobj = new Integer(15);

Example: int i1 = Xobj; Unboxing


int i2 = Yobj;

At the time of compilation java compiler converts the code


int i1 = Xobj.intValue();
int i2 = Yobj.intValue();

//BoxUnboxDemo.java
public class BoxUnboxDemo
{
public static void main(String[] args)
{
Integer obj1 = 10;
//Integer obj1 = new Integer(10);
Integer obj2 = 15;
//Integer obj2 = new Integer(15);
int sum = obj1 + obj2;
//int sum = obj1.intValue() + obj2.intValue();
System.out.println(sum);
}
}
Exceptional Handling

Write a program that gets an exception


public class ExceptionTest
{
public static void main(String [] args)
{
String str = new String ("Hello");
System.out.println(str.charAt(0));
System.out.println(str.charAt(1));
System.out.println(str.charAt(2));
System.out.println(str.charAt(3));
System.out.println(str.charAt(4));
System.out.println(str.charAt(5));

System.out.println("End of program");
}
}

Output:
H
e
l
l
o
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index
out of range: 5
at java.lang.String.charAt(String.java:658)
at ExceptionTest.main(ExceptionTest.java:11)

Exceptions
➢ An exception is an event, which occurs during the execution of a program that
disrupts the normal flow of the program’s instruction.
➢ The term exception is shorthand for the phrase “Exceptional Event”

Exception Object
➢ When an exception occurs with in a method, the method creates an object. This
object is called exception object
➢ Now the method hands over the object to the runtime system(JVM) (by using
throw)
➢ Now the runtime system(JVM) looks for the right exception handling mechanism
(catch block) that is matching to this exception object
- if handling mechanism is not defined for this object, our program will be
crashed.

Exception object contains information about


➢ The error type
➢ Error message
➢ The location of the program where the error occurred
Error Type

Exception in thread "main" java.lang.StringIndexOutOfBoundsException:


String index out of range: 5-------> Error Message
at java.lang.String.charAt(String.java:658)
at ExceptionTest.main(ExceptionTest.java:11)
Error location in the program
Exceptional Handler
➢ The method that contains a block of code that can handle the exception is called
an exceptional handler
➢ Exception handling can be provided using the three exception handling
components
try
catch
finally

Try Block
The first step in constructing an exceptional handling is: To enclose the code that might
get an exception within a try block
Syntax:
try
{
//here is the try block code (main solution)
}
catch and/or finally block

Catch Block
Catch block is an exception handler and handles that exception raised by the try block
One or more catch blocks will be provided immediately after the try block.
Syntax:
try
{
//here is the try block code (main solution)
}
catch (Exception Type-1 name)
{
// here is the first catch block code (first alternate solution)
}
catch (Exception Type -n name)
{
// here is the nth catch block code (nth alternate solution)
}
I charAt () method exception creation in case of failure
StringIndexOutOfBoundsException e = new StringIndexOutOfBoundsException
(“String Index out of range: 5”)

II throw e;
handover to JVM

JVM
III JVM finds the right catch block

IV exception = e;

Modify the previous program for handling the exception


public class ExceptionTest
{
public static void main(String [] args)
{
String str = new String ("Hello");
try
{
System.out.println(str.charAt(0));
System.out.println(str.charAt(1));
System.out.println(str.charAt(2));
System.out.println(str.charAt(3));
System.out.println(str.charAt(4));
System.out.println(str.charAt(5));
}
catch (StringIndexOutOfBoundsException exception)
{
System.out.println( exception.getMessage());
}
System.out.println("End of program");
}
}
Output:
H
e
l
l
o
String index out of range: 5 ➔ this message is from catch block
End of program

Finally Block
The finally block always executes when the try block exist irrespective of the exception
occurs or not
This is the best place for writing the cleanup code like closing a file, closing database
connections or network connections etc.

Finally block execution scenarios – 1


try
{
//try code ➔ execution dose not occur
}
catch (Exception e)
{
// catch code ➔ catch code dose not execute
}
finally
{
// finally code ➔ finally code executes after completing try code
}

Finally block execution scenarios – 2


try
{
//try code ➔ execution occured
}
catch (Exception e)
{
// catch code ➔ catch code executed after exception
}
finally
{
// finally code ➔ finally code executes after completing catch code
}

Finally block execution scenarios – 3


try
{
//try code ➔exception occurred no suitable catch exception program is
getting executed
}
catch (Exception e)
{
// catch code ➔ catch code dose not execute
}
finally
{
// finally code ➔ finally code executes just before crashing of program
}

Finally block execution scenarios – 4


try
{
//try code ➔ exception occurred
}
catch (Exception e)
{
// catch code ➔ catch code executes after exception and it has return stmt
}
finally
{
// finally code ➔ finally code executes before return statement in catch
block
}

Write a program for demonstrating finally block and prove finally will be executed
always

public class ExceptionalHandlingDemo


{
public static void main(String [] args)
{
String str = new String ("Hello");
try
{
System.out.println(str.charAt(0));
System.out.println(str.charAt(1));
System.out.println(str.charAt(2));
System.out.println(str.charAt(3));
System.out.println(str.charAt(4));
System.out.println(str.charAt(5));
}
catch (StringIndexOutOfBoundsException exception)
{
System.out.println( exception.getMessage());
}
finally
{
System.out.println("End of program");
}
}
}

Output:
H
e
l
l
o
String index out of range: 5
End of program

Throwable class and its subclasses

Object

Throwable

Error Exception

IO Error VirtualMachineError IO Exception SQLException RuntimeException

IndexOutOfBoundsException NullPointerException

ArrayIndexOutOfBoudsException StringIndexOutOfBoundsException

Categories of exception

There are three different categories of the exceptions

1. Error 2.Checked Exception 3.Unchecked Exception


Error
➢ Our program may get error mainly due to the issues that exists outside our
program
➢ Errors are the subclasses of java.lang.Error
➢ Our program may get errors due to the non availability of the memory in the
heap or stack etc

Checked Exception

➢ Our program may get checked exceptions mainly due to issues inside our
program

➢ These are called checked exceptions because the possibility of getting the
exceptions at our program can be verified by the compiler at the time of
compiling the program
➢ These are the sub classes of java.lang.Exception extends from
java.lang.RuntimeException and its sub classes

Unchecked Exceptions

➢ Our program may get unchecked exceptions mainly due to issues inside our
program
➢ These are called unchecked exceptions because the possibility of getting the
exceptions at our program cannot be verified by the compiler at the time of
compiling our program
➢ These are the sub classes of java.lang.RuntimeException and its sub classes

What is the parent class for all exceptions in java?


java.lang.Throwable

Exceptional Handling 2nd Approach

➢ If a method dose not want to handle the exceptions that can occur within it,
then the method must specify that it can throw these exception to its calling
method
➢ To specify that a method can throw these exceptions, add a throws clause to the
method declaration
➢ The throws clause comprises the throws keyword followed by a comma-
separated list of all the exceptions thrown by that method
The clause goes after the method name and arguments list
Eg: public void m1() throws IndexOutOfBoundsException
Understanding throws in detail
public void m1() throws XYZException
{
…..
….. Called Method
…..
}
public void m2()
{
….
m1() Calling Method
….
}

➢ throws works if an only if there is an exception in the called method


➢ Whenever there is an exception in the called method, throws will handover this
exception object to calling method
➢ Any unchecked exception will throws to calling method automatically. Writing
unchecked exception in throws caluse is optional

throws statement
A programmer’s code can raise an exception and handovers the object to runtime
system by using throw
Syntax: throw SomeThrowableObject
Eg: throw new NullPointerException();

What is the difference between Throwable, throws and throw


Throwable: It is the base class for all exceptions in java
throws : It is a way of handling an exception by a called method and
handover(throws) the exception to the calling method
throw: It is a way of raising an exception from a method programmatically and
handover (throw) the exception object to runtime system
Q Which of the following is not a keyword?
Throwable
throws
throw
Ans: Throwable

Generalized catch mechanism


try
{
//try solution may get different types of exceptions
}
catch (Exception e)
{
//this catch solution handles any type of Exception and its child classes
//comes under java.lang.Exception
//this mechanism demonstrates runtime polymorphism
}

Genralized catch with specific catch


try
{
//try solution
}
catch (Exception Type-1 e1)
{
//assume Exception Type-1 is child class of Exception
//this catch solution handles any Type-1 of Exception
}
catch (Exception Type-2 e2)
{
//assume Exception Type-2 is child class of Exception
//this catch solution handles any Type-2 of Exception
}
{
//this catch solution handles any type of Exception except Expt Type-1 & Expt Type-2
//comes under java.lang.Exception
//this mechanism demonstrates runtime polymorphism
}

public class Test


{
public static void main (String [] args)
{
String str = null;
try
{
System.out.println(str.charAt(0));
}
catch(Exception exception)
{
System.out.println("Exception");
}
catch(StringIndexOutOfBoundsException exception)
{
System.out.println("StringIndexOutOfBoundsException");
}
catch(NullPointerException exception)
{
System.out.println("NullPointerException");
}
}
}

Output:

Test.java:14: error: exception StringIndexOutOfBoundsException has already been


caught
catch(StringIndexOutOfBoundsException exception)
^
Test.java:18: error: exception NullPointerException has already been caught
catch(NullPointerException exception)
^
2 errors

Note: 2 compilation errors because the last 2 catch blocks will never be executed
public class Test
{
public static void main (String [] args)
{
String str = null;
try
{
System.out.println(str.charAt(0));
}
catch(StringIndexOutOfBoundsException exception)
{
System.out.println("StringIndexOutOfBoundsException");
}
catch(NullPointerException exception)
{
System.out.println("NullPointerException");
}
catch(Exception exception)
{
System.out.println("Exception");
}
}
}

Output:
NullPointerException

The generalized catch block should always be written at the last of the catch blocks
chain

Nested try catch


try
{
….. ➔ Outer try
try
{
// nested try ➔ nested try
}
catch(Exception en)
{
// nested catch ➔ nested catch
}
……
catch (Exception e)
{
//outer catch ➔ outer catch
}

Userdefined exceptions

This concept is used for defining our own exception classes and then, use these
exception classes in our program for handling negative scenarios

main()
{
…..
m1()
…..
}
void m1 () throws SIOBE invoke
{ m1() m2()
….. returns result
str.charAt(3); or
….. throws exception
}
charAt() throws SIOBE
{
SIOBE siobe = new SIOBE();
throw siobe;
}

Case study:
Test Bank
invoke
main() withdraw()

withdraw (or)
throws InsufficientFundsException

Step by step procedure for doing user defined exception handling mechanism
1. Write an user defined exception class by extending our exception class from
java.lang.Exception
Eg: InsufficientFundsException.java

2. The constructor of this user defined exception should always invoke its parent
class constructor [by using super(String)] for passing exception message (so that
parent class constructor gets the message in exception object)
Eg: InsufficientFundsException(String msg)
super(msg)
Note: The parent class constructor is setting this exception message in the exception
object

//InsufficientFundsException.java
public class InsufficientFundsException extends Exception
{
public InsufficientFundsException()
{
super("Sufficient balance is not available in the account");
}
public InsufficientFundsException(String msg)
{
super(msg);
}
}

3. Write a called method for creating an user defined exception object, raising
(throw) the exception object and throwing (throws) the exception object during
the negative scenarios
Eg: withdraw() method in Bank.java
Public void withdraw(float amount) throws InsufficientFundsException

//Bank.java
public class Bank
{
private float balance;
public Bank()
{
balance = 5000.0f;
}
public void withdraw (float amount) throws InsufficientFundsException
{
if (balance < amount)
{
InsufficientFundsException e = new InsufficientFundsException(
"cannot withdraw, only Rs" + balance+ "is available in account");
throw e;
}
else
{
balance = balance - amount;
System.out.println(amount + " withdrawn from your account");
System.out.println("your balance amount =" + balance);
}
}
}

4. Write a calling method for providing user defined exception handling by using
try/catch in case of negative scenarios
Eg: main() method in Test.java

//Test.java
public class Test
{
public static void main(String [] args)
{
Bank obj = new Bank();
try
{
obj.withdraw(4000.0f);
obj.withdraw(2000.0f);
}
catch(InsufficientFundsException e)
{
System.out.println(e.getMessage());
}
}
}
Output:
4000.0 withdrawn from your account
your balance amount =1000.0
cannot withdraw, only Rs1000.0is available in account
Collections
An example of a project without using collections

Middleware

2
Processing Request
UI Database
5
Processing Results
3
1

6
4

In this approach every request from the User Interface UI is interacting with database
through the middleware
Accessing the data from the database and processing its results may consume extra
time and it affects the performance of the software.
This problem can be solved by changing the model of the project by using the concept
collections as shown in the diagram below.

Middleware
Collections
1
8 Object

Database
UI 7 4
5 2
Processing Processing
Results Request
6 3

As shown in this diagram the important data that is required for the clients is pre-
processed and converted into objects and kept all the in the memory are called
collections. At later point of time we can access these objects from the collections so
that accessing time can be saved.

➢ Collections are simply an object that groups multiple elements in single unit.
➢ Collections is called as container
➢ Collection are use to create, retrieve etc (manipulate) and communicate
aggregate data.
Java Collections Framework

A collections framework is unified architecture of representing and manipulating objects


in the collections.

Java Collections Framework contains.

➢ Interface
➢ Implementation
➢ Algorithms

Core Collection Interfaces

These are the foundation of the java collections framework

Collections Map

Set List Queue Sortedmap

Sortedset

Collections is the root of collection hierarchy

Some types of collections


➢ Allow duplicate elements and others do not.
➢ Are ordered and others are unordered

Set:
Set is a collection that cannot contain duplicate elements
It is like a mathematical set representation (unordered collection of elements)
List:
List is an ordered collection (sometimes called a sequence)
Lists can contain duplicate elements
The elements in the list can be accessed by using index
Queue:
Queue is a collection used to hold multiple elements prior to processing
Note: If the rate of processing time is slower than that of rate of arrival queues
are used
Queues are ordered elements (but do not necessarily) in First In First Out (FIFO)

Map: Map is an object that maps keys to values


A map cannot contain duplicate keys
Implementation classes for List

ArrayList:
Provides best performance if we add or remove elements from the end
We can get values from anywhere from the ArrayList based on Index

LinkedList:
This is implemented based on double LinkedList (traverse in both directions)
Provides best performance when we insert the elements in between the list

Vector:
Same as ArrayList but synchronized (take care of multithread issues)

Implementation classes for Set

HashSet:
Implemented set Interface (elements can be anywhere)

TreeSet:
Implemented SortedSet Interface (elements should be sorted)

Implementation classes for Map

HashMap:
Implemented Map Interface
Provides best performance in Map for inserting, deleting and locating the
element

TreeMap:
Implemented SortedMap Interface and Keys are sorted in ascending order
Provides best pefromance for sorting the keys in order

HashTable:
Same as HashMap but synchronized(support multithreading)
Implementation classes for Queue

LinkedList:
Implemented both List and Queue

PriorityQueue:
Doesn’t allow null elements

All collection Interface and their implementation class are defined in a package called
java.util

Methods in Interface Collection

Basic Operators
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(Object element) // optional
boolean remove(Object element) // optional
Iterator iterator ();

Bulk Operations
boolean containsAll(collection c);
boolean addAll(collection c) optional
boolean removeAll(collection c) optional
boolean retailnAll(collection c) optional
void clear() optional

Array Operations
Object [] toArray();

Difference between Array and Collection


➢ Array size is fixed, we cannot add more elements into any array – The size of the
collection will be growing dynamically by adding more elements

➢ Array supports single type of data(Homogeneous) – Any data can be added into
the collection (Heterogeneous)
➢ We should write standard algorithms for searching the data in array – Standard
algorithms are already written by java team for data searching in collection

➢ Array supports organizing the data only based on Index (list based) – collections
support organizing the data in different types like List based, Set based, Queue
based, Map based etc.

Unsupported Operation Exception

If implementation classed does not support optional methods in the collection,


accessing that method will throw the execution
java.lang.UnsupportedOperationException

Understanding add(Object c) internal functionality

Collection c = new ArrayList();

Object of String (String str = new String(“Hello”) at mem location 1111


Hello

Collection c = new ArrayList();

c.add(str)

Collection c = new ArrayList();

1111
Object of String (String str = new String(“Hello”) at mem location 1111
Hello

List Interface methods

boolean add(Object element)


- Appends the specified element to the end of this list
void add(int Index, Object element)
- Inserts the specified element at the specified position in the list
boolean contains(Object o)
- Returns the element at the specified element in the list
int indexOf(Object o)
- Returns the index of the first occurrence of the specified element in this list, or
-1 if the list does not contain the element
object remove(int Index)
- Removes the element at the specified position in this list
boolean remove(object o)
- Removes the first occurrence of the specified element from this list
object set(int index, object element)
- Replace the element at the specified position in this list with the specified
element
int size()
- Returns the number of elements in this list

//ListDemo1.java
import java.util.*;
public class ListDemo1
{
public static void main(String [] args)
{
List list = new ArrayList();

list.add("raj");
list.add("Elizabeth");
list.add("lalli");
list.add("Elizabeth");
list.add("Rock");

System.out.println(list);
System.out.println("2:" + list.get(2));
System.out.println("0:" + list.get(0));
}
}

Output:

[raj, Elizabeth, lalli, Elizabeth, Rock]


2:lalli
0:raj

//ListDemo2.java
import java.util.*;
public class ListDemo2
{
public static void main(String [] args)
{
List list = new ArrayList();
list.add("Venky");
list.add("Pinky");
list.add("Bittu");

System.out.println(list);
System.out.println(list.size());

list.add(1,"Sunny");
System.out.println(list);
System.out.println(list.size());

list.set(0,"Rock");
System.out.println(list);
System.out.println(list.size());

list.remove(3);
System.out.println(list);
System.out.println(list.size());

System.out.println(list.indexOf("Pinky"));
System.out.println(list.contains("Sunny"));
System.out.println(list.contains("pratap"));
}
}

Output

[Venky, Pinky, Bittu]


3
[Venky, Sunny, Pinky, Bittu]
4
[Rock, Sunny, Pinky, Bittu]
4
[Rock, Sunny, Pinky]
3
2
true
false

Set () Methods

boolean add(Object element)


- Add the specified element to the this set if it is not already present
boolean contains(Object o)
- Returns true of this set contains the specified element
Iterate iterate(Object o)
- Returns an iterator over the elements in this set
boolean remove(object o)
- Removes the specified element from this set if it is present
int size()
- Returns the number of elements in this set

//SetDemo1.java
import java.util.*;
public class SetDemo1
{
public static void main(String [] args)
{
Set set = new HashSet();

set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");

System.out.println(set);
System.out.println(set.size());
}
}

Output:

[Five, Three, One, Four, Two]


5

– Random
//SetDemo2.java
import java.util.*;
public class SetDemo2
{
public static void main(String [] args)
{
Set set = new TreeSet();

set.add("Three");
set.add("Two");
set.add("Four");
set.add("One");
set.add("Five");

System.out.println(set);
}
}

Output:

[Five, Four, One, Three, Two]

Interface Iterator methods

boolean hasNext();
- Returns true, if there is a next element
Object next();
- Returns the element and then moves the iterator to next element
void remove(); optional

Collection with iterator design diagram

Iterator it

obj ref 1111

Collection collection

Object of String (String str = new String(“Hello”) at mem location 1111


Hello

We can get iterator reference in our program by using collection method as


Iterator it = collection.Iterator();
Object o = it.next();

Iterator it

obj ref 1111

Collection collection

Object of String (String str = new String(“Hello”) at mem location 1111


Hello

The next method in the Iterator returns the current obj ref to our program and then
moves the Iterator to the next object

Using Iterator with for loop

Initialization Condition

for(Iterator it = collection.Iterator; it.hasNext();)


{
System.out.println(it.Next());
}

Using Iterator with while loop

Iterator it = collection.Iterator();
while(it.hasNext())
{
System.out.println(it.Next());
}

//SetDemo3.java
import java.util.*;
public class SetDemo3
{
public static void main(String [] args)
{
Set set = new HashSet(); Runtime Polymorphism (parent obj ref
pointing to child obj)
set.add("Learn"); Object obj = it.next()
set.add("Soft"); 2233
set.add("Technologies");
Hello String @ 2233

System.out.println(set);
Iterator it = set.iterator(); String element = (String) obj
2233
while(it.hasNext())
{
String element = (String) it.next();
System.out.println(element.toUpperCase());
}
}
}

Output:

[soft, Technologies, Learn]


SOFT
TECHNOLOGIES
Mahendra

Traversing Collections

There are 2 ways to traverse collections

➢ By using for-each loop


➢ By using Iterator

for-each loop

The for-each was introduced tactfully to avoid introduction of any initialization variable
Introduced in J2SE1.5 onwards
You would read:
for(String msg: messages)
“for each string msg in messages”
Note: messages is a String[]
//SetDemo4.java
import java.util.*;
public class SetDemo4
{
public static void main(String [] args)
{
Set set = new HashSet();
set.add("Learn");
set.add("Soft");
set.add("Technologies");

System.out.println(set);
for (Object obj : set)
{
String element = (String) obj;
System.out.println(element.toUpperCase());
}
}
}

Output:

[Soft, Technologies, Learn]


Soft
TECHNOLOGIES
Learn

Queue Methods

Throws Exception Return special value


in –ve scenarios in –ve scenarios
Insert Boolean add(e) Boolean offer(e) Adding the element in the end
of the Queue
Remove object remove() object poll Removes the first element
from the Queue
Examine object element() object peak() Gets the first element from
the queue but dose not
remove
//QueueDemo1.java
import java.util.*;
public class QueueDemo1
{
public static void main (String [] args)
{
Queue queue = new LinkedList();

queue.add("Frist");
queue.add("Second");
queue.add("Third");
queue.add("Fourth");

System.out.println(queue);
System.out.println("The current size of Queue" + queue.size());
System.out.println("Removed" + queue.remove());
System.out.println(queue);
System.out.println("The current size of Queue" + queue.size());
System.out.println("Removed" + queue.poll());
System.out.println(queue);
System.out.println("The current size of the Queue" + queue.size());
}
}

Output:

[Frist, Second, Third, Fourth]


The current size of Queue4
RemovedFrist
[Second, Third, Fourth]
The current size of Queue3
RemovedSecond
[Third, Fourth]
The current size of the Queue2
//Demonstrates the conditions
//QueueDemo2.java
import java.util.*;
public class QueueDemo2
{
public static void main (String [] args)
{
Queue queue = new PriorityQueue();
System.out.println("Remove" + queue.poll());
System.out.println("Remove" + queue.remove());
System.out.println("End of program");
}
}

Output:

Removenull
Exception in thread "main" java.util.NoSuchElementException
at java.util.AbstractQueue.remove(AbstractQueue.java:117)
at QueueDemo2.main(QueueDemo2.java:9)

//LinkedListDemo.java
import java.util.*;
public class LinkedListDemo
{
public static void main (String [] args)
{
LinkedList linkedList = new LinkedList();
linkedList.addFirst ("Raj"); //Queue interface method
linkedList.addFirst ("Elizabeth");
linkedList.addFirst ("Lalli");
linkedList.addFirst ("Elizabeth");
linkedList.addFirst ("Rock");
System.out.println(linkedList);

linkedList.removeLast(); // Queue interface method


linkedList.removeLast();
System.out.println(linkedList);
}
}

Output:

[Rock, Elizabeth, Lalli, Elizabeth, Raj]


[Rock, Elizabeth, Lalli]

MAP

Object
Object

Map Methods

Object get(object key) – returns the value as object for the specified key as object
Object put(object, object value) – Storing the key and value objects into the map.
Returns the reference value
Set keySet() – returns all the keys in this map as set object
Object remove (object key) – Removes the value mapped to the specified key Returns
the reference of the value
int size() – returns the size of key value in the map
get () – returns the null value if the given key is not available in the map

//MapDemo1.java
import java.util.*;
public class MapDemo1
{
public static void main (String [] args)
{
Map map = new HashMap();

map.put("1001", "Rakesh");
map.put("1002" , "Ramesh");
map.put("1003" , "Mallesh");
map.put("1004" , "Mukesh");

System.out.println(map);
String name = (String) map.get("1004");
System.out.println(name);
System.out.println(map.get("1007"));
}
}
Output:
{1003=Mallesh, 1004=Mukesh, 1001=Rakesh, 1002=Ramesh}
Mukesh
null
//MapDemo2.java
import java.util.*;
public class MapDemo2
{
public static void main (String [] args)
{
Map map = new HashMap ();
map.put("1001" , "Rakesh");
map.put("1002" , "Ramesh");
System.out.println(map);
//overrides the previous value
map.put("1001" , "Mallesh");
System.out.println(map);
}
}

Output:
{1001=Rakesh, 1002=Ramesh}
{1001=Mallesh, 1002=Ramesh}

You might also like