Professional Documents
Culture Documents
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
What is software?
Set of programs that generate instructions to the machine for doing/completing one or
more activities of a business automatically.
Activity Activity
Data
Activity Activity
JVM Architecture
JVM Environment
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
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
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
When a new thread is launched, the JVM executes a new java stack from the thread
What is an object?
➢ Any physical representation is called object
➢ Any object in this world occupies space
Software objects will be used by the machine for doing different activities. This process
is called automated process.
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 data?
The value stored in a variable is called data.
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
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.
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
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
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;
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
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.
x= x+1 y=x
y= x x = x+1
11 11
11 10
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)
if (condition 1 || condition 2)
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
Example
Add
Parameters Number 1 Sum = num 1
+ num 2 Sum
Input Number 2 (return value output)
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
}
By applying design meaning of a class, the above program can be divided into the
following classes.
}
Fundamental principal – 1
Encapsulation
Achieving data abstraction (hiding the variables)
How?
➢ By combining similar variables and methods together
➢ Using access modifiers.
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.
class SimpleArithmetic
{ Variable
int a, b; declaration
simplearithmetic ( )
{ Constructor
a = 10; declaration
b = 20;
}
int add ( )
{ Method
return a + b; declaration
}
}
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);
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.
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
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);
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;
}
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
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
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
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 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.
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.
A
A
Same dir diff dir
B
B
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.
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)
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
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
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”.
Output: 21 6 27
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 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();
}
}
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:
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()
a = 10; basicobj
b = 20;
c = 200;
d = 100;
add()
sub()
Step IV
a = 10;
b = 20; basicobj
c = 200;
d = 100;
add()
sub()
Note: In the above case, if the parent class does not have no-argument constructor you
will get compile-time error.
Output:
200
100
200
100
300
100
//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
Class B Class X
Class D Class C
Class Y
Other Packages
Class A
Fields
Methods
Default
Class B Class X
Class D Class C
Class Y
Other Packages
Class A
Protected
Fields
Methods
Class B Class X
Class D Class C
Class Y
Other Packages
Class A
Fields
Public Methods
Class B Class X
Class D Class C
Class Y
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.
Using super keyword super class methods can be access from sub class.
class Test
{
public static void main (String [] args)
{
child obj = new child();
obj.m1();
}
}
Child III
Overridden method ()
Parent reference.overridden method();
Child Specific method ()
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.
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;
}
}
//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 ();
➢ 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)
}
}
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
Boolean
Character
Class
Class loader
Double
Math
Float
Number
Integer
Process
Long
Object Runtime
Security Manager
String
String Buffer
System
Thread
Thread Death
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
//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:
II public String(String)
String helloString = new String(“hello”);
System.out.println(helloString);
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.
Output:
Not Equal
Runtime Execution
str1 = = str2
2233 ≠ 3355
Output:
Equal
Equal
String Literal Pool
String Literal Pool
String str1 = “Hello”; String str1 = new String(“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
Equal
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
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
1. If the string starts with “Learn” display the message as “Learn Soft”
3. If the string starts with “Learn” and ends with “Soft” display the message as
“Learn Soft from Mahendra”
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.
HELLP NEPAPP
Output:
HELLP NEPAPP
Arrays
int ➔ integer datatype
int[] ➔ integer Array
7 10
2255
intArray[0] intArray[4]
Write a program for creating an Integer Array with size 5 and sum all the elements
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
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;
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.
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
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.
Date = 11
Month = 05
Year = 2003
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
Output:
o LearnSoft Tech
LearnSoft Technologies pvt ltd
Output:
Extension = html
Filename = index
Path = /home/LearnSoft
➢ 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
➢ 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
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
G r e e t i n g s
Length = 9 Capacity = 16
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
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
All numeric wrapper classes are derived from the instance class Number in java.lang
package
Number
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
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”)
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
➢ Boxing and Unboxing system looks like the operations we are performing on the
primitive variables
Xobj = 12;
Boxing
Yobj = 15;
//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
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.
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;
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.
Write a program for demonstrating finally block and prove finally will be executed
always
Output:
H
e
l
l
o
String index out of range: 5
End of program
Object
Throwable
Error Exception
IndexOutOfBoundsException NullPointerException
ArrayIndexOutOfBoudsException StringIndexOutOfBoundsException
Categories of exception
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
➢ 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 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();
Output:
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
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
➢ Interface
➢ Implementation
➢ Algorithms
Collections Map
Sortedset
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)
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)
HashSet:
Implemented set Interface (elements can be anywhere)
TreeSet:
Implemented SortedSet Interface (elements should be sorted)
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
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();
➢ 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.
c.add(str)
1111
Object of String (String str = new String(“Hello”) at mem location 1111
Hello
//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:
//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
Set () Methods
//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:
– 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:
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
Iterator it
Collection collection
Iterator it
Collection collection
The next method in the Iterator returns the current obj ref to our program and then
moves the Iterator to the next object
Initialization Condition
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:
Traversing Collections
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:
Queue Methods
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:
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);
Output:
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}