SlideShare a Scribd company logo
1 of 234
1
Introduction to Java
Presented by
Amit Srivastava
Java Duke
Java 6
Mustang
Java is one of the slang terms for coffee
Java 7
Dolphin
2
Agenda
1. Java Introduction
2. Java Basics
3. Object Oriented Basics (OO Basics)
4. Using Constructor and Finalize
5. IS-A and HAS-A
6. Polymorphism, Abstract class and interfaces
7. Pass By Value & Pass By Reference
8. All About Static
9. Deep Inside JVM
10. OOAD
3
Java Introduction
 What is Java
 Java History
 WORA
 Java Kick Start
 The way Java Works
 Writing First Java Program
4
The Power of Java
Java software powers the onboard computers in toys, cars, planes, rockets, and
even the NASA (National Aeronautics and Space Administration/Agency )
Mars Rover. It brings interactivity to the Internet, real-time graphics to television,
instant imaging to cameras, and multi-player games to mobile phones and
desktop PCs. It connects the largest enterprises and smallest businesses to
their employees, customers, and data. And it secures the vast majority of
electronic transactions in retail, finance, government, science, and medicine. In
short, Java technology goes everywhere you go
5
A Mars rover is an automated
motor vehicle which propels itself
across the surface of the planet
Mars after landing.
Rovers have several advantages
over stationary landers: they
examine more territory, they can
be directed to interesting features,
they can place themselves in
sunny positions to weather winter
months.
6
Java software runs on more types of consumer and embedded devices, smart
cards, ATMs, thin clients, PCs, servers, and mainframes than any other
software.
Today's six million Java developers are one of the largest communities of
software developers.
The Java economy includes 2.5 billion smart cards, 800 million PCs shipped
with Java, 1.85 billion Java Powered phones , and over 180 telecom providers
who deploy Java technology based content/services.
The Power of Java
7
 WHAT IS JAVA?
 Object Oriented Programming
 WORA( Write Once Run any where) or Platform Independence
 The Java language was created by James Gosling in June 1991.
 Java Provides development and deployment environment.
 It is similar in syntax to C++
 It is robust provides exception handling , automatic garbage
collection.
 Designed for the distributed environment.
 Supports Multithreading
 Secure ( No Pointer and Byte Code Verifier)
 Architectural Neutral - If a company develops new hardware , it
doesn’t have to make a new software , only JRE needs to be replace
for New platform).
 Open Source
 High Performance (JITc)
Java Introduction
8
what is the mean of platform?
Platform consists of the computer hardware(mainly architecture of the
microprocessor) and OS.
Platform=hardware+Operating System
Anything that is platform indepedent can run on any operating system and
hardware.
Java is platform indepedent so java can run on any operating system and
hardware.
Now question is how it is platform independent?
This is because of the magic of Byte Code which is OS indepedent.
When java compiler compile any code then it generate the byte code not the
machine native code(unlike C compiler).Now this byte code need a interpreter to
execute on a machine.
This interpreter is JVM.So JVM read that byte code(that is machine indepedent)
amd execute it. Different JVM is designed for different OS and byte code is able
to run on different OS.
9
 JAVA HISTORY
 Green Project (1991) was designed for
hand-held devices and set-top boxes.
(Requirement was the hardware in the consumer devices
was always changing but the same code use on the
different hardware systems)
 It was originally named as Oak but became
unsuccessful, so in 1995, Sun changed its
name to JAVA
 James Gosling's goals were to implement a
virtual machine and a language that had a
familiar C/C++ style of notation. The first
public implementation was Java 1.0 in 1995.
It promised "Write Once, Run Anywhere"
(WORA).
Note : The initial version of Java is so small it
fit in a floppy. Now it of 60+MB.
Java Introduction
10
Java Introduction
 JAVA HISTORY continue…
11
JDK 1.0.2 JDK 1.1 JDK 1.2 JDK 1.5 JDK 1.6 JDK 1.7
Oak ------ Playground 1.2
Kestrel 1.3
Merlin 1.4
Tiger Mustang Dolphin
250 Classes 500 Classes 2300 Classes 3500 Classes 3793 Classes 4024 Classes
23 Jan 96 19 Feb 97 8 Dec 98 (1.2)
8 May 2000
(1.3)
6 Feb 2002 (1.4)
30 Sept 2004 11 Dec 2006 28 July 2011
you could use
private and
protected together
to create yet
another form of
protection that
would restrict
access to
methods or
variables solely to
subclasses of a
given class. As of
1.0.2, this
capability has
been removed
from the
language.
Extensive AWT
RMI
Inner Classes
JavaBeans
JDBC
Reflection
JDK 1.2
Strictfp
Swing
CORBA
Collection FW
JDK 1.3
Java Sound
JNDI
Java 1.4
Assert
XML Parser
Security and
Cryptography
Enhance for Loop
Var-Args
Generics
AutoBoxing
Static import
Java Compiler
API
Splash Screen
System Tray Icon
Instrument Class
(For Object Size)
Switch with String
Numeric Literal
with Underscore
Improved
Generics
Catching multiple
Exception
New Java NIO
Java Version Histroy
12
JDK 1.8 JDK 1.9 JDK 1.10
Lambda ------
Sept 2013 ---- -----
Improvement in java.lang
package
Parallel Array Sorting
Bulk Data Operations for
Collections
Base64 Encoding and
Decoding
New HTTP Client
More Security
enhancements from the
language
MultiGiga bytes Heap
Self Tuning JVM
Remove Primitive data
types
Move Towards 64 Bit
Addressing
13
 WORA
The goal is to write an application which run anywhere.
Java Introduction
14
Java Editions
15
 JAVA KICK START
1. JDK (Java Development Kit)
JDK = javac compiler + .jar (libraries) + javadoc + jdb + JRE
JDK – JDK is a software package which is used to develop and deploy
java applications.
JDK consists
a) javac compiler – it is use to convert .java file into .class file
b) JAR Files - A jar files are java API’s , which contains number of
classes and interfaces. For Example to make a database
connection with oracle we require ojdbc.jar.
c) Javadoc – through this utility we can make Java documentaion for
any java program.
d) Jdb- jdb is a java debugger.
e) JRE – See in the next slide
Java Introduction
16
 JAVA KICK START continue…
Java Introduction
2. JRE (Java Runtime Environment)- A JRE is required to run Java
applications interpretively on a target hardware and operating system platform.
JRE=JVM (Java Virtual machine)+ jar files (libraries)
Java Program execution flow
17
Java Introduction
 JAVA KICK START continue…
3. JVM
JVM is a software that is plat form
specific. For example for Linux
platform
You require a Linux based JVM ,
for windows platform you require a
windows based JVM.
Now in these days JVM is bundled
with Internet explorer and With
other types of browsers.
18
A JVM performs the following tasks.
1. Class Loader Load all the .class file, necessary for the execution of
a program.
2. Byte code Verifier It ensures the code does not no illegal data
conversion, no stack over flow, not violate system integrity.
3. JIT – (Just In time compiler) JIT work as a cache for the JVM
interpreted code. It memorized the repeated code instructions (that is
interpreted by the JVM) and when JVM reqiure the same set of
instructions so JIT provides these instructions to the JVM , so JVM
does not interpret the same instructions again
4. Generate Native Code- The JVM and the Java API are built for every
O/S platform. The Java API calls to the O/S API.
 JAVA KICK START continue…
Java Introduction
19
Java Introduction
In particular, a Java program, unlike one written in C or C++, isn't a
Single executable file, but instead is composed of many individual class files, each
of which corresponds to a single Java class.
Additionally, these class files are not loaded into memory all at once, but rather are
loaded on demand, as needed by the program.
The ClassLoader is the part of the JVM that loads classes into memory.
a) BootStrap or Primordial or Default or System Class Loader – It is a part of the
JVM Implementation. It loads the classes, including the classes of Java API.
b) User-Defined Class Loader- A Java Application can install user-define class
loader that load classes in the custom ways, such as by downloading class files
across a network.
 JAVA Class Loader
20
Types of Class Loader in Java
a) BootStrap Class Loader - Bootstrap class loader loads java’s core classes
like java.lang, java.util etc. These are classes that are part of java runtime
environment. Bootstrap class loader is native implementation and so they
may differ across different JVMs. The bootstrap class loader loads the core
Java libraries located in the <JAVA_HOME>/jre/lib directory, search for rt.jar
.
b) Extension Class loader - classes in JAR files in the lib/ext directory of the
JRE, and in the system-wide, platform-specific extension directory (such as
/usr/jdk/packages/lib/ext on the Solaris™ Operating System, but note that
use of this directory applies only to Java™ 6 and later
c) System Class Loader - The class path: classes, including classes in JAR
files, on paths specified by the system property java.class.path. If a JAR file
on the class path has a manifest with the Class-Path attribute, JAR files
specified by the Class-Path attribute will be searched also. By default, the
java.class.path property's value is ., the current directory. You can change
the value by using the -classpath or -cp command-line options, or setting
the CLASSPATH environment variable. The command-line options override
the setting of the CLASSPATH environment variable.
21
 The Way Java Works
Java Introduction
22
 Writing First Java Program
Step -1 Write Source Code
Example:
class A
{
public static void main(String args[])
{
System.out.println(“Hello Java ! “);
}
}
Step- 2 Save Code with class Name
A.java
Step-3 Compile the code
javac A.java ( when you compile the code it will generate an intermediate code (Byte
code) it is not a machine code.
Step-4 run the Program
java A ( running the program by starting the JVM with the A.class. The JVM translates the
bytecode into something the underlying platform understands , and runs your program.
Execution point of java program
Java Introduction
23
Inside System Class
24
System Class
In - System.in
Out - System.out.println()
Err – System.err.println()
Shorten the System.out.println()
Import static java.lang.System.out;
out.println(“Hello Java ! “);
25
1. Do you know through System.out.println(), You can write the output in a file
instead of writing on a Console.
2. You can print output in a different language , like in Hindi in Java
3. You can get the Login User Name , Operation System Name, JDK Location,
Number of Processor in a System and many more.
4. Request to the Java Garbage Collector
5. You can not create an object of System class
6. Performance Monitoring of a Method
7. Introduce the printf method
Example:
String name ="Amit";
int age =21;
System.out.printf("Your Name is %s and Age is %d",name,age);
char gender ='M';
System.out.printf("nGender is %c ",gender);
float amount = 12000.50f;
System.out.printf("nAmount is %f",amount);
System.out.printf("nAmount is %6.2f",amount);
The Magic of System class
26
Program Observation
When the JVM starts running , it looks for the class that is at the
command line. Then it starts looking for a specially written method that
looks exactly like:
public static void main(String args[])
{
//Your Code Here
}
Note: Every Java application has to have at least one class, and at
least one main method.
Java Introduction
27
Program Observation continue…
You can define main method in the following ways
a) public static void main(String args[])
b) static public void main(String args[])
c) public static void main(String …a) // Allowed in JDK 1.5 or higher
d) static public void main(String …a) //Allowed in jdk1.5 or higher
The main method is public , because java is package centric language.
Now JVM has to access your main method from outside your package.
That’s why it set to as public
The main method also static , because static is loaded on the compile
Time and not required to instantiate.
The main method is void , because it is not required to return any thing
to the JVM.
Main is the name of the method
String args[] is used for command line arguments , where String is a
Java class.
Java Introduction
28
Java Introduction
Program Observation continue…
System.out.println(“Hello Java ! ”);
Where System is a final class, found in java.lang package.
Out is a object of PrintStream class and it declare static in the System
Class.
Println(String msg) this is a method define in the PrintStream class.
Used to print on console and print in new line
29
Java Basics
 Identifier
 Variable
 Constant
 Keyword
 Data Types
 Java Coding Conventions
 Sequential Programs
 Conditional Programs
 Looping
30
Identifier
It is a name given to a class, variable, constant or method.
Rules for Declaring a Legal Identifier:
a) Identifier must start with a letter, $, _. Cannot start with number.
b) After the first letter, contain numeric.
c) No Limit to the number of characters an identifier can contain.
d) Cannot use keyword in identifier name.
e) Identifiers are case-sensitive.
Java Basics
31
Variable
A variable is just like a cup or container. It can hold something.
It has a size and a type.
Example:
int a=123;
a
Java Basics
Sample Example
32
 Constant
As the name implies , constants are fixed values which never
change.
Example:
final int MAX=100;
“final” keyword is used to declare a constant in java.
 Keywords
Keywords are reserved which has some special meaning for
the compiler.
For Example : if , while ,int etc.
Java Basics
Sample Example
33
Java Basics
Java Keywords
34
 Data types
Variable (Cup) can be of two type
✔Primitive Type
✔Reference Type
Primitive Type – Primitives are like the cups at the Coffee-House
They come in different sizes and each has name like small , big,
medium.
Java Basics
35
Primitive Type Example
byte x=10; // Take 1 byte in memory
short y=500; // Take 2 bytes in memory
int a=40000; // Take 4 bytes in memory
Java Basics
36
Primitive Data Types List
In Java, primitives come in different sizes with different names.
When you declare a variable in Java, you must declare with a
specific type.
Java Basics
Data Type Bytes Range
boolean
: Internally java treat is 1 for true and 0 for false, and dependent on OS itcan be treated as byte, short, int)
True or false
char 2 Bytes (UNICODE Characters) 0 to 65535
byte 1 byte -128 to 127
short 2 bytes -32768 to 32767
int 4 bytes -2147483648 to2147483647
long 8 bytes huge
float 4 bytes varies
double 8 bytes varies
37
TEST YOUR SELF
Java Basics
I am a slow walker, but I never walk back. Said by Abraham Lincoln
38
Test Your Self
1. Declare a variable, in which store age of Employee,
choose the best way
a) int age;
b) short age;
c) long age;
d) boolean age;
e) byte age;
2. To declare constant in java
a) const int a=10;
b) int a=10;
c) final int A=10;
d) byte a=10;
3. To store the attendance status of employee , whether Employee is
present or not. Which deceleration is appropriate.
a) boolean att; c) float att;
b) int att; d) double att;
Java Basics
39
Test Your Self
4. Which one is the correct variable deceleration ,
choose all that apply
a) int _a;
b) int _____a;
c) int 1a;
d) int emp_no;
e) float @sal;
f) float $sal;
g) double $_bonus;
h) boolean int;
Java Basics
40
Reference type
A Reference variable holds bits that represents a way to access
an object.
It doesn't hold the object itself, but it holds something like a
pointer, or an address.
Java Basics
41
b
JAVA
Reference Type Example:
String b=”Java”;
Java Basics
42
Primitive Type Example
int a=100;
int b=200;
int c=a;
100 200
a b
100
c
Memory Area
Java Basics
Primitive Vs Reference Type
43
Java object
reference
World object
reference
Java object
reference
a
b
c
Java
World
Reference Type Example
String a=new String(“Java”);
String b=new String(“World”);
String c=a;
Java Basics
Primitive vs Reference Type
44
Using == with primitive type
Example
int a=100;
int b=100;
System.out.println(a==b); //print true
Using == with reference type
Example:
String a=new String(“Hello”);
String b=new String(“Hello”);
System.out.println(a==b); // false But Why ???
Answer is, The reference type checks address in this case , it return true if both
address or references are same.
So HOW I COMPARE VALUES IN REFERENCE TYPE, BECAUSE == CHECKS
ADDRESS NOT VALUE?
Answer is using equals()
System.out.println(a.equals(b)); //return true
Java Basics
45
TEST YOUR SELF
Java Basics
There is nothing impossible to him who will try.
Said by Alexander the Great
46
Test Your Self
1) What will be the output of the following code?
String a=new String(“Hello”);
String b=new String(“Hello”);
if(a.equals(b))
System.out.println(“Same “);
else
System.out.println(“Not Same “);
Java Basics
47
Test Your Self contd…
2) What will be the output of the following code?
String a=new String(“Hello”);
String b=new String(“Hello”);
String c=a;
String d=b;
if(a==c)
System.out.println(“Same Reference “);
else
System.out.println(“Not Same Reference “);
if(b==d)
System.out.println(“Same b and d Reference“);
else
System.out.println(“Not Same b and d reference “);
Java Basics
48
Java Coding Convention
Class and Interfaces – The First letter should be capital, and first
letter of the inner words should be Capital.
Example : Account
PrintWriter
Emp
Methods – The First Letter should be lowercase, and then normal
camelCase rules should be used.
Example : getBalance
setCustomerName
Variables – Same rule as Method Rule
Constants – All in Uppercase.
Example : MIN_HEIGHT
Java Basics
49
What can you say in the main method?
•Write Sequential Statements
•Conditional Branching
•Looping
Java Basics
50
 Writing Sequential Statements
Example:
class Test
{
public static void main(String args[])
{
int a,b,c; //declaring primitive variables
a=100;
b=200;
c=a+b;
System.out.println(“Sum is “+c);
} //main close
} //class close
Java Basics
51
Exercise: To Do YourSelf
1) WAP to swap two numbers.
2) WAP to calculate simple interest
3) WAP to calculate area and perimeter of a rectangle
4) WAP to calculate net salary of employee, take basic
salary of employee and calculate Hra 30% of basic salary,
DA 20% of the basic salary, Ta 10% of the basic salary and
net salary is sum up of basic salary+ allowances-pf. Pf is
1400 fix.
Note : Follow Java Conventions during coding
Java Basics
52
Java Decision Making Statements
1) Using if-else
2) Using switch
Java Basics
53
 Decision Making Programs
Example 1
class Test
{
public static void main(String args[])
{
int a,b;
a=100;
b=200;
if(a>b) //required boolean true or false
System.out.println(“A is Greater “);
else
System.out.println(“B is Greater “);
}
}
Java Basics
54
class Test
{
public static void main(String args[])
{
int a=2;
switch(a)
{
case 1:
System.out.println(“Sunday “);
break;
case 2:
System.out.println(“Monday “);
break;
case 3:
System.out.println(“Tuesday”);
break;
case 4:
System.out.println(“Wednesday “);
break;
case 5:
System.out.println(“Thursday “);
break;
case 6:
System.out.println(“Friday “);
break;
Java Basics
Example 2:
case 7:
System.out.println(“saturday “);
break;
default:
System.out.println(“Invalid Day “);
}
}
}
Note: Switch only allowed
int ,byte, char type
55
TEST YOUR SELF
Your Purpose in life is to find your purpose and give your whole heart and soul to it.
Said by Buddha
56
Test Your Self
Java Basics
1) What will be the output of the following code?
class Test
{
public static void main(String args[])
{
int a=10;
if(a=20)
System.out.println(“TRUE”);
else
System.out.println(“False “);
}
}
a) Print TRUE b) Print False
c) Compilation Fail d) None of these
57
2) What will be the output of the following code?
class Test
{
public static void main(String args[])
{
String name=”Mike”;
int age=21;
if((name.equals(“Mike”)) && age>=21)
System.out.println(“Welcome “+name);
else
System.out.println(“Bye “+name);
}
}
Test Your Self contd…
Java Basics
58
3) What will be the output of the following code?
class Test
{
public static void main(String args[])
{
int color=2;
switch(color)
{
case 1:
System.out.println(“RED “);
default:
System.out.println(“GREEN”);
case 3:
System.out.println(“BLUE”);
}
}
}
Test Your Self contd…
Java Basics
59
4) What will be the output of the following code?
class Test
{
public static void main(String args[])
{
int color=2;
switch(color)
{
case 1:
System.out.println(“RED “);
break;
default:
System.out.println(“GREEN”);
break;
case 3:
System.out.println(“BLUE”);
break;
}}}
Test Your Self contd…
Java Basics
60
Exercise:
1) Find out entered number is Positive or Negative Number.
2) Find out the grade , according to given percentage of the user.
>=90 print A Grade
89 to 70 B Grade
69 to 50 C Grade
<50 D Grade
Java Basics
61
3) A Insurance Company have a following polices (Insurance Premium
Calculation program)
User Input :
Person Name
Person gender
Person Age
Person city (Metro or Non-Metro)
Conditions:
if person age is 25 to 35 and gender is male and city is metro , Output is
Premium is 6%
if person age is 25 to 40 and gender is male and city is non-metro, Output
is Premium 4%
if person age is 25 to 42 and gender is female and city is Metro, Output is
Premium 3%
if person age is 25 to 45 and gender is female and city is non-metro , output
is Premium 2%
else Not Insured
Exercise: contd…
Java Basics
62
When you want to repeat something for definite number of times,
it is called loop.
Java has three basic loops
a) for b) while c) do-while.
In JDK 1.5 java introduce one more loop called Enhance for
loop.
Java Basics
 LOOPING
63
 JAVA LOOPS EXAMPLE
class Test
{
public static void main(String args[])
{
int i=1;
while(i<=10) //Need boolean test
{
System.out.println(“While Loop Value of i is “+i);
i++;
}
for(i=1;i<=10;i++)
{
System.out.println(“For Loop Value of i is “+i);
}
i=10;
do
{
System.out.println(“Do While Value of i is “+i);
}while(i<10);
}
}
Java Basics
64
Enhance For Loop
Enhance for loop introduced in JDK 1.5 version
Example:
int a[]= {10,20, 30, 40, 50};
for(int x: a)
{
System.out.println(x);
}
Java Basics
65
TEST YOUR SELF
I hated every minute of training but I said, ‘Don’t quit. Suffer now and live the rest
of your life as a Champion.
Said by Muhammad Ali
66
Test Your Self
1) What will be the output of the following code
class Test
{
public static void main(String args[])
{
for(int i=1;i<=3;i++)
{
for(int j=1;j<=3;j++)
{
System.out.println(“Value of i is “+i +” Value of j is “+j);
} //j for loop close
} //i for loop close
} //main close
} //class close
Java Basics
67
Test Your Self contd…
2) What will be the output of the following code?
class Test
{
public static void main(String args[])
{
String names [] = {“Ram”, “Shyam”, “Mohan”, “Sohan”};
for(int temp: names)
{
System.out.println(temp);
}
}
}
Java Basics
68
Java Basics
Test Your Self contd…
2) What will be the output of the following code?
class Test
{
public static void main(String args[])
{
for(int i=1;i<=3;i++)
{
for(int j=1;j<=3;j++)
{
if(i==j)
continue;
else
System.out.println(“Value of i is “+i +” Value of j is “+j);
}
}
}
}
69
Exercise:
1) WAP to count even number and odd number between 1 to 100.
2) WAP to count prime number between 1 to 100.
3) WAP to print sum of
1+2+3+.............................n
4) WAP to print sum of
12+22+32+..........................n2
Java Basics
5) Now i want to improve the functionality of the “Insurance Premium
Calculation program”.
Take the input of user details like name, gender, city and age, until user
enters “No”. If user enters ‘No’, then exit from the loop, else continue in the
loop. Take input again and check if eligibility for the insurance is there or not
, also count how many users are eligible and how many are not.
70
Object Oriented Basics (OO Basics)
 OO and Procedural Programming WAR
 Object Oriented Features
71
A programmer primary task is to write software to solve a problem. Many
programming models have evolved to help programmers in being more effective.
Procedural Programming
One way of solving a problem is to break it down into smaller parts and solve each
of the smaller parts. Then aggregate (collate) all the parts to solve the overall
problem.
Think of each small part as task, to perform which you write a block of code is
called function. You can call one function from another.
This approach in software development is called process centric or Procedural.
For Example:
Procedural Programming
72
Drawbacks of Procedural Programming
1. The code are so interdependent (due to one function call to another function) , so
one application code cannot be used in another application.
2. Interdependence between the modules so it is inflexible to change, So
maintaince is not easy.
3. This approach only good , if software engineer knows every aspects of project.
4. Not on Real world approach
5. Not good to solve large and complex problems
Procedural Programming
73
An Object Oriented programming
Object oriented programming works on object instead of functions.
An object is a real world entity.
For Example:
Cat , Car , Ball are some of the examples of real world objects
An object represents two things
a) State – Dog has 4 legs , 1 tail , 2 ears . It shows the dog state
b) Behavior- are the functions or methods , that uses the state and shows
behavior of an object.
For example : dog jumps, so for this it is depend on legs
Now we take some more example
Amit is working as a Employee in Xyz Ltd.
So Amit represents an object of type Employee.
His states are empno is1010, Name is Amit Srivastava, Age is 27, and it’s
behavior are Attendance details, work details, salary calculation etc.
OO Basics
74
Object Oriented Programming and Procedural Programming WAR
OO Basics
75
OO Basics
Contd.....
76
Add one more shape in your current program
Contd.....
OO Basics
77
OO Basics
Contd.....
78
Contd.....
OO Basics
79
OO Basics
Contd.....
80
Contd.....
OO Basics
81
Conclusion of the Story
In Object Oriented Programming , Developer divide the problem into different objects
, instead of breaking the problem into functions (methods).
The Object is a real world entity.
For Example:
Amit is an object of class Employee
Royal Enfield is an object of Motor Bike
Object = State + Behavior
State represents the data items , for example : State of Amit are Empno, Name , Age
, Gender, Deptno , PhoneNo etc.
Behavior represents the functions (methods) . For example : work details,
attendance details, salary calculation etc.
82
Object Oriented Features
1) Encapsulation
Encapsulation - Binding “Data and Method” into a single unit and good encapsulation
is when your Data is private/protected and your methods are public.
Example of Encapsulation is Human Brain, Capsule.
OO Basics
class Emp
{
int empno; //DATA
String name;
float sal;
void input() //METHOD
{
empno=1001;
name=”MIKE”;
sal=9090.00f;
}
void show()
{
System.out.println(“Empno is “+empno);
System.out.println(“Name is “+name);
System.out.println(“Sal is “+sal);
}
}
83
2) Abstraction- Working on the essential things and to forget the things which are
not essential for us.
For Example : If i drive my car from my house to market, so i have to know how to
use brakes, accelerator, gear, steering, horn , clutch etc., i don't need to know
internal working of these things.
Example of Abstraction in Java is abstract classes, interfaces.
Contd.....
OO Basics
HyperLink
84
3) Inheritance - Used to show parent - child relationship like one class inherit the
features of the other class, so it provide you the code reusability.
For Example:
A CAR IS A Vehicle, it means CAR inherits the feature of Vehicle like brakes,
wheels, horn, clutch etc.
Contd.....
OO Basics
85
Inheritance Example:
class Account
{
int accountno;
float balance;
void deposit()
{
}
void withdraw()
{
}
}
class SavingAccount extends Account
{
float rateOfInterest;
void calculateRoi()
{
}
}
OO Basics
86
4) Polymorphism- One thing having several forms.
Example: All Animals are eating, but each type has different eating habits like Dog eats Meat,
Cow eats grass etc.
Example: In a calculator we can add two Integer, two real number, three numbers so a same
method name is used to add two numbers, three numbers, four numbers, two int numbers ,
two float numbers etc. This term is called “Method Overloading”.
Sample Code:
void add(int x,int y)
{
System.out.println(x+y);
}
void add(float x,float y)
{
System.out.println(x+y);
}
void add(int a,int b,int c)
{
System.out.println(a+b+c);
}
Object Oriented Features Contd......
OO Basics
87
5) Class- Contains state (instance variables) and behaviour
(methods). A template that describes the kinds of state and
behaviour that objects of its type support.
5.1) State (Instance variables) – Each Object (instance of a class)
will have its own unique set of instance variables as defined in the
class.
5.2) Behaviour (Methods) – Methods are where the class logic is
stored, and it work on instance variables.
6) Object – Is an instance of a class. When JVM encounters the
new keyword, it will use the same class to make an object. That
Object will have its own states, and access to all of the behaviour
defined by it's class.
Contd......
OO Basics
88
Example: Creating class and Object
class Emp
{
int empno; //Instance variables
String name;
float sal;
void input(int eno,String ename,float esal) //Methods
{
empno=empno;
name=ename;
sal=esal;
}
void show()
{
System.out.println(“Empno is “+empno);
System.out.println(“Name is “+name);
System.out.println(“Sal is “+sal);
}
public static void main(String args[])
{
Emp ram=new Emp();
//Creating a new object, a new operator is used to allocate a memory for the object.
ram.input(1001,”Ram “, 9090.0f);
ram.show();
Emp shyam =new Emp();
shyam.input(1002,”Shyam”,8888.0f); shyam.show();
}
}
OO Basics
Sample Example
89
Memory Representation of Emp Class Object
empno=1001
name
sal=9090.0f
MIKE
obj
OO Basics
Sample Example
90
General formula for calculating memory usage
In general, the heap memory used by a Java object in JVM consists of:
an object header, consisting of a few bytes of "housekeeping" information;
"housekeeping" information, such as recording an object's class, ID and status flags
such as whether the object is currently reachable, currently synchronization-locked
etc.
memory for primitive fields, according to their size
memory for reference fields (4 bytes each);
padding: potentially a few "wasted" unused bytes after the object data, to make
every object start at an address that is a convenient multiple of bytes and reduce the
number of bits required to represent a pointer to an object.
In Hotspot, every object occupies a number of bytes that is a multiple of 8. If the
number of bytes required by an object for its header and fields is not a multiple 8, then
you round up to the next multiple of 8.
91
This means, for example, that:
a bare Object (With no instance Variable) takes up 8 bytes;
an instance of a class with a single boolean field takes up 16 bytes: 8 bytes of
header, 1 byte for the boolean and 7 bytes of "padding" to make the size up to a
multiple of 8;
an instance with eight boolean fields will also take up 16 bytes: 8 for the header, 8
for the booleans; since this is already a multiple of 8, no padding is needed;
an object with a two long fields, three int fields and a boolean will take up:
8 bytes for the header;
16 bytes for the 2 longs (8 each);
12 bytes for the 3 ints (4 each);
1 byte for the boolean;
a further 3 bytes of padding, to round the total up from 37 to 40, a multiple of 8.
92
Object Size get in Java
package com.example.demo
public class MyAgent {
public static void premain(String args, Instrumentation inst) {
SomeClass obj = new SomeClass();
long size = inst.getObjectSize(obj);
System.out.println("Bytes used by object: " + size);
}
public static void main(String args[])
{
System.out.println(“Inside Main “);
}
}
Package the Agent into JAR
Add the following entry in the Manifest.mf file
Premain-Class: com.example.demo.MyAgent
Main-class :com.example.demo.MyAgent
Run
java -javaagent:agent.jar –jar agent.jar
93
Improving the Emp class example by using JavaBean
Java Bean
Simple Java classes that have private instance members and
public setter and getter methods. It is a reusable component.
OO Basics
94
Example: Creating JavaBean
class Emp
{
private int empno;
private String name;
public void setEmpno(int empno) //Java Bean Rules
{
this.empno=empno; //Shadowing
}
public int getEmpno()
{
return empno;
}
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
}
NOTE: this is also called good encapsulation
OO Basics
Sample Example
95
TEST YOUR SELF
Nobody has the power to take two steps together; you can take only one step at a time.
Said by Osho
96
1) Check this is proper Java Bean.
class Customer
{
private int custId;
public String name;
public void setCustId(int custId)
{
this.custId=custId;
}
public int getCustId()
{
return custId;
}
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
}
OO Basics
97
2) TRUE – FALSE
a) Encapsulation means private methods and public variables.
b) extends is used for inheritance.
c) Overloading is an example of Abstraction.
d) Instance Variables live in a Stack.
e) new operator is used to allocate a memory for an object
f) object always of reference type.
g) Class is an instance of an object.
h) Local Variables and Methods live in a Stack.
OO Basics
98
Exercise :
1) Create a Student class which has rollno , name, 3 subject
marks(English , Hindi , Maths) calculate total marks, percentage and
grade. And print the Result Sheet of the Student.
2) Create a Employee class which has empno,name,basicSalary,
calculate HRA, DA , TA and GS.
HRA is 30% of basic salary
DA is 20% of basic salary
TA is 10% of basic salary
GS=BasicSalary+ hra+da+ta
OO Basics
99
Using Constructor
 About Constructor
 Calling One Constructor by another constructor
100
 Constructor
✔Constructor has same name as a class name.
✔It is same like a method.
✔It returns nothing.
✔It Call automatically when object is created.
✔It is used to initialize the instance variables of a class.
✔You can't make a new object without invoking a constructor.
✔Every class have a default constructor by default.
Using Constructor
101
class Emp
{
int empno;
String name;
float sal;
void input()
{
empno=1002;
name=”Mike”;
sal=9090.0f;
}
public static void main(String
args[])
{
Emp obj=new Emp();
System.out.println(obj.empno+
obj.name+obj.sal);
}}
class Emp
{
int empno;
String name;
float sal;
Emp()
{
empno=1001;
name=”TIM”;
sal=9090.0f;
}
public static void main(String args[])
{
Emp obj=new Emp();
System.out.println(obj.empno+obj.name+obj.sal)
;
}
}
Using Constructor
Example 1 Without Constructor Example 2 Using Constructor
Sample Example
102
Example 3:
class A
{
A() //the default constructor for the A Class
{
}
}
Example 4:
class A
{
A(int a)
{
}
}
A obj=new A(); //Won't compile , no matching constructor.
Example 5:
class A
{
A()
{
System.out.println(“I am default Constructor”);
}
void A()
{
System.out.println(“ I am not a constructor , i am a method ! “);
}
}
Contd….
Using Constructor
103
Calling One Constructor by another Constructor in same class
Example:
class A
{
private A()
{
System.out.println(“ I am default constructor of the A Class “);
}
A(int s) //Overloading of the Constructor
{
this(); // Must be the first statement
System.out.println(“I am the A class Parameterized Constructor “);
}
}
class Test
{
public static void main(String agrs[])
{
A obj=new A(); //Error because default constructor is private
A obj1=new A(100);
}
}
Using Constructor
104
TEST YOUR SELF
Don’t find a fault, find a remedy; anyone can complain
Said by Henry Ford
105
Test your Self
1) What will be the output of the following code?
class A
{
A(int b)
{
System.out.println(“A class Constructor “);
}
public static void main(String args[])
{
A obj=new A();
}
}
Using Constructor
106
Test Your Self contd…
2) What will be the output of the following code?
class A
{
A()
{
System.out.println(“A class Default Constructor Call “);
}
A(int x)
{
this();
System.out.println(“A class Parameterized Constructor Call “);
}
public static void main(String args[])
{
A obj=new A(10);
}
}
Using Constructor
107
Exercise:
Create a class Emp with empno,name,sal as instance variables
and then create two constructor default and parametrized to set
the values of instance members and create a method print() to
print the values.
Using Constructor
108
IS-A
 About Inheritance
 Inheritance Advantages
 Reference Variable Rules
 HAS-A
 Class Access Ways
 Access Modifiers
 Final class
109
IS-A
INHERITANCE TREE
LION IS-A Animal
Hippo IS-A Animal
Tiger IS-A Animal
Inheritance
110
Account
(Account number, balance)
Current Account Saving Account
LOAN
AutoLoan Personal
Loan
IS-A
Inheritance Example
111
Contd.......
Example:
class A
{
Feature1 ;
Feature 2;
}
class B extends A
{
Feature 3; // + Feature 1 and Feature 2 comes from class A
Feature 4;
}
Inheritance has two advantages
1. To Promote code reuse ability, so code redundancy is reduce.
2. To Use Polymorphism
IS-A
Sample Example
112
1) To Promote code reuse ability, so code redundancy is reduce.
class Person
{
int age;
String name;
String address;
void input()
{ age=21;
name=”TIM”;
address=”NewYork”; }
void print()
{
System.out.println(“Person Name is “+name);
System.out.println(“Person Age is “+age);
System.out.println(“Person Address is “+address);
}
}
class Emp extends Person
{
int empno;
String desig;
float sal;
public void empInput()
{
empno=1001;
desig=”Programmer”;
sal=9090.00f;
}
Inheritance First Advantage
113
Contd....
public void empPrint()
{
System.out.println(“Empno is “+empno);
System.out.println(“Designation is “+desig);
System.out.println(“Salary is “+sal);
}
}
class Test
{
public static void main(String args[])
{
Emp obj=new Emp();
obj.input();
obj.empInput();
obj.print();
obj.empPrint();
}
}
IS-A
114
2) To Use Polymorphism
Polymorphism one thing with several forms.
Example:
class Animal
{
}
class Dog extends Animal
{
}
class Cat extends Animal
{
}
Animal a=new Animal();
a=new Dog();
a=new Cat();
Inheritance Second Advantage
IS-A
115
 Reference variable rule:
✔A reference variable can be only one type and once declared,
that type can never be changed.
✔A reference type determines the methods that can be
invoked on the object the variable is referring.
✔It can refer to the same type or the sub type.
✔A reference variable can be of class type or interface type.
✔Up casting allowed only ( parent can take own and sub-type)
but down casting not allowed (child cannot take parent type).
NOTE: we cannot make a single program with out inheritance in java,
because every class inherit java.lang.Object class.
NOTE: Java is a package centric language; the developer assumed that for
good organization and name scoping , you would put all the your classes into
packages.
IS-A
116
Exercise:
Person class
Student class
Emp class
IS-A
Account
Current Account Saving
Account
117
 HAS- A
Has a relationship is based on usage , rather than inheritance.
Has-A used by making an object of the other class in your class.
For Examples:
Horse HAS-A Halter,
Customer Has-A Loan
Sample Code:
class Loan
{
}
class Customer
{
Loan carLoan =new Loan();
}
IS-A
118
IS-A HAS-A
Used to create a parent child relationship. IS-
A is based on class inheritance or interface.
Has-A relationship is based on usage , rather
than inheritance
For Example: BMW is a Car, Horse is an
Animal, AutoLoan IS-A Loan
For Example: Horse HAS-A Halter,
Customer HAS-A Loan
IS-A can be use by extends or implements
keyword.
Has-A used by making an object of the other
class in your class.
Example:
class Loan
{
}
class AutoLoan extends Loan
{
}
Example:
class Customer
{
AutoLoan car=new AutoLoan();
}
class AutoLoan
{
}
Advantages of IS-A
1) To Promote code re useability, so code
redundancy is reduced.
2) To Use Polymorphism
Advantages of HAS-A
1) Can work on other class instance variables
& methods without inheriting that class.
 CLASS ACCESS WAYS
IS-A
119
Access Modifier
There are 4 access modifier. (private, public, protected, default)
Note: With class only 2 access modifier can apply. ( public and default).
✔public access modifier- When a method or variable member is
declared public, it means access with in a package or outside a
package.
✔private access modifier- Members marked private can't be accessed
by code in any class other than the class in which the private member
was declared.
✔protected access modifier - Access with in same package and can
access outside the package by using inheritance.
✔default access modifier- If we didn't place an access modifier in front
of the variable or method, the access control is default, which means
package level.
Note: Can Access Modifiers be applied to local variables ? NO!
IS-A
120
Example: Show Use of public access modifier
package book; package cert;
import cert.*; public class B
class A {
{
public static void main(String args[]) public void show()
{ {
B obj=new B(); System.out.println(“B Class Show “);
obj.show(); }
} }
}
IS-A
121
IS-A
Final class
final class A //final class cannot be inherit
{
}
class B extends A // You cannot inherit a final class
{
}
NOTE: String is a final class
Sample Example
122
TEST YOUR SELF
Nothing is particularly hard if you divide it into the small jobs.
Said by Henry Ford
123
Test Your Self
IS-A
1) What will be the output of the following code?
class A
{
}
class B extends A
{
}
class C extends A, B
{
}
124
• What is the output:
class A
{
A()
{
System.out.println(“A Class Default Constructor Call “);
}
}
class B
{
B()
{
System.out.println(“B class Default Constructor Call “);
}
}
class Test
{ public static void main(String args[])
{
B obj=new B(); }
}
Test Your Self contd…
IS-A
125
class A
{
A(int a)
{
System.out.println(“A class Parameterized Constructor Call “);
}
}
class B extends A
{
B()
{
System.out.println(“B Class Default Constructor Call “);
}
}
class Test
{
public static void main(String args[])
{ B obj=new B(); }
}
IS-A
3) What is the output:
Test Your Self contd…
126
IS-A
4) What will be the output of the following code?
class A
{
void showA()
{
System.out.println(“A show “);
}
}
final class B extends A
{
void showB()
{
System.out.println(“B Show “);
}
}
class Test
{
public static void main(String args[])
{
B obj=new B(); obj.showA(); obj.showB(); }
}
Test Your Self contd…
127
IS-A
5) What will be the output of the following code?
class A
{
private int a=10;
public int b=20;
int c=30;
protected int d=40;
}
class B extends A
{
void add()
{
System.out.println(a+b+c+d);
}
public static void main(String args[])
{
B obj=new B();
obj.add();
}
}
Test Your Self contd…
128
Polymorphism
 Overloading
 Overriding
 Using final in Overriding
 Overloading vs Overriding
 super vs this
129
Polymorphism- One thing with several forms.
For Example: All Animals are eating, but each type has different eating habits like Dog eats
Meat, Cow eats grass etc.
For Example: In calculator we can add two Integer, two real number, three numbers so a
same method name is used to add two numbers, three numbers, four numbers, two int
numbers , two float numbers etc.
Sample Code:
void add(int x,int y)
{
System.out.println(x+y);
}
void add(float x,float y)
{
System.out.println(x+y);
}
void add(int a,int b,int c)
{
System.out.println(a+b+c);
}
Polymorphism
130
 Overloading
Overloaded methods can be reused as the same method name in a class,
but with different arguments and optionally , a different return type.
Example : A search method on Banking System, to search its customer by
name, or by address or by dob, or by phone number, or by customer id.
Sample Code:
boolean search(int custid)
boolean search(String name,String address)
boolean search(String name,Date dob)
boolean search(String name,String phoneno)
Polymorphism
Sample Example
131
Overloading Example:
class Calculator
{
public void add(int x,int y)
{
System.out.println(x+y);
}
public void add(int x,int y, int z)
{
System.out.println(x+y+z);
}
public void add(float x,float y)
{
System.out.println(x+y);
}
public int add(long x,long y)
{
return (x+y);
}
public static void main(String args[])
{
Calculator obj=new Calculator();
obj.add(10,20);
obj.add(10,20,30);
obj,add(10.1f,20.2f);
obj.add(10l,20l);
}
}
Polymorphism
132
 Overriding
Polymorphism
133
Overridden Methods
Any time you have a class that inherits a method from a superclass, you have the
opportunity to override the method.
Example:
class Animal
{
public void eat()
{
System.out.println(“Generic Animal eating Generically “);
}
}
class Dog extends Animal
{
public void eat()
{
System.out.println(“EAT MEAT”);
}
}
class Cow extends Animal
{
public void eat()
{
System.out.println(“EAT GRASS “);
}
}
Here eat() method overridden
Polymorphism
Sample Example
134
class Account
{
void withdraw() { }
void deposit() { }
void rateOfInterest() { }
}
class CurrentAccount extends Account
{
public void rateOfInterest()
{
}
}
class SavingAccount extends Account
{
public void rateOfInterest()
{
}
}
Polymorphism
Overriding Example
Sample Example
135
Polymorphism
Using final in Overriding
class A
{
final void show()
{
}
}
class B extends A
{
void show() //Compilation Fails because show is defined final , and we cannot
//override a final method.
{
}
}
136
Polymorphism
Overloading Overriding
Any time you have a class that inherits a
method from a superclass, you have the
opportunity to override the method.
Overloaded methods let you reuse the same
method name in a class, but with different
arguments( and optionally , a different return
type.
The argument list must be same. Overloaded methods must change the
argument list.
The return type must be same in jdk1.4, but
in jdk1.5 it should be co-variant returns
Overloaded methods can change the return
type.
The access level can't be less restrictive in
Overridden method.
Overloaded methods can change the
access modifier.
Can throw any unchecked exception by
Overriding.
The Overridden method can throw any sub
type or same type exception of overriding
method.
Overloaded methods can declare new or
broader checked exceptions.
Without inheritance no Overriding. A method can be overloaded in the same
class or in a subclass.
You cannot override a method marked final.
You cannot override a method marked
static.
Can overload final and static methods.
137
Widening in Overloading
Widening always use same or bigger data type, not go for the smaller.
Example: What is the output
class A {
void show(int x) { System.out.println(“Show Int “); }
void show(byte x) { System.out.println(“Show byte “); }
void show(long x) { System.out.println(“Show long “); }
public static void main(String args[]) {
A obj = new A();
Obj.show(10);
}
}
138
The compiler will choose the older style before it chooses the newer style,
keeping existing code more robust. So far we've seen that
1) Widening beats boxing
2) Widening beats var-args
Example: AutoBoxing Happens Automatically
class AddBoxing {
static void go(Integer x) { System.out.println("Integer"); }
public static void main(String [] args) {
int i = 5;
go(i);
}
}
Overloading Rules
139
Example: Here widening Happens
class AddBoxing {
static void go(long x) { System.out.println("long"); }
public static void main(String [] args) {
int i = 5;
go(i);
}
}
Example : Here Widening Beats Boxing
class AddBoxing {
static void go(Integer x) { System.out.println("Integer"); }
static void go(long x) { System.out.println("long"); }
public static void main(String [] args) {
int i = 5;
go(i); // which go() will be invoked?
}
}
140
Example : Here Wrapper classes Beats Var-args
class BoxOrVararg {
static void go(Byte x, Byte y){ System.out.println("Byte, Byte"); }
static void go(byte... x) { System.out.println("byte... "); }
public static void main(String [] args) {
byte b = 5;
go(b,b); // which go() will be invoked?
}
}
Example: Here Mixing Wideing and Autoboxing, The Java Compiler not able
to do it both, so it will give error
class WidenAndBox {
static void go(Long x) { System.out.println("Long"); }
public static void main(String [] args) {
byte b = 5;
go(b); // must widen then box - illegal
}
}
141
1) Static binding in Java occurs during Compile time while Dynamic binding
occurs during Runtime.
2) Static binding uses Type(Class in Java) information for binding while
Dynamic binding uses Object to resolve binding
3) Overloaded methods are bonded using static binding while overridden
methods are bonded during run time (Dynamic Binding).
4) Instance Variable bound with static binding.
Static v/s Dynamic Binding
142
public class StaticBindingTest {
public static void main(String args[]) {
Collection c = new HashSet();
StaticBindingTest et = new StaticBindingTest();
et.sort(c);
}
//overloaded method takes Collection argument
public Collection sort(Collection c){
System.out.println("Inside Collection sort method");
return c;
}
//another overloaded method which takes HashSet argument which is sub class
public Collection sort(HashSet hs){
System.out.println("Inside HashSet sort method");
return hs;
}
}
Output:
Inside Collection sort method
Static Binding Demo
143
Dynamic Binding Demo
public class DynamicBindingTest {
public static void main(String args[]) {
Vehicle vehicle = new Car(); //here Type is vehicle but object will be Car
vehicle.start(); //Car's start called because start() is overridden method
}
}
class Vehicle {
public void start() {
System.out.println("Inside start method of Vehicle");
}
}
class Car extends Vehicle {
public void start() {
System.out.println("Inside start method of Car");
}
}
Output:
Inside start method of Car
144
TEST YOUR SELF
A person who never made a mistake never tried anything new.
Said by Albert Einstein
145
TEST YOUR SELF
1) What will be the output of the following code?
class A
{
void show()
{
System.out.println(“ A class Show Call “);
}
}
class B extends A
{
String show()
{
System.out.println(“B Class show call “);
}
}
B obj=new B(); obj.show();
Polymorphism
146
TEST YOUR SELF contd…
2) What is this , Overloading or Overriding?
class A
{
void show()
{
System.out.println(“ A class Show Call “);
}
}
class B extends A
{
void show(int i)
{
System.out.println(“B Class show call “);
}
}
Polymorphism
147
TEST YOUR SELF contd….
3) What will be the output of the following code?
class A
{
public void show()
{
System.out.println(“ A class Show Call “);
}
}
class B extends A
{
void show()
{
System.out.println(“B Class show call “);
}
}
B obj=new B(); obj.show();
Polymorphism
148
TEST YOUR SELF contd….
4) What will be the output of the following code?
class A
{
private final void show()
{
System.out.println(“ A class Show Call “);
}
}
class B extends A
{
void show()
{
System.out.println(“B Class show call “);
}
}
B obj=new B(); obj.show();
Polymorphism
149
super this
Super keyword always refers to the parent
elements like parent method , parent
constructor, parent instance variables.
This keyword always refers to the current
class elements like methods, constructors,
instance variables.
Calling parent class method by using super.
Example:
super.parentClassMethodName();
Calling current class method.
Example :
this.currentClassMethodName();
Calling parent class constructor.
Example:
super();
super(100);
Calling current class constructor.
Example:
this();
this(100);
Using parent class variable in child class.
super.a=100;
Using current class variable.
Example:
this.a=100;
 super vs this
Polymorphism
150
Use of super and this keyword
Example 1
class A
{
int temp=10;
void show()
{
System.out.println(“ A Sho w”);
}
}
class B extends A
{
int temp=20;
void show()
{
super.show(); //Use of super to call parent class method
System.out.println(“B Show “);
this.temp=super.temp+this.temp;
}
}
class Test
{
public static void main(String args[])
{
B obj=new B();
obj.show();
}
Polymorphism
151
Example 2 Another use of super and this use
class A
{
A()
{ System.out.println(“A Class Default Constructor Call “); }
A(int a)
{
System.out.println(“A class Parameterized Constructor call “);
}
}
class B extends A
{
B()
{
System.out.println(“B Class Default Constructor Call “);
}
B(int t)
{
super(10); //Use of super to call parent class parameterized constructor and it must be the
first line.
System.out.println(“B Class Parameterized Constructor call “);
}
}
Polymorphism
152
TEST YOUR SELF
Success is the sum of small efforts, repeated day in and day out.
Robert Collier
153
1) What will be the output of the following code?
class A
{
A()
{
this(10);
System.out.println(“A Class Default Constructor “);
}
A(int a)
{
System.out.println(“A class Parameterized Constructor “);
}
}
class B extends A
{
B()
{
System.out.println(“B Class Default Constructor “);
}
public static void main(String args[])
{
B obj=new B(); }
}
Polymorphism
154
Abstract Class
 Abstract class Intro
 Abstract Methods
155
Abstract class
An abstract class never be instantiated. It is used by extending it.
Abstract class has generic methods (Abstract methods) common to all sub –
classes .
Abstract methods are body less methods (Methods Prototypes) and
child classes override the abstract methods.
Example:
abstract class Account
{
public void deposit()
{
}
public void withdraw()
{
}
public void checkBalance()
{
}
public abstract float rateOfInterest();
public abstract String[] services();
}
Abstract class
156
class SavingAccount extends Account
{
public float rateOfInterest()
{
}
public String[] services()
{
}
}
class CurrentAccount extends Account
{
public float rateOfInterest()
{
}
//Now this class become abstract , if you not override all the abstract methods
//of abstract class, your class become abstract too.
}
Abstract class
157
TEST YOUR SELF
The difference between a successful person and others is not a lack of
strength, not a lack of knowledge, but rather a lack in will.
Vince Lombardi
158
1) What will be the output of the following code?
class Account
{
abstract void deposit();
}
class SavingAccount extends Account
{
void deposit()
{
System.out.println(“Deposit Call “);
}
public static void main(String args[])
{
SavingAccount obj=new SavingAccount();
obj.deposit();
}
}
Abstract class
159
2) What will be the output of the following code?
abstract class Account
{
void deposit()
{
System.out.println(“Abstract class Deposit Call “);
}
}
class SavingAccount extends Account
{
void deposit()
{
System.out.println(“Deposit Call “);
}
public static void main(String args[])
{
SavingAccount obj=new SavingAccount();
obj.deposit();
}
}
Abstract class
160
3) What will be the output of the following code?
abstract class Account
{
abstract void deposit();
}
class SavingAccount extends Account
{
void deposit(int a)
{
System.out.println(“Deposit Call “);
}
public static void main(String args[])
{
SavingAccount obj=new SavingAccount();
obj.deposit(11);
}
}
Abstract class
161
Interface
 Interface Introduction
 Interface On Job
 Interface Coding techniques
162
Interface Introduction
163
Interfaces
Interface contains method prototypes (body less methods) and constants.
When you create an interface, you're defining a contract for what a class can do,
without saying anything about how the class will do it.
Interface
164
Interface Example:
interface Animal
{
int LEGS=4; //public static final LEGS=4;
void eat(); //public abstract void eat();
void sound(); //public abstract void sound();
}
class Dog implements Animal
{
public void eat()
{
System.out.println(“EAT MEAT “);
}
public void sound()
{
System.out.println(“BARK “);
}
}
class Cow implements Animal
{
public void eat()
{
System.out.println(“EAT GRASS “);
}
public void sound()
{
System.out.println(“MOO “);
}
}
Interface
Sample Example
165
public interface CustOperation
{
public int insert(Customer obj) ;
public int update(int custid,Customer obj);
public int delete(Customer obj);
public void select(Customer obj) ;
}
NOTE: Create a Customer Bean (Customerid, Customer Name,
Gender, Address , Phone).
 Interface on JOB
Interface
166
 Interface Coding techniques
Example 1:
interface A
{
int x=10; //internally public static final int x=10;
void show(); //convert internally to public abstract void show()
}
interface B extends A
{
void disp(); //public abstract void disp();
}
Example 2:
interface A
{
void show();
}
interface B
{
void disp();
}
interface C extends A,B //Multiple inheritance can be possible using interface.
{
}
Interface
167
Contd.....
Example 3:
interface Animal
{
void sleep();
void eat();
}
interface Pet
{
void faithful();
}
class Dog implements Animal,Pet
{
public void sleep()
{
}
public void eat()
{
}
public void faithful()
{
}
}
NOTE:
1) You implement an interface by properly and concretely overriding all of the
methods defined by the interface.
2) A single class can implement many interfaces.
Interface
168
TEST YOUR SELF
He who has never learned to obey
cannot be a good commander.
Aristotle
169
Test Your Self
1) What will be the output of the following code?
interface X
{
void show();
}
class Y extends X
{
public void show()
{
System.out.println(“Inside Y Show “)
}
}
Interface
170
2) what will be the output of the following code?
interface X
{
void show();
}
class Y implements X
{
void show()
{
System.out.println(“Inside Y Show “);
}
}
Test Your Self contd….
Interface
171
3) what will be the output of the following code?
interface X
{
void show();
}
interface Y implements X
{
void disp();
}
class Z extends Y
{
public void show()
{
System.out.println(“ Inside show “);
}
}
Test Your Self contd….
Interface
172
Exercise:
1) Create an interface CustOperation which have insert, delete, print
methods and a customer class implements CustOperation interface and
overrides it's all methods.
2) Create three interfaces Account interface, Emp interface, Bank interface.
Account interface has emp loan method, leave detail method. Emp interface
has salary calculate method and bank has deposit and withdraw method.
And finally we have a payroll interface which inherit all these interfaces.
And Nucleus class implements all these interfaces.
173
Pass By Value
And
Pass By Reference
174
Pass by Value Pass By Reference
It means passing a primitive variable into
method.
It means passing an object reference to the
method.
Pass by variable means Pass by copy of the
variable.
When you pass an object variable into
method, you must keep in mind that you're
passing the object reference, and not the
actual object it self.
So for the primitive variable, you are always
passing a copy of bits in the variable.
Passing the copy of reference variable to the
method. In other words , both the caller and
the called method will now have identical
copies of the reference, and thus both will
refer to the exact (not a copy ) object on the
heap.
Note: It makes no difference if you're passing primitive or reference variables, you are always passing a
copy of bits in the variable.
175
class X
{
void modify(int x,int y)
{
x++;
y++;
System.out.println(“Value of x is “+x+” and y is “+y);
}
}
class Test
{
public static void main(String args[])
{
X obj=new X();
int a=100,int b=200;
obj.modify(a,b);
System.out.println(“After Modification Values are “+a+” “+b);
}
}
a=100 b=200
x=101 y=201
Pass by value Example
176
Pass By Reference
class X
{
int a,b;
X()
{
a=100;
b=200;
System.out.println(“Inside X Default Constructor “);
}
void modify(X obj)
{
obj.a++;
obj.b++;
System.out.println(“Value of a is “+obj.a+” and b is “+obj.b);
}
}
class Test
{
public static void main(String args[])
{
X temp=new X();
temp.modify(temp);
System.out.println(“Value of a and b inside main “+temp.a+temp.b);
}
}
temp=1080
a=100
b=200
1080
HEAP
obj=1080
177
Static member
 Static Variable
 Static Method
178
Static variable
Value is the same for all instances of the class.
Static variables are shared.
All instances of the same class share a single copy of the static variables.
Note : Instance variables 1 per instance.
Static variables 1 per class
Static member
179
class Emp
{
static int empCount;
private int empno;
Emp()
{
empCount++;
}
public void setEmpno(int empno)
{
this.empno=empno;
}
public int getEmpno()
{
return empno;
}
public static void main(String args[])
{
Emp ram=new Emp();
ram.setEmpno(1001);
Emp shyam=new Emp();
shyam.setEmpno(1002);
}
}
Static example
Static member
Sample Example
180
Static Method
Static methods are same like instance methods, but it is static so it is shareable
to all objects.
Static methods can use only static members or local variables , it cannot use
non – static members.
Static method access directly with-out creating an object of a class.
Example:
class A
{
static void show()
{
System.out.println(“Inside Show “);
}
}
class Test
{
public static void main(String args[])
{
A.show(); } }
Static member
Sample Example
181
TEST YOUR SELF
Static member
Experience is the child of thought, and thought is the child
of action. We cannot learn men from books.
Benjamin Disraeli
182
1) What will be the output of the following code?
class Test
{
int a=100,b=200;
static void add()
{
int c=a+b;
System.out.println(“Sum is “+c);
}
public static void main(String args[])
{
add();
}
}
Static member
183
2) What will be the output of the following code ?
class Test
{
static int a;
int b;
Test()
{
a++;
b++;
System.out.println(“A Value is “+a);
System.out.println(“B Value is “+b);
}
public static void main(String args[])
{
Test obj1=new Test();
Test obj2=new Test();
Test obj3=new Test();
}
}
Static member
184
JDK 1.5
1. Enhance For Loop
2. Var – Args
3. AutoBoxing
4. Static import
5. Annotations
6. Generics
7. Enum
185
Inside JVM
186
A Java virtual machine's main job is to load class files and execute the
bytecodes they contain .
187
JVM Architecture
188
189
190
Data Types in Java
191
Treatment of boolean data type in the Java
When a compiler translates Java source code into bytecodes, it uses ints
or bytes to represent booleans. In the Java virtual machine, false is represented
by integer zero and true by any non-zero integer.
The Java virtual machine works with one other primitive type that is unavailable
to the Java programmer: thereturnAddress type
returnAddress types are pointers to the opcodes of JVM instructions.
192
193
An instance of class java.lang.Class is created by the Java
virtual machine for every type it loads. The virtual machine
must in some way associate a reference to
the Class instance for a type with the type's data in the
method area.
194
Object Representation in Memory
a) Splitting an object across a handle pool and object pool.
Advantage is Heap size is Compact.
Two Reference need to maintain in Heap one for instance data and
other for Method area.
b) Keeping object data all in one place
Only one reference need to maintain in heap is only for the method
area
195
a) Splitting an object across a handle pool and object pool.
196
b) Keeping object data all in one place
197
198
Array Representation in Memory
In Java, arrays are full-fledged objects. Like objects, arrays are always stored on
the heap. Also like objects, implementation designers can decide how they want
to represent arrays on the heap.
Arrays have a Class instance associated with their class, just like any other
object. All arrays of the same dimension and type have the same class. The
length of an array (or the lengths of each dimension of a multidimensional array)
does not play any role in establishing the array's class. For example, an array of
threeints has the same class as an array of three hundred ints. The length of an
array is considered part of its instance data.
The name of an array's class has one open square bracket for each dimension
plus a letter or string representing the array's type. For example, the class name
for an array of ints is "[I"
199
200
Object Creation Steps
201
The Java virtual machine makes types available to the running program through
a process of loading, linking, andinitialization.
1. Loading is the process of bringing a binary form for a type into the Java virtual
machine.
2. Linking is the process of incorporating the binary type data into the runtime
state of the virtual machine.
3. Linking is divided into three sub-steps: verification, preparation,
and resolution.
3.1 Verification ensures the type is properly formed and fit for use by the Java
virtual machine.
3.2 Preparation involves allocating memory needed by the type, such as memory
for any class variables.
3.3 Resolution is the process of transforming symbolic references in the constant
pool into direct references.
Implementations may delay the resolution step until each symbolic reference is
actually used by the running program.
NOTE : After verification, preparation, and (optionally) resolution are completed,
the type is ready for initialization.
Object Creation Steps
202
Garbage Collection
Any garbage collection (GC) algorithm must do two basic things.
First, it must detect garbage objects.
Second, it must reclaim the heap space used by the garbage objects and make
the space available again to the program.
It determining reachability from the roots.
An object is reachable if there is some path of references from the roots by which
the executing program can access the object.
The roots are always accessible to the program. Any objects that are reachable
from the roots are considered "live."
Objects that are not reachable are considered garbage,
203
to determine garbage collection, start your app as –
java –verbose:gc HelloWorld
The output of above change should be something like –
GC 325407K->83000K(776768K), 0.2300771 secs
GC – Indicates that it was a minor collection (young generation).
If it had said Full GC then that indicates that it was a major collection (tenured
generation).
325407K – The combined size of live objects before garbage collection.
83000K – The combined size of live objects after garbage collection.
(776768K) – the total available space, not counting the space in the permanent
generation,
which is the total heap minus one of the survivor spaces.
0.2300771 secs – time it took for garbage collection to occur.
Full GC Example:
[Full GC [Tenured: 3485K->4095K(4096K), 0.1745373 secs] 61244K-
>7418K(63104K), [Perm : 10756K->10756K(12288K)], 0.1762129 secs] [Times:
user=0.19 sys=0.00, real=0.19 secs]
204
Inside Heap
As we know objects are created inside heap memory and Garbage collection
is a process which removes dead objects from Java Heap space and returns
memory back to Heap in Java.
For the sake of Garbage collection Heap is divided into three main regions
named as New Generation, Old or Tenured Generation and Perm space.
New Generation of Java Heap is part of Java Heap memory where newly
created object are stored,
During the course of application many objects created and died but those
remain live they got moved to Old or Tenured Generation by Java Garbage
collector thread.
Perm space of Java Heap is where JVM stores Meta data about classes and
methods, String pool and Class level details.
205
1) objects are created on heap in Java irrespective of there scope e.g. local or member
variable. while its worth noting that class variables or static members are created in method
area of Java memory space and both heap and method area is shared between different
thread.
2) Garbage collection is a mechanism provided by Java Virtual Machine to reclaim heap
space from objects which are eligible for Garbage collection.
3) Garbage collection relieves java programmer from memory management which is
essential part of C++ programming and gives more time to focus on business logic.
4) Garbage Collection in Java is carried by a daemon thread called Garbage Collector.
5) Before removing an object from memory Garbage collection thread invokes finalize ()
method of that object and gives an opportunity to perform any sort of cleanup required.
6) You as Java programmer can not force Garbage collection in Java; it will only trigger if
JVM thinks it needs a garbage collection based on Java heap size.
7) There are methods like System.gc () and Runtime.gc () which is used to send request
of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen.
8) If there is no memory space for creating new object in Heap Java Virtual
Machine throws OutOfMemoryError or java.lang.OutOfMemoryError heap space
9) J2SE 5(Java 2 Standard Edition) adds a new feature called Ergonomics goal of
ergonomics is to provide good performance from the JVM with minimum of command
line tuning.
206
Java Memory Types
207
Java Memory Types
Java objects are created in Heap and Heap is divided into two parts or
generations for sake of garbage collection in Java, these are called as Young
generation or New Generation, Tenured or Old Generation.
Young Generation or New Generation is further divided into three parts
known as Eden space, Survivor 1 and Survivor 2 space.
When an object first created in heap its gets created in new generation inside
Eden space and after subsequent Minor Garbage collection if
object survives its gets moved to survivor 1 and then Survivor 2.
before Major Garbage collection moved that object toOld or tenured
generation.
Old Generation – It has 2 parts Tenured Generation and Permant Generation
(PermGen) . After Surviour2 objects are move to Tenured Generation.
Permanent generation or Perm Area is somewhat special and it is used to store
Meta data related to classes and method in JVM. And only Perm Gen is part of
Non-Heap Memory.
208
There are some GC algorithms which can be used by a Java VM. The following
command line options allow to use a specific GC algorithm:
-XX:+UseSerialGC -> single threaded, young generation, and old generation garbage
collector (should be used only for small Java heap sizes such as -Xmx256m or
smaller)
-XX:+UseParallelGC -> only the young generation space utilizes a multithreaded
(parallel) garbage collector.The old generation space uses a single-threaded
garbage collector.
-XX:+UseParallelOldGC -> both young and old generations use multithread garbage
collector.
-XX:+UseParNewGC -> enables a multithreaded, young generation garbage collector
-XX:+UseConcMarkSweepGC -> enables the VM’s mostly concurrent garbage
collector. It also auto-enables -XX:+UseParNewGC (use if If you are not able to meet
your application’s worst case latency requirements due to full garbage collection
duration being too long)
-XX:+UseG1GC -> garbage first collector (default in java 7, can be also used in latest
releases of java 6)
209
The G1 Garbage Collector
The Garbage-First (G1) collector is a server-style garbage collector, targeted for
multi-processor machines with large memories. It meets garbage collection (GC)
pause time goals with a high probability, while achieving high throughput. The G1
garbage collector is fully supported in Oracle JDK 7 update 4 and later releases.
The G1 collector is designed for applications that:
Can operate concurrently with applications threads like the CMS collector.
Compact free space without lengthy GC induced pause times.
Need more predictable GC pause durations.
Do not want to sacrifice a lot of throughput performance.
Do not require a much larger Java heap.
G1 is planned as the long term replacement for the Concurrent Mark-Sweep
Collector (CMS). Comparing G1 with CMS, there are differences that make G1 a
better solution. One difference is that G1 is a compacting collector. G1 compacts
sufficiently to completely avoid the use of fine-grained free lists for allocation,
and instead relies on regions. This considerably simplifies parts of the collector,
and mostly eliminates potential fragmentation issues. Also, G1 offers more
predictable garbage collection pauses than the CMS collector, and allows users
to specify desired pause targets.
210
Monitoring the Garbage Collection
GC is done by JVM, and since the GC monitoring tools disclose the GC
information provided by JVM, you will get the same results no matter how you
monitor GC.
First, the GC monitoring methods can be separated into CUI and GUI depending
on the access interface. The typical CUI GC monitoring method involves using a
separate CUI application called "jstat", or selecting a JVM option called
"verbosegc" when running JVM.
GUI GC monitoring is done by using a separate GUI application, and three most
commonly used applications would be "jconsole", "jvisualvm" .
211
CUI GC
1. java –verbose:gc HelloWorld
2. Java -XX:+PrintGCDetails HelloWorld
3. Java XX:+PrintGCTimeStamps HelloWorld
2. jstat is a monitoring tool in JVM
jstat –gc <pid>
Where pid is the process id and you can get the java process id.
By using jps command
jstat does not provide only the GC operation information display. It also
provides class loader operation information or Just-in-Time compiler operation
information.
212
GUI GC
1. Java Visual VM is a GUI profiling/monitoring tool.
visualvm_134visualvm_134binvisualvm.exe – to run simple run the exe
file.
213
GUI GC
2. Jconsole
This command comes with jdk
Syntax:
Jconsole <processid>
You can get the process id by using the jps
214
Summary on Garbage collection in Java
1) Java Heap is divided into three generation for sake of garbage collection. These
are young generation, tenured or old generation and Perm area.
2) New objects are created into young generation and subsequently moved
to old generation.
3) String pool is created in Perm area of Heap, garbage collection can occur in
perm space but depends upon JVM to JVM.
4) Minor garbage collection is used to move object from Eden space to
Survivor 1 and Survivor 2 space and Major collection is used to move object
from young to tenured generation.
5) Whenever Major garbage collection occurs application threads stops during
that period which will reduce application’s performance and throughput.
6) There are few performance improvement has been applied in garbage
collection in java 6 and we usually use JRE 1.6.20 for running our application.
7) JVM command line options –Xmx and -Xms is used to setup starting and
max size for Java Heap. Ideal ratio of this parameter is either 1:1 or 1:1.5 based
upon my experience for example you can have either both –Xmx and –Xms as
1GB or –Xms 1.2 GB and 1.8 GB.
8) There is no manual way of doing garbage collection in Java.
215
How to increase size of Java Heap
Default size of Heap space in Java is 128MB on most of 32 bit
Sun's JVM but its highly varies from JVM to JVM.
Maximum 64 MB Perm Space by Default and can extend to 128 MB in 32
Bit Window O/S.
VM options -Xms and -Xmx
java -Xms64m -Xmx256m HelloWorld
Java -XX:PermSize 128m HelloWorld
Java -Xss 1024m HelloWorld
216
217
Java Commands and Usage
Javac command
javac –verbose A.java
Javac –source 1.4 A.java
Javac –cp
Javac –classpath
Javap –verbose
Java –verbose
Java DeCompiler Usage
218
Using Runtime Class for GC and Heap Analysis
Using System Class for GC and System Properties
219
NOTE:
You cannot call this() from methods, only from constructors. If you do call this()in
a constructor, you must call it first, before any other code in the constructor, and
you can only call it once.
Instance initialization methods
When you compile a class, the Java compiler creates an instance initialization
method for each constructor you declare in the source code of the class. Although
the constructor is not a method, the instance initialization method is. It has a
name, <init>, a return type, void, and a set of parameters that match the
parameters of the constructor from which it was generated. For example, given
the following two constructors in the source file for class CoffeeCup:
220
// In source packet in file init/ex8/CoffeeCup.java class CoffeeCup { public
CoffeeCup() { //... } public CoffeeCup(int amount) { //... } // ... } the compiler would
generate the following two instance initialization methods in the class file for
class CoffeeCup, one for each constructor in the source file:
// In binary form in file init/ex8/CoffeeCup.class: public void (CoffeeCup this) {...}
public void (CoffeeCup this, int amount) {...} Note that <init> is not a valid Java
method name, so you could not define a method in your source file that
accidentally conflicted with an instance initialization method. (<init> is not a
method in the Java language sense of the term, because it has an illegal name.
In the compiled, binary Java class file, however, it is a legal method.)
Also, the this reference passed as the first parameter to <init> is inserted by the
Java compiler into the parameter list of every instance method. For example, the
method void add(int amount) in the source file for class CoffeeCup would become
the void add(CoffeeCup this, int amount) method in the class file. The
hidden this reference is the way in which instance methods, including instance
initialization methods, are able to access instance data.
221
OOAD
Object Oriented Analysis and Design
222
We build software to solve problems.
People have problems.
Therefore, we build software for people.
Good software not only solves
immediate problems, but it can be
maintained and modified to address the
inevitable changes that the customer
will want.
223
Three steps to great software
1. Make sure the software
does what the customer
wants
2. Apply good object-oriented
principles
3. Strive for a maintainable,
reusable design
223
224
We create software for a reason.
We create software fro people.
We need to know what the people want in
the software we build.
These are called REQUIREMENTS.
225
1
2
3
4
5
Who provides requirements?
225
We call these people Stakeholders
Customer
End user
Development team members
Management
Technology providers
226
What is a requirement?
226
‣ A requirement is a feature that your system must
have in order to satisfy the customer.
‣ A requirement is something your system must do.
Did we meet the requirements?
227
Define the problem
• Talk to the customer
• Talk to other stakeholders
• Ask questions
• Brainstorm
• Look at the problem from many
points of view
227
228
Improper requirement gathering result
229
Welcome to use cases
•A use case is
– A complete sequence of
steps that provides value to
someone
– Something your system
must do
– Initiated by an Actor
(someone or something not
part of your system)
229
230
230
‣ Provide value
‣ Are complete
‣ Are initiated by an actor
‣ Describe a single goal of the system
‣ Be described by UML diagrams with text
‣ Be formally structured
‣ Be described using a language with formal semantics
‣ Be described by using software tools
Use cases definitely…
Use cases may…
The essence of use cases
231
Parts of a use case
231
Name:
Usually verb-noun (e.g. enroll in course)
Description:
A paragraph or two describing the purpose and value
(results)
Actors:
Name the actor(s) involved
Basic Flow:
The most common or expected path through the use case
Alternate Flows:
Those paths or exceptions that can occur
Preconditions:
Things that must be true before the use case can begin
Postconditions:
Things that must be true when the use case ends
successfully
232
232
And you’re responsible for
changing your programs
233
What might change?
233
Hardware (new and modified)
The use case
The code (implementation and tests)
Technology Upgrade
1
2
3
4
234
THANK YOU !

More Related Content

What's hot (20)

Introduction to java
Introduction to java Introduction to java
Introduction to java
 
JAVA PPT Part-1 BY ADI.pdf
JAVA PPT Part-1 BY ADI.pdfJAVA PPT Part-1 BY ADI.pdf
JAVA PPT Part-1 BY ADI.pdf
 
Introduction of java
Introduction  of javaIntroduction  of java
Introduction of java
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Training on Core java | PPT Presentation | Shravan Sanidhya
Training on Core java | PPT Presentation | Shravan SanidhyaTraining on Core java | PPT Presentation | Shravan Sanidhya
Training on Core java | PPT Presentation | Shravan Sanidhya
 
Java Introduction
Java IntroductionJava Introduction
Java Introduction
 
core java
core javacore java
core java
 
Core java
Core java Core java
Core java
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Features of java
Features of javaFeatures of java
Features of java
 
CORE JAVA
CORE JAVACORE JAVA
CORE JAVA
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core java
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programming
 
Jdk,jre,jvm
Jdk,jre,jvmJdk,jre,jvm
Jdk,jre,jvm
 
JRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVAJRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVA
 
Java Development Kit (jdk)
Java Development Kit (jdk)Java Development Kit (jdk)
Java Development Kit (jdk)
 
Java basic introduction
Java basic introductionJava basic introduction
Java basic introduction
 
Java basic
Java basicJava basic
Java basic
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
 

Viewers also liked

CCHHS HR Recruitment Infographic
CCHHS HR Recruitment InfographicCCHHS HR Recruitment Infographic
CCHHS HR Recruitment InfographicLisa Capozzi
 
GAME PLAN FOR 2017 GENERAL ELECTION MARCH-2015
GAME PLAN FOR 2017 GENERAL ELECTION MARCH-2015GAME PLAN FOR 2017 GENERAL ELECTION MARCH-2015
GAME PLAN FOR 2017 GENERAL ELECTION MARCH-2015samuel mutemi
 
Repere cultural-educative - protectie civila
Repere cultural-educative -  protectie civilaRepere cultural-educative -  protectie civila
Repere cultural-educative - protectie civilaomirel
 
Making your own bootloader
Making your own bootloaderMaking your own bootloader
Making your own bootloaderiamumr
 
Norme psi specifice unitatlor de invatamant 2000
Norme psi specifice unitatlor de invatamant 2000Norme psi specifice unitatlor de invatamant 2000
Norme psi specifice unitatlor de invatamant 2000omirel
 
Soccer for peace
Soccer for peaceSoccer for peace
Soccer for peacesoccerpeace
 
氨回收新技術簡介 140219 2
氨回收新技術簡介 140219 2氨回收新技術簡介 140219 2
氨回收新技術簡介 140219 2h3363989
 
How to dive
How to diveHow to dive
How to divezumoku
 
Konsep teknologi informasi
Konsep teknologi informasiKonsep teknologi informasi
Konsep teknologi informasirenniantika
 
Ordin mai 160 din_2007 planificare svsu
Ordin mai 160 din_2007 planificare svsuOrdin mai 160 din_2007 planificare svsu
Ordin mai 160 din_2007 planificare svsuomirel
 
Completed MSc TESOL dissertation_Xi ZHU
Completed MSc TESOL dissertation_Xi ZHUCompleted MSc TESOL dissertation_Xi ZHU
Completed MSc TESOL dissertation_Xi ZHUXi Zhu
 
Actify's Product solution Presentation in Simplified Chinese
Actify's Product solution Presentation in Simplified ChineseActify's Product solution Presentation in Simplified Chinese
Actify's Product solution Presentation in Simplified ChineseAlen Kuo
 
It cloud services
It cloud servicesIt cloud services
It cloud serviceszumoku
 
Ordin MAI nr.-195-din- 2007 criterii SVSU
Ordin MAI  nr.-195-din- 2007 criterii SVSUOrdin MAI  nr.-195-din- 2007 criterii SVSU
Ordin MAI nr.-195-din- 2007 criterii SVSUomirel
 
Ordin MIRA195 svsu criterii svsu si spsu
Ordin MIRA195 svsu criterii svsu si spsuOrdin MIRA195 svsu criterii svsu si spsu
Ordin MIRA195 svsu criterii svsu si spsuomirel
 

Viewers also liked (20)

CCHHS HR Recruitment Infographic
CCHHS HR Recruitment InfographicCCHHS HR Recruitment Infographic
CCHHS HR Recruitment Infographic
 
GAME PLAN FOR 2017 GENERAL ELECTION MARCH-2015
GAME PLAN FOR 2017 GENERAL ELECTION MARCH-2015GAME PLAN FOR 2017 GENERAL ELECTION MARCH-2015
GAME PLAN FOR 2017 GENERAL ELECTION MARCH-2015
 
Repere cultural-educative - protectie civila
Repere cultural-educative -  protectie civilaRepere cultural-educative -  protectie civila
Repere cultural-educative - protectie civila
 
Reglamento del aprendiz sena
Reglamento del aprendiz sena Reglamento del aprendiz sena
Reglamento del aprendiz sena
 
Making your own bootloader
Making your own bootloaderMaking your own bootloader
Making your own bootloader
 
Anika
AnikaAnika
Anika
 
Norme psi specifice unitatlor de invatamant 2000
Norme psi specifice unitatlor de invatamant 2000Norme psi specifice unitatlor de invatamant 2000
Norme psi specifice unitatlor de invatamant 2000
 
Soccer for peace
Soccer for peaceSoccer for peace
Soccer for peace
 
氨回收新技術簡介 140219 2
氨回收新技術簡介 140219 2氨回收新技術簡介 140219 2
氨回收新技術簡介 140219 2
 
How to dive
How to diveHow to dive
How to dive
 
Konsep teknologi informasi
Konsep teknologi informasiKonsep teknologi informasi
Konsep teknologi informasi
 
Ordin mai 160 din_2007 planificare svsu
Ordin mai 160 din_2007 planificare svsuOrdin mai 160 din_2007 planificare svsu
Ordin mai 160 din_2007 planificare svsu
 
Completed MSc TESOL dissertation_Xi ZHU
Completed MSc TESOL dissertation_Xi ZHUCompleted MSc TESOL dissertation_Xi ZHU
Completed MSc TESOL dissertation_Xi ZHU
 
Actify's Product solution Presentation in Simplified Chinese
Actify's Product solution Presentation in Simplified ChineseActify's Product solution Presentation in Simplified Chinese
Actify's Product solution Presentation in Simplified Chinese
 
Eğiticinin Eğitimi Uygulama Sınavı Ör.
Eğiticinin Eğitimi Uygulama Sınavı Ör.Eğiticinin Eğitimi Uygulama Sınavı Ör.
Eğiticinin Eğitimi Uygulama Sınavı Ör.
 
It cloud services
It cloud servicesIt cloud services
It cloud services
 
00
0000
00
 
Ordin MAI nr.-195-din- 2007 criterii SVSU
Ordin MAI  nr.-195-din- 2007 criterii SVSUOrdin MAI  nr.-195-din- 2007 criterii SVSU
Ordin MAI nr.-195-din- 2007 criterii SVSU
 
Ordin MIRA195 svsu criterii svsu si spsu
Ordin MIRA195 svsu criterii svsu si spsuOrdin MIRA195 svsu criterii svsu si spsu
Ordin MIRA195 svsu criterii svsu si spsu
 
ANTI CORRAPTION
ANTI CORRAPTIONANTI CORRAPTION
ANTI CORRAPTION
 

Similar to Introduction to java

Similar to Introduction to java (20)

Object Oriented Programming-JAVA
Object Oriented Programming-JAVAObject Oriented Programming-JAVA
Object Oriented Programming-JAVA
 
JAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptxJAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptx
 
JAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptxJAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptx
 
Java -lec-1
Java -lec-1Java -lec-1
Java -lec-1
 
Java ms harsha
Java ms harshaJava ms harsha
Java ms harsha
 
Java
JavaJava
Java
 
Java chapter 1
Java   chapter 1Java   chapter 1
Java chapter 1
 
Java unit 1
Java unit 1Java unit 1
Java unit 1
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
Java ppt1
Java ppt1Java ppt1
Java ppt1
 
Learn Java Part 1
Learn Java Part 1Learn Java Part 1
Learn Java Part 1
 
Java session2
Java session2Java session2
Java session2
 
Java Lecture 1
Java Lecture 1Java Lecture 1
Java Lecture 1
 
Introduction java programming
Introduction java programmingIntroduction java programming
Introduction java programming
 
UNIT 1.pptx
UNIT 1.pptxUNIT 1.pptx
UNIT 1.pptx
 
Java basics
Java basicsJava basics
Java basics
 
Presentation on Java Basic
Presentation on Java BasicPresentation on Java Basic
Presentation on Java Basic
 
Java - At a glance
Java - At a glanceJava - At a glance
Java - At a glance
 
JAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptxJAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptx
 
Unit1 JAVA.pptx
Unit1 JAVA.pptxUnit1 JAVA.pptx
Unit1 JAVA.pptx
 

Recently uploaded

Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdfKamal Acharya
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARKOUSTAV SARKAR
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdfKamal Acharya
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdfKamal Acharya
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
Computer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersComputer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersMairaAshraf6
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxmaisarahman1
 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...soginsider
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxJuliansyahHarahap1
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaOmar Fathy
 
Bridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptxBridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptxnuruddin69
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Servicemeghakumariji156
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwaitjaanualu31
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsvanyagupta248
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...HenryBriggs2
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptNANDHAKUMARA10
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapRishantSharmaFr
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesRAJNEESHKUMAR341697
 

Recently uploaded (20)

Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Computer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersComputer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to Computers
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Bridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptxBridge Jacking Design Sample Calculation.pptx
Bridge Jacking Design Sample Calculation.pptx
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 

Introduction to java

  • 1. 1 Introduction to Java Presented by Amit Srivastava Java Duke Java 6 Mustang Java is one of the slang terms for coffee Java 7 Dolphin
  • 2. 2 Agenda 1. Java Introduction 2. Java Basics 3. Object Oriented Basics (OO Basics) 4. Using Constructor and Finalize 5. IS-A and HAS-A 6. Polymorphism, Abstract class and interfaces 7. Pass By Value & Pass By Reference 8. All About Static 9. Deep Inside JVM 10. OOAD
  • 3. 3 Java Introduction  What is Java  Java History  WORA  Java Kick Start  The way Java Works  Writing First Java Program
  • 4. 4 The Power of Java Java software powers the onboard computers in toys, cars, planes, rockets, and even the NASA (National Aeronautics and Space Administration/Agency ) Mars Rover. It brings interactivity to the Internet, real-time graphics to television, instant imaging to cameras, and multi-player games to mobile phones and desktop PCs. It connects the largest enterprises and smallest businesses to their employees, customers, and data. And it secures the vast majority of electronic transactions in retail, finance, government, science, and medicine. In short, Java technology goes everywhere you go
  • 5. 5 A Mars rover is an automated motor vehicle which propels itself across the surface of the planet Mars after landing. Rovers have several advantages over stationary landers: they examine more territory, they can be directed to interesting features, they can place themselves in sunny positions to weather winter months.
  • 6. 6 Java software runs on more types of consumer and embedded devices, smart cards, ATMs, thin clients, PCs, servers, and mainframes than any other software. Today's six million Java developers are one of the largest communities of software developers. The Java economy includes 2.5 billion smart cards, 800 million PCs shipped with Java, 1.85 billion Java Powered phones , and over 180 telecom providers who deploy Java technology based content/services. The Power of Java
  • 7. 7  WHAT IS JAVA?  Object Oriented Programming  WORA( Write Once Run any where) or Platform Independence  The Java language was created by James Gosling in June 1991.  Java Provides development and deployment environment.  It is similar in syntax to C++  It is robust provides exception handling , automatic garbage collection.  Designed for the distributed environment.  Supports Multithreading  Secure ( No Pointer and Byte Code Verifier)  Architectural Neutral - If a company develops new hardware , it doesn’t have to make a new software , only JRE needs to be replace for New platform).  Open Source  High Performance (JITc) Java Introduction
  • 8. 8 what is the mean of platform? Platform consists of the computer hardware(mainly architecture of the microprocessor) and OS. Platform=hardware+Operating System Anything that is platform indepedent can run on any operating system and hardware. Java is platform indepedent so java can run on any operating system and hardware. Now question is how it is platform independent? This is because of the magic of Byte Code which is OS indepedent. When java compiler compile any code then it generate the byte code not the machine native code(unlike C compiler).Now this byte code need a interpreter to execute on a machine. This interpreter is JVM.So JVM read that byte code(that is machine indepedent) amd execute it. Different JVM is designed for different OS and byte code is able to run on different OS.
  • 9. 9  JAVA HISTORY  Green Project (1991) was designed for hand-held devices and set-top boxes. (Requirement was the hardware in the consumer devices was always changing but the same code use on the different hardware systems)  It was originally named as Oak but became unsuccessful, so in 1995, Sun changed its name to JAVA  James Gosling's goals were to implement a virtual machine and a language that had a familiar C/C++ style of notation. The first public implementation was Java 1.0 in 1995. It promised "Write Once, Run Anywhere" (WORA). Note : The initial version of Java is so small it fit in a floppy. Now it of 60+MB. Java Introduction
  • 10. 10 Java Introduction  JAVA HISTORY continue…
  • 11. 11 JDK 1.0.2 JDK 1.1 JDK 1.2 JDK 1.5 JDK 1.6 JDK 1.7 Oak ------ Playground 1.2 Kestrel 1.3 Merlin 1.4 Tiger Mustang Dolphin 250 Classes 500 Classes 2300 Classes 3500 Classes 3793 Classes 4024 Classes 23 Jan 96 19 Feb 97 8 Dec 98 (1.2) 8 May 2000 (1.3) 6 Feb 2002 (1.4) 30 Sept 2004 11 Dec 2006 28 July 2011 you could use private and protected together to create yet another form of protection that would restrict access to methods or variables solely to subclasses of a given class. As of 1.0.2, this capability has been removed from the language. Extensive AWT RMI Inner Classes JavaBeans JDBC Reflection JDK 1.2 Strictfp Swing CORBA Collection FW JDK 1.3 Java Sound JNDI Java 1.4 Assert XML Parser Security and Cryptography Enhance for Loop Var-Args Generics AutoBoxing Static import Java Compiler API Splash Screen System Tray Icon Instrument Class (For Object Size) Switch with String Numeric Literal with Underscore Improved Generics Catching multiple Exception New Java NIO Java Version Histroy
  • 12. 12 JDK 1.8 JDK 1.9 JDK 1.10 Lambda ------ Sept 2013 ---- ----- Improvement in java.lang package Parallel Array Sorting Bulk Data Operations for Collections Base64 Encoding and Decoding New HTTP Client More Security enhancements from the language MultiGiga bytes Heap Self Tuning JVM Remove Primitive data types Move Towards 64 Bit Addressing
  • 13. 13  WORA The goal is to write an application which run anywhere. Java Introduction
  • 15. 15  JAVA KICK START 1. JDK (Java Development Kit) JDK = javac compiler + .jar (libraries) + javadoc + jdb + JRE JDK – JDK is a software package which is used to develop and deploy java applications. JDK consists a) javac compiler – it is use to convert .java file into .class file b) JAR Files - A jar files are java API’s , which contains number of classes and interfaces. For Example to make a database connection with oracle we require ojdbc.jar. c) Javadoc – through this utility we can make Java documentaion for any java program. d) Jdb- jdb is a java debugger. e) JRE – See in the next slide Java Introduction
  • 16. 16  JAVA KICK START continue… Java Introduction 2. JRE (Java Runtime Environment)- A JRE is required to run Java applications interpretively on a target hardware and operating system platform. JRE=JVM (Java Virtual machine)+ jar files (libraries) Java Program execution flow
  • 17. 17 Java Introduction  JAVA KICK START continue… 3. JVM JVM is a software that is plat form specific. For example for Linux platform You require a Linux based JVM , for windows platform you require a windows based JVM. Now in these days JVM is bundled with Internet explorer and With other types of browsers.
  • 18. 18 A JVM performs the following tasks. 1. Class Loader Load all the .class file, necessary for the execution of a program. 2. Byte code Verifier It ensures the code does not no illegal data conversion, no stack over flow, not violate system integrity. 3. JIT – (Just In time compiler) JIT work as a cache for the JVM interpreted code. It memorized the repeated code instructions (that is interpreted by the JVM) and when JVM reqiure the same set of instructions so JIT provides these instructions to the JVM , so JVM does not interpret the same instructions again 4. Generate Native Code- The JVM and the Java API are built for every O/S platform. The Java API calls to the O/S API.  JAVA KICK START continue… Java Introduction
  • 19. 19 Java Introduction In particular, a Java program, unlike one written in C or C++, isn't a Single executable file, but instead is composed of many individual class files, each of which corresponds to a single Java class. Additionally, these class files are not loaded into memory all at once, but rather are loaded on demand, as needed by the program. The ClassLoader is the part of the JVM that loads classes into memory. a) BootStrap or Primordial or Default or System Class Loader – It is a part of the JVM Implementation. It loads the classes, including the classes of Java API. b) User-Defined Class Loader- A Java Application can install user-define class loader that load classes in the custom ways, such as by downloading class files across a network.  JAVA Class Loader
  • 20. 20 Types of Class Loader in Java a) BootStrap Class Loader - Bootstrap class loader loads java’s core classes like java.lang, java.util etc. These are classes that are part of java runtime environment. Bootstrap class loader is native implementation and so they may differ across different JVMs. The bootstrap class loader loads the core Java libraries located in the <JAVA_HOME>/jre/lib directory, search for rt.jar . b) Extension Class loader - classes in JAR files in the lib/ext directory of the JRE, and in the system-wide, platform-specific extension directory (such as /usr/jdk/packages/lib/ext on the Solaris™ Operating System, but note that use of this directory applies only to Java™ 6 and later c) System Class Loader - The class path: classes, including classes in JAR files, on paths specified by the system property java.class.path. If a JAR file on the class path has a manifest with the Class-Path attribute, JAR files specified by the Class-Path attribute will be searched also. By default, the java.class.path property's value is ., the current directory. You can change the value by using the -classpath or -cp command-line options, or setting the CLASSPATH environment variable. The command-line options override the setting of the CLASSPATH environment variable.
  • 21. 21  The Way Java Works Java Introduction
  • 22. 22  Writing First Java Program Step -1 Write Source Code Example: class A { public static void main(String args[]) { System.out.println(“Hello Java ! “); } } Step- 2 Save Code with class Name A.java Step-3 Compile the code javac A.java ( when you compile the code it will generate an intermediate code (Byte code) it is not a machine code. Step-4 run the Program java A ( running the program by starting the JVM with the A.class. The JVM translates the bytecode into something the underlying platform understands , and runs your program. Execution point of java program Java Introduction
  • 24. 24 System Class In - System.in Out - System.out.println() Err – System.err.println() Shorten the System.out.println() Import static java.lang.System.out; out.println(“Hello Java ! “);
  • 25. 25 1. Do you know through System.out.println(), You can write the output in a file instead of writing on a Console. 2. You can print output in a different language , like in Hindi in Java 3. You can get the Login User Name , Operation System Name, JDK Location, Number of Processor in a System and many more. 4. Request to the Java Garbage Collector 5. You can not create an object of System class 6. Performance Monitoring of a Method 7. Introduce the printf method Example: String name ="Amit"; int age =21; System.out.printf("Your Name is %s and Age is %d",name,age); char gender ='M'; System.out.printf("nGender is %c ",gender); float amount = 12000.50f; System.out.printf("nAmount is %f",amount); System.out.printf("nAmount is %6.2f",amount); The Magic of System class
  • 26. 26 Program Observation When the JVM starts running , it looks for the class that is at the command line. Then it starts looking for a specially written method that looks exactly like: public static void main(String args[]) { //Your Code Here } Note: Every Java application has to have at least one class, and at least one main method. Java Introduction
  • 27. 27 Program Observation continue… You can define main method in the following ways a) public static void main(String args[]) b) static public void main(String args[]) c) public static void main(String …a) // Allowed in JDK 1.5 or higher d) static public void main(String …a) //Allowed in jdk1.5 or higher The main method is public , because java is package centric language. Now JVM has to access your main method from outside your package. That’s why it set to as public The main method also static , because static is loaded on the compile Time and not required to instantiate. The main method is void , because it is not required to return any thing to the JVM. Main is the name of the method String args[] is used for command line arguments , where String is a Java class. Java Introduction
  • 28. 28 Java Introduction Program Observation continue… System.out.println(“Hello Java ! ”); Where System is a final class, found in java.lang package. Out is a object of PrintStream class and it declare static in the System Class. Println(String msg) this is a method define in the PrintStream class. Used to print on console and print in new line
  • 29. 29 Java Basics  Identifier  Variable  Constant  Keyword  Data Types  Java Coding Conventions  Sequential Programs  Conditional Programs  Looping
  • 30. 30 Identifier It is a name given to a class, variable, constant or method. Rules for Declaring a Legal Identifier: a) Identifier must start with a letter, $, _. Cannot start with number. b) After the first letter, contain numeric. c) No Limit to the number of characters an identifier can contain. d) Cannot use keyword in identifier name. e) Identifiers are case-sensitive. Java Basics
  • 31. 31 Variable A variable is just like a cup or container. It can hold something. It has a size and a type. Example: int a=123; a Java Basics Sample Example
  • 32. 32  Constant As the name implies , constants are fixed values which never change. Example: final int MAX=100; “final” keyword is used to declare a constant in java.  Keywords Keywords are reserved which has some special meaning for the compiler. For Example : if , while ,int etc. Java Basics Sample Example
  • 34. 34  Data types Variable (Cup) can be of two type ✔Primitive Type ✔Reference Type Primitive Type – Primitives are like the cups at the Coffee-House They come in different sizes and each has name like small , big, medium. Java Basics
  • 35. 35 Primitive Type Example byte x=10; // Take 1 byte in memory short y=500; // Take 2 bytes in memory int a=40000; // Take 4 bytes in memory Java Basics
  • 36. 36 Primitive Data Types List In Java, primitives come in different sizes with different names. When you declare a variable in Java, you must declare with a specific type. Java Basics Data Type Bytes Range boolean : Internally java treat is 1 for true and 0 for false, and dependent on OS itcan be treated as byte, short, int) True or false char 2 Bytes (UNICODE Characters) 0 to 65535 byte 1 byte -128 to 127 short 2 bytes -32768 to 32767 int 4 bytes -2147483648 to2147483647 long 8 bytes huge float 4 bytes varies double 8 bytes varies
  • 37. 37 TEST YOUR SELF Java Basics I am a slow walker, but I never walk back. Said by Abraham Lincoln
  • 38. 38 Test Your Self 1. Declare a variable, in which store age of Employee, choose the best way a) int age; b) short age; c) long age; d) boolean age; e) byte age; 2. To declare constant in java a) const int a=10; b) int a=10; c) final int A=10; d) byte a=10; 3. To store the attendance status of employee , whether Employee is present or not. Which deceleration is appropriate. a) boolean att; c) float att; b) int att; d) double att; Java Basics
  • 39. 39 Test Your Self 4. Which one is the correct variable deceleration , choose all that apply a) int _a; b) int _____a; c) int 1a; d) int emp_no; e) float @sal; f) float $sal; g) double $_bonus; h) boolean int; Java Basics
  • 40. 40 Reference type A Reference variable holds bits that represents a way to access an object. It doesn't hold the object itself, but it holds something like a pointer, or an address. Java Basics
  • 41. 41 b JAVA Reference Type Example: String b=”Java”; Java Basics
  • 42. 42 Primitive Type Example int a=100; int b=200; int c=a; 100 200 a b 100 c Memory Area Java Basics Primitive Vs Reference Type
  • 43. 43 Java object reference World object reference Java object reference a b c Java World Reference Type Example String a=new String(“Java”); String b=new String(“World”); String c=a; Java Basics Primitive vs Reference Type
  • 44. 44 Using == with primitive type Example int a=100; int b=100; System.out.println(a==b); //print true Using == with reference type Example: String a=new String(“Hello”); String b=new String(“Hello”); System.out.println(a==b); // false But Why ??? Answer is, The reference type checks address in this case , it return true if both address or references are same. So HOW I COMPARE VALUES IN REFERENCE TYPE, BECAUSE == CHECKS ADDRESS NOT VALUE? Answer is using equals() System.out.println(a.equals(b)); //return true Java Basics
  • 45. 45 TEST YOUR SELF Java Basics There is nothing impossible to him who will try. Said by Alexander the Great
  • 46. 46 Test Your Self 1) What will be the output of the following code? String a=new String(“Hello”); String b=new String(“Hello”); if(a.equals(b)) System.out.println(“Same “); else System.out.println(“Not Same “); Java Basics
  • 47. 47 Test Your Self contd… 2) What will be the output of the following code? String a=new String(“Hello”); String b=new String(“Hello”); String c=a; String d=b; if(a==c) System.out.println(“Same Reference “); else System.out.println(“Not Same Reference “); if(b==d) System.out.println(“Same b and d Reference“); else System.out.println(“Not Same b and d reference “); Java Basics
  • 48. 48 Java Coding Convention Class and Interfaces – The First letter should be capital, and first letter of the inner words should be Capital. Example : Account PrintWriter Emp Methods – The First Letter should be lowercase, and then normal camelCase rules should be used. Example : getBalance setCustomerName Variables – Same rule as Method Rule Constants – All in Uppercase. Example : MIN_HEIGHT Java Basics
  • 49. 49 What can you say in the main method? •Write Sequential Statements •Conditional Branching •Looping Java Basics
  • 50. 50  Writing Sequential Statements Example: class Test { public static void main(String args[]) { int a,b,c; //declaring primitive variables a=100; b=200; c=a+b; System.out.println(“Sum is “+c); } //main close } //class close Java Basics
  • 51. 51 Exercise: To Do YourSelf 1) WAP to swap two numbers. 2) WAP to calculate simple interest 3) WAP to calculate area and perimeter of a rectangle 4) WAP to calculate net salary of employee, take basic salary of employee and calculate Hra 30% of basic salary, DA 20% of the basic salary, Ta 10% of the basic salary and net salary is sum up of basic salary+ allowances-pf. Pf is 1400 fix. Note : Follow Java Conventions during coding Java Basics
  • 52. 52 Java Decision Making Statements 1) Using if-else 2) Using switch Java Basics
  • 53. 53  Decision Making Programs Example 1 class Test { public static void main(String args[]) { int a,b; a=100; b=200; if(a>b) //required boolean true or false System.out.println(“A is Greater “); else System.out.println(“B is Greater “); } } Java Basics
  • 54. 54 class Test { public static void main(String args[]) { int a=2; switch(a) { case 1: System.out.println(“Sunday “); break; case 2: System.out.println(“Monday “); break; case 3: System.out.println(“Tuesday”); break; case 4: System.out.println(“Wednesday “); break; case 5: System.out.println(“Thursday “); break; case 6: System.out.println(“Friday “); break; Java Basics Example 2: case 7: System.out.println(“saturday “); break; default: System.out.println(“Invalid Day “); } } } Note: Switch only allowed int ,byte, char type
  • 55. 55 TEST YOUR SELF Your Purpose in life is to find your purpose and give your whole heart and soul to it. Said by Buddha
  • 56. 56 Test Your Self Java Basics 1) What will be the output of the following code? class Test { public static void main(String args[]) { int a=10; if(a=20) System.out.println(“TRUE”); else System.out.println(“False “); } } a) Print TRUE b) Print False c) Compilation Fail d) None of these
  • 57. 57 2) What will be the output of the following code? class Test { public static void main(String args[]) { String name=”Mike”; int age=21; if((name.equals(“Mike”)) && age>=21) System.out.println(“Welcome “+name); else System.out.println(“Bye “+name); } } Test Your Self contd… Java Basics
  • 58. 58 3) What will be the output of the following code? class Test { public static void main(String args[]) { int color=2; switch(color) { case 1: System.out.println(“RED “); default: System.out.println(“GREEN”); case 3: System.out.println(“BLUE”); } } } Test Your Self contd… Java Basics
  • 59. 59 4) What will be the output of the following code? class Test { public static void main(String args[]) { int color=2; switch(color) { case 1: System.out.println(“RED “); break; default: System.out.println(“GREEN”); break; case 3: System.out.println(“BLUE”); break; }}} Test Your Self contd… Java Basics
  • 60. 60 Exercise: 1) Find out entered number is Positive or Negative Number. 2) Find out the grade , according to given percentage of the user. >=90 print A Grade 89 to 70 B Grade 69 to 50 C Grade <50 D Grade Java Basics
  • 61. 61 3) A Insurance Company have a following polices (Insurance Premium Calculation program) User Input : Person Name Person gender Person Age Person city (Metro or Non-Metro) Conditions: if person age is 25 to 35 and gender is male and city is metro , Output is Premium is 6% if person age is 25 to 40 and gender is male and city is non-metro, Output is Premium 4% if person age is 25 to 42 and gender is female and city is Metro, Output is Premium 3% if person age is 25 to 45 and gender is female and city is non-metro , output is Premium 2% else Not Insured Exercise: contd… Java Basics
  • 62. 62 When you want to repeat something for definite number of times, it is called loop. Java has three basic loops a) for b) while c) do-while. In JDK 1.5 java introduce one more loop called Enhance for loop. Java Basics  LOOPING
  • 63. 63  JAVA LOOPS EXAMPLE class Test { public static void main(String args[]) { int i=1; while(i<=10) //Need boolean test { System.out.println(“While Loop Value of i is “+i); i++; } for(i=1;i<=10;i++) { System.out.println(“For Loop Value of i is “+i); } i=10; do { System.out.println(“Do While Value of i is “+i); }while(i<10); } } Java Basics
  • 64. 64 Enhance For Loop Enhance for loop introduced in JDK 1.5 version Example: int a[]= {10,20, 30, 40, 50}; for(int x: a) { System.out.println(x); } Java Basics
  • 65. 65 TEST YOUR SELF I hated every minute of training but I said, ‘Don’t quit. Suffer now and live the rest of your life as a Champion. Said by Muhammad Ali
  • 66. 66 Test Your Self 1) What will be the output of the following code class Test { public static void main(String args[]) { for(int i=1;i<=3;i++) { for(int j=1;j<=3;j++) { System.out.println(“Value of i is “+i +” Value of j is “+j); } //j for loop close } //i for loop close } //main close } //class close Java Basics
  • 67. 67 Test Your Self contd… 2) What will be the output of the following code? class Test { public static void main(String args[]) { String names [] = {“Ram”, “Shyam”, “Mohan”, “Sohan”}; for(int temp: names) { System.out.println(temp); } } } Java Basics
  • 68. 68 Java Basics Test Your Self contd… 2) What will be the output of the following code? class Test { public static void main(String args[]) { for(int i=1;i<=3;i++) { for(int j=1;j<=3;j++) { if(i==j) continue; else System.out.println(“Value of i is “+i +” Value of j is “+j); } } } }
  • 69. 69 Exercise: 1) WAP to count even number and odd number between 1 to 100. 2) WAP to count prime number between 1 to 100. 3) WAP to print sum of 1+2+3+.............................n 4) WAP to print sum of 12+22+32+..........................n2 Java Basics 5) Now i want to improve the functionality of the “Insurance Premium Calculation program”. Take the input of user details like name, gender, city and age, until user enters “No”. If user enters ‘No’, then exit from the loop, else continue in the loop. Take input again and check if eligibility for the insurance is there or not , also count how many users are eligible and how many are not.
  • 70. 70 Object Oriented Basics (OO Basics)  OO and Procedural Programming WAR  Object Oriented Features
  • 71. 71 A programmer primary task is to write software to solve a problem. Many programming models have evolved to help programmers in being more effective. Procedural Programming One way of solving a problem is to break it down into smaller parts and solve each of the smaller parts. Then aggregate (collate) all the parts to solve the overall problem. Think of each small part as task, to perform which you write a block of code is called function. You can call one function from another. This approach in software development is called process centric or Procedural. For Example: Procedural Programming
  • 72. 72 Drawbacks of Procedural Programming 1. The code are so interdependent (due to one function call to another function) , so one application code cannot be used in another application. 2. Interdependence between the modules so it is inflexible to change, So maintaince is not easy. 3. This approach only good , if software engineer knows every aspects of project. 4. Not on Real world approach 5. Not good to solve large and complex problems Procedural Programming
  • 73. 73 An Object Oriented programming Object oriented programming works on object instead of functions. An object is a real world entity. For Example: Cat , Car , Ball are some of the examples of real world objects An object represents two things a) State – Dog has 4 legs , 1 tail , 2 ears . It shows the dog state b) Behavior- are the functions or methods , that uses the state and shows behavior of an object. For example : dog jumps, so for this it is depend on legs Now we take some more example Amit is working as a Employee in Xyz Ltd. So Amit represents an object of type Employee. His states are empno is1010, Name is Amit Srivastava, Age is 27, and it’s behavior are Attendance details, work details, salary calculation etc. OO Basics
  • 74. 74 Object Oriented Programming and Procedural Programming WAR OO Basics
  • 76. 76 Add one more shape in your current program Contd..... OO Basics
  • 81. 81 Conclusion of the Story In Object Oriented Programming , Developer divide the problem into different objects , instead of breaking the problem into functions (methods). The Object is a real world entity. For Example: Amit is an object of class Employee Royal Enfield is an object of Motor Bike Object = State + Behavior State represents the data items , for example : State of Amit are Empno, Name , Age , Gender, Deptno , PhoneNo etc. Behavior represents the functions (methods) . For example : work details, attendance details, salary calculation etc.
  • 82. 82 Object Oriented Features 1) Encapsulation Encapsulation - Binding “Data and Method” into a single unit and good encapsulation is when your Data is private/protected and your methods are public. Example of Encapsulation is Human Brain, Capsule. OO Basics class Emp { int empno; //DATA String name; float sal; void input() //METHOD { empno=1001; name=”MIKE”; sal=9090.00f; } void show() { System.out.println(“Empno is “+empno); System.out.println(“Name is “+name); System.out.println(“Sal is “+sal); } }
  • 83. 83 2) Abstraction- Working on the essential things and to forget the things which are not essential for us. For Example : If i drive my car from my house to market, so i have to know how to use brakes, accelerator, gear, steering, horn , clutch etc., i don't need to know internal working of these things. Example of Abstraction in Java is abstract classes, interfaces. Contd..... OO Basics HyperLink
  • 84. 84 3) Inheritance - Used to show parent - child relationship like one class inherit the features of the other class, so it provide you the code reusability. For Example: A CAR IS A Vehicle, it means CAR inherits the feature of Vehicle like brakes, wheels, horn, clutch etc. Contd..... OO Basics
  • 85. 85 Inheritance Example: class Account { int accountno; float balance; void deposit() { } void withdraw() { } } class SavingAccount extends Account { float rateOfInterest; void calculateRoi() { } } OO Basics
  • 86. 86 4) Polymorphism- One thing having several forms. Example: All Animals are eating, but each type has different eating habits like Dog eats Meat, Cow eats grass etc. Example: In a calculator we can add two Integer, two real number, three numbers so a same method name is used to add two numbers, three numbers, four numbers, two int numbers , two float numbers etc. This term is called “Method Overloading”. Sample Code: void add(int x,int y) { System.out.println(x+y); } void add(float x,float y) { System.out.println(x+y); } void add(int a,int b,int c) { System.out.println(a+b+c); } Object Oriented Features Contd...... OO Basics
  • 87. 87 5) Class- Contains state (instance variables) and behaviour (methods). A template that describes the kinds of state and behaviour that objects of its type support. 5.1) State (Instance variables) – Each Object (instance of a class) will have its own unique set of instance variables as defined in the class. 5.2) Behaviour (Methods) – Methods are where the class logic is stored, and it work on instance variables. 6) Object – Is an instance of a class. When JVM encounters the new keyword, it will use the same class to make an object. That Object will have its own states, and access to all of the behaviour defined by it's class. Contd...... OO Basics
  • 88. 88 Example: Creating class and Object class Emp { int empno; //Instance variables String name; float sal; void input(int eno,String ename,float esal) //Methods { empno=empno; name=ename; sal=esal; } void show() { System.out.println(“Empno is “+empno); System.out.println(“Name is “+name); System.out.println(“Sal is “+sal); } public static void main(String args[]) { Emp ram=new Emp(); //Creating a new object, a new operator is used to allocate a memory for the object. ram.input(1001,”Ram “, 9090.0f); ram.show(); Emp shyam =new Emp(); shyam.input(1002,”Shyam”,8888.0f); shyam.show(); } } OO Basics Sample Example
  • 89. 89 Memory Representation of Emp Class Object empno=1001 name sal=9090.0f MIKE obj OO Basics Sample Example
  • 90. 90 General formula for calculating memory usage In general, the heap memory used by a Java object in JVM consists of: an object header, consisting of a few bytes of "housekeeping" information; "housekeeping" information, such as recording an object's class, ID and status flags such as whether the object is currently reachable, currently synchronization-locked etc. memory for primitive fields, according to their size memory for reference fields (4 bytes each); padding: potentially a few "wasted" unused bytes after the object data, to make every object start at an address that is a convenient multiple of bytes and reduce the number of bits required to represent a pointer to an object. In Hotspot, every object occupies a number of bytes that is a multiple of 8. If the number of bytes required by an object for its header and fields is not a multiple 8, then you round up to the next multiple of 8.
  • 91. 91 This means, for example, that: a bare Object (With no instance Variable) takes up 8 bytes; an instance of a class with a single boolean field takes up 16 bytes: 8 bytes of header, 1 byte for the boolean and 7 bytes of "padding" to make the size up to a multiple of 8; an instance with eight boolean fields will also take up 16 bytes: 8 for the header, 8 for the booleans; since this is already a multiple of 8, no padding is needed; an object with a two long fields, three int fields and a boolean will take up: 8 bytes for the header; 16 bytes for the 2 longs (8 each); 12 bytes for the 3 ints (4 each); 1 byte for the boolean; a further 3 bytes of padding, to round the total up from 37 to 40, a multiple of 8.
  • 92. 92 Object Size get in Java package com.example.demo public class MyAgent { public static void premain(String args, Instrumentation inst) { SomeClass obj = new SomeClass(); long size = inst.getObjectSize(obj); System.out.println("Bytes used by object: " + size); } public static void main(String args[]) { System.out.println(“Inside Main “); } } Package the Agent into JAR Add the following entry in the Manifest.mf file Premain-Class: com.example.demo.MyAgent Main-class :com.example.demo.MyAgent Run java -javaagent:agent.jar –jar agent.jar
  • 93. 93 Improving the Emp class example by using JavaBean Java Bean Simple Java classes that have private instance members and public setter and getter methods. It is a reusable component. OO Basics
  • 94. 94 Example: Creating JavaBean class Emp { private int empno; private String name; public void setEmpno(int empno) //Java Bean Rules { this.empno=empno; //Shadowing } public int getEmpno() { return empno; } public void setName(String name) { this.name=name; } public String getName() { return name; } } NOTE: this is also called good encapsulation OO Basics Sample Example
  • 95. 95 TEST YOUR SELF Nobody has the power to take two steps together; you can take only one step at a time. Said by Osho
  • 96. 96 1) Check this is proper Java Bean. class Customer { private int custId; public String name; public void setCustId(int custId) { this.custId=custId; } public int getCustId() { return custId; } public void setName(String name) { this.name=name; } public String getName() { return name; } } OO Basics
  • 97. 97 2) TRUE – FALSE a) Encapsulation means private methods and public variables. b) extends is used for inheritance. c) Overloading is an example of Abstraction. d) Instance Variables live in a Stack. e) new operator is used to allocate a memory for an object f) object always of reference type. g) Class is an instance of an object. h) Local Variables and Methods live in a Stack. OO Basics
  • 98. 98 Exercise : 1) Create a Student class which has rollno , name, 3 subject marks(English , Hindi , Maths) calculate total marks, percentage and grade. And print the Result Sheet of the Student. 2) Create a Employee class which has empno,name,basicSalary, calculate HRA, DA , TA and GS. HRA is 30% of basic salary DA is 20% of basic salary TA is 10% of basic salary GS=BasicSalary+ hra+da+ta OO Basics
  • 99. 99 Using Constructor  About Constructor  Calling One Constructor by another constructor
  • 100. 100  Constructor ✔Constructor has same name as a class name. ✔It is same like a method. ✔It returns nothing. ✔It Call automatically when object is created. ✔It is used to initialize the instance variables of a class. ✔You can't make a new object without invoking a constructor. ✔Every class have a default constructor by default. Using Constructor
  • 101. 101 class Emp { int empno; String name; float sal; void input() { empno=1002; name=”Mike”; sal=9090.0f; } public static void main(String args[]) { Emp obj=new Emp(); System.out.println(obj.empno+ obj.name+obj.sal); }} class Emp { int empno; String name; float sal; Emp() { empno=1001; name=”TIM”; sal=9090.0f; } public static void main(String args[]) { Emp obj=new Emp(); System.out.println(obj.empno+obj.name+obj.sal) ; } } Using Constructor Example 1 Without Constructor Example 2 Using Constructor Sample Example
  • 102. 102 Example 3: class A { A() //the default constructor for the A Class { } } Example 4: class A { A(int a) { } } A obj=new A(); //Won't compile , no matching constructor. Example 5: class A { A() { System.out.println(“I am default Constructor”); } void A() { System.out.println(“ I am not a constructor , i am a method ! “); } } Contd…. Using Constructor
  • 103. 103 Calling One Constructor by another Constructor in same class Example: class A { private A() { System.out.println(“ I am default constructor of the A Class “); } A(int s) //Overloading of the Constructor { this(); // Must be the first statement System.out.println(“I am the A class Parameterized Constructor “); } } class Test { public static void main(String agrs[]) { A obj=new A(); //Error because default constructor is private A obj1=new A(100); } } Using Constructor
  • 104. 104 TEST YOUR SELF Don’t find a fault, find a remedy; anyone can complain Said by Henry Ford
  • 105. 105 Test your Self 1) What will be the output of the following code? class A { A(int b) { System.out.println(“A class Constructor “); } public static void main(String args[]) { A obj=new A(); } } Using Constructor
  • 106. 106 Test Your Self contd… 2) What will be the output of the following code? class A { A() { System.out.println(“A class Default Constructor Call “); } A(int x) { this(); System.out.println(“A class Parameterized Constructor Call “); } public static void main(String args[]) { A obj=new A(10); } } Using Constructor
  • 107. 107 Exercise: Create a class Emp with empno,name,sal as instance variables and then create two constructor default and parametrized to set the values of instance members and create a method print() to print the values. Using Constructor
  • 108. 108 IS-A  About Inheritance  Inheritance Advantages  Reference Variable Rules  HAS-A  Class Access Ways  Access Modifiers  Final class
  • 109. 109 IS-A INHERITANCE TREE LION IS-A Animal Hippo IS-A Animal Tiger IS-A Animal Inheritance
  • 110. 110 Account (Account number, balance) Current Account Saving Account LOAN AutoLoan Personal Loan IS-A Inheritance Example
  • 111. 111 Contd....... Example: class A { Feature1 ; Feature 2; } class B extends A { Feature 3; // + Feature 1 and Feature 2 comes from class A Feature 4; } Inheritance has two advantages 1. To Promote code reuse ability, so code redundancy is reduce. 2. To Use Polymorphism IS-A Sample Example
  • 112. 112 1) To Promote code reuse ability, so code redundancy is reduce. class Person { int age; String name; String address; void input() { age=21; name=”TIM”; address=”NewYork”; } void print() { System.out.println(“Person Name is “+name); System.out.println(“Person Age is “+age); System.out.println(“Person Address is “+address); } } class Emp extends Person { int empno; String desig; float sal; public void empInput() { empno=1001; desig=”Programmer”; sal=9090.00f; } Inheritance First Advantage
  • 113. 113 Contd.... public void empPrint() { System.out.println(“Empno is “+empno); System.out.println(“Designation is “+desig); System.out.println(“Salary is “+sal); } } class Test { public static void main(String args[]) { Emp obj=new Emp(); obj.input(); obj.empInput(); obj.print(); obj.empPrint(); } } IS-A
  • 114. 114 2) To Use Polymorphism Polymorphism one thing with several forms. Example: class Animal { } class Dog extends Animal { } class Cat extends Animal { } Animal a=new Animal(); a=new Dog(); a=new Cat(); Inheritance Second Advantage IS-A
  • 115. 115  Reference variable rule: ✔A reference variable can be only one type and once declared, that type can never be changed. ✔A reference type determines the methods that can be invoked on the object the variable is referring. ✔It can refer to the same type or the sub type. ✔A reference variable can be of class type or interface type. ✔Up casting allowed only ( parent can take own and sub-type) but down casting not allowed (child cannot take parent type). NOTE: we cannot make a single program with out inheritance in java, because every class inherit java.lang.Object class. NOTE: Java is a package centric language; the developer assumed that for good organization and name scoping , you would put all the your classes into packages. IS-A
  • 116. 116 Exercise: Person class Student class Emp class IS-A Account Current Account Saving Account
  • 117. 117  HAS- A Has a relationship is based on usage , rather than inheritance. Has-A used by making an object of the other class in your class. For Examples: Horse HAS-A Halter, Customer Has-A Loan Sample Code: class Loan { } class Customer { Loan carLoan =new Loan(); } IS-A
  • 118. 118 IS-A HAS-A Used to create a parent child relationship. IS- A is based on class inheritance or interface. Has-A relationship is based on usage , rather than inheritance For Example: BMW is a Car, Horse is an Animal, AutoLoan IS-A Loan For Example: Horse HAS-A Halter, Customer HAS-A Loan IS-A can be use by extends or implements keyword. Has-A used by making an object of the other class in your class. Example: class Loan { } class AutoLoan extends Loan { } Example: class Customer { AutoLoan car=new AutoLoan(); } class AutoLoan { } Advantages of IS-A 1) To Promote code re useability, so code redundancy is reduced. 2) To Use Polymorphism Advantages of HAS-A 1) Can work on other class instance variables & methods without inheriting that class.  CLASS ACCESS WAYS IS-A
  • 119. 119 Access Modifier There are 4 access modifier. (private, public, protected, default) Note: With class only 2 access modifier can apply. ( public and default). ✔public access modifier- When a method or variable member is declared public, it means access with in a package or outside a package. ✔private access modifier- Members marked private can't be accessed by code in any class other than the class in which the private member was declared. ✔protected access modifier - Access with in same package and can access outside the package by using inheritance. ✔default access modifier- If we didn't place an access modifier in front of the variable or method, the access control is default, which means package level. Note: Can Access Modifiers be applied to local variables ? NO! IS-A
  • 120. 120 Example: Show Use of public access modifier package book; package cert; import cert.*; public class B class A { { public static void main(String args[]) public void show() { { B obj=new B(); System.out.println(“B Class Show “); obj.show(); } } } } IS-A
  • 121. 121 IS-A Final class final class A //final class cannot be inherit { } class B extends A // You cannot inherit a final class { } NOTE: String is a final class Sample Example
  • 122. 122 TEST YOUR SELF Nothing is particularly hard if you divide it into the small jobs. Said by Henry Ford
  • 123. 123 Test Your Self IS-A 1) What will be the output of the following code? class A { } class B extends A { } class C extends A, B { }
  • 124. 124 • What is the output: class A { A() { System.out.println(“A Class Default Constructor Call “); } } class B { B() { System.out.println(“B class Default Constructor Call “); } } class Test { public static void main(String args[]) { B obj=new B(); } } Test Your Self contd… IS-A
  • 125. 125 class A { A(int a) { System.out.println(“A class Parameterized Constructor Call “); } } class B extends A { B() { System.out.println(“B Class Default Constructor Call “); } } class Test { public static void main(String args[]) { B obj=new B(); } } IS-A 3) What is the output: Test Your Self contd…
  • 126. 126 IS-A 4) What will be the output of the following code? class A { void showA() { System.out.println(“A show “); } } final class B extends A { void showB() { System.out.println(“B Show “); } } class Test { public static void main(String args[]) { B obj=new B(); obj.showA(); obj.showB(); } } Test Your Self contd…
  • 127. 127 IS-A 5) What will be the output of the following code? class A { private int a=10; public int b=20; int c=30; protected int d=40; } class B extends A { void add() { System.out.println(a+b+c+d); } public static void main(String args[]) { B obj=new B(); obj.add(); } } Test Your Self contd…
  • 128. 128 Polymorphism  Overloading  Overriding  Using final in Overriding  Overloading vs Overriding  super vs this
  • 129. 129 Polymorphism- One thing with several forms. For Example: All Animals are eating, but each type has different eating habits like Dog eats Meat, Cow eats grass etc. For Example: In calculator we can add two Integer, two real number, three numbers so a same method name is used to add two numbers, three numbers, four numbers, two int numbers , two float numbers etc. Sample Code: void add(int x,int y) { System.out.println(x+y); } void add(float x,float y) { System.out.println(x+y); } void add(int a,int b,int c) { System.out.println(a+b+c); } Polymorphism
  • 130. 130  Overloading Overloaded methods can be reused as the same method name in a class, but with different arguments and optionally , a different return type. Example : A search method on Banking System, to search its customer by name, or by address or by dob, or by phone number, or by customer id. Sample Code: boolean search(int custid) boolean search(String name,String address) boolean search(String name,Date dob) boolean search(String name,String phoneno) Polymorphism Sample Example
  • 131. 131 Overloading Example: class Calculator { public void add(int x,int y) { System.out.println(x+y); } public void add(int x,int y, int z) { System.out.println(x+y+z); } public void add(float x,float y) { System.out.println(x+y); } public int add(long x,long y) { return (x+y); } public static void main(String args[]) { Calculator obj=new Calculator(); obj.add(10,20); obj.add(10,20,30); obj,add(10.1f,20.2f); obj.add(10l,20l); } } Polymorphism
  • 133. 133 Overridden Methods Any time you have a class that inherits a method from a superclass, you have the opportunity to override the method. Example: class Animal { public void eat() { System.out.println(“Generic Animal eating Generically “); } } class Dog extends Animal { public void eat() { System.out.println(“EAT MEAT”); } } class Cow extends Animal { public void eat() { System.out.println(“EAT GRASS “); } } Here eat() method overridden Polymorphism Sample Example
  • 134. 134 class Account { void withdraw() { } void deposit() { } void rateOfInterest() { } } class CurrentAccount extends Account { public void rateOfInterest() { } } class SavingAccount extends Account { public void rateOfInterest() { } } Polymorphism Overriding Example Sample Example
  • 135. 135 Polymorphism Using final in Overriding class A { final void show() { } } class B extends A { void show() //Compilation Fails because show is defined final , and we cannot //override a final method. { } }
  • 136. 136 Polymorphism Overloading Overriding Any time you have a class that inherits a method from a superclass, you have the opportunity to override the method. Overloaded methods let you reuse the same method name in a class, but with different arguments( and optionally , a different return type. The argument list must be same. Overloaded methods must change the argument list. The return type must be same in jdk1.4, but in jdk1.5 it should be co-variant returns Overloaded methods can change the return type. The access level can't be less restrictive in Overridden method. Overloaded methods can change the access modifier. Can throw any unchecked exception by Overriding. The Overridden method can throw any sub type or same type exception of overriding method. Overloaded methods can declare new or broader checked exceptions. Without inheritance no Overriding. A method can be overloaded in the same class or in a subclass. You cannot override a method marked final. You cannot override a method marked static. Can overload final and static methods.
  • 137. 137 Widening in Overloading Widening always use same or bigger data type, not go for the smaller. Example: What is the output class A { void show(int x) { System.out.println(“Show Int “); } void show(byte x) { System.out.println(“Show byte “); } void show(long x) { System.out.println(“Show long “); } public static void main(String args[]) { A obj = new A(); Obj.show(10); } }
  • 138. 138 The compiler will choose the older style before it chooses the newer style, keeping existing code more robust. So far we've seen that 1) Widening beats boxing 2) Widening beats var-args Example: AutoBoxing Happens Automatically class AddBoxing { static void go(Integer x) { System.out.println("Integer"); } public static void main(String [] args) { int i = 5; go(i); } } Overloading Rules
  • 139. 139 Example: Here widening Happens class AddBoxing { static void go(long x) { System.out.println("long"); } public static void main(String [] args) { int i = 5; go(i); } } Example : Here Widening Beats Boxing class AddBoxing { static void go(Integer x) { System.out.println("Integer"); } static void go(long x) { System.out.println("long"); } public static void main(String [] args) { int i = 5; go(i); // which go() will be invoked? } }
  • 140. 140 Example : Here Wrapper classes Beats Var-args class BoxOrVararg { static void go(Byte x, Byte y){ System.out.println("Byte, Byte"); } static void go(byte... x) { System.out.println("byte... "); } public static void main(String [] args) { byte b = 5; go(b,b); // which go() will be invoked? } } Example: Here Mixing Wideing and Autoboxing, The Java Compiler not able to do it both, so it will give error class WidenAndBox { static void go(Long x) { System.out.println("Long"); } public static void main(String [] args) { byte b = 5; go(b); // must widen then box - illegal } }
  • 141. 141 1) Static binding in Java occurs during Compile time while Dynamic binding occurs during Runtime. 2) Static binding uses Type(Class in Java) information for binding while Dynamic binding uses Object to resolve binding 3) Overloaded methods are bonded using static binding while overridden methods are bonded during run time (Dynamic Binding). 4) Instance Variable bound with static binding. Static v/s Dynamic Binding
  • 142. 142 public class StaticBindingTest { public static void main(String args[]) { Collection c = new HashSet(); StaticBindingTest et = new StaticBindingTest(); et.sort(c); } //overloaded method takes Collection argument public Collection sort(Collection c){ System.out.println("Inside Collection sort method"); return c; } //another overloaded method which takes HashSet argument which is sub class public Collection sort(HashSet hs){ System.out.println("Inside HashSet sort method"); return hs; } } Output: Inside Collection sort method Static Binding Demo
  • 143. 143 Dynamic Binding Demo public class DynamicBindingTest { public static void main(String args[]) { Vehicle vehicle = new Car(); //here Type is vehicle but object will be Car vehicle.start(); //Car's start called because start() is overridden method } } class Vehicle { public void start() { System.out.println("Inside start method of Vehicle"); } } class Car extends Vehicle { public void start() { System.out.println("Inside start method of Car"); } } Output: Inside start method of Car
  • 144. 144 TEST YOUR SELF A person who never made a mistake never tried anything new. Said by Albert Einstein
  • 145. 145 TEST YOUR SELF 1) What will be the output of the following code? class A { void show() { System.out.println(“ A class Show Call “); } } class B extends A { String show() { System.out.println(“B Class show call “); } } B obj=new B(); obj.show(); Polymorphism
  • 146. 146 TEST YOUR SELF contd… 2) What is this , Overloading or Overriding? class A { void show() { System.out.println(“ A class Show Call “); } } class B extends A { void show(int i) { System.out.println(“B Class show call “); } } Polymorphism
  • 147. 147 TEST YOUR SELF contd…. 3) What will be the output of the following code? class A { public void show() { System.out.println(“ A class Show Call “); } } class B extends A { void show() { System.out.println(“B Class show call “); } } B obj=new B(); obj.show(); Polymorphism
  • 148. 148 TEST YOUR SELF contd…. 4) What will be the output of the following code? class A { private final void show() { System.out.println(“ A class Show Call “); } } class B extends A { void show() { System.out.println(“B Class show call “); } } B obj=new B(); obj.show(); Polymorphism
  • 149. 149 super this Super keyword always refers to the parent elements like parent method , parent constructor, parent instance variables. This keyword always refers to the current class elements like methods, constructors, instance variables. Calling parent class method by using super. Example: super.parentClassMethodName(); Calling current class method. Example : this.currentClassMethodName(); Calling parent class constructor. Example: super(); super(100); Calling current class constructor. Example: this(); this(100); Using parent class variable in child class. super.a=100; Using current class variable. Example: this.a=100;  super vs this Polymorphism
  • 150. 150 Use of super and this keyword Example 1 class A { int temp=10; void show() { System.out.println(“ A Sho w”); } } class B extends A { int temp=20; void show() { super.show(); //Use of super to call parent class method System.out.println(“B Show “); this.temp=super.temp+this.temp; } } class Test { public static void main(String args[]) { B obj=new B(); obj.show(); } Polymorphism
  • 151. 151 Example 2 Another use of super and this use class A { A() { System.out.println(“A Class Default Constructor Call “); } A(int a) { System.out.println(“A class Parameterized Constructor call “); } } class B extends A { B() { System.out.println(“B Class Default Constructor Call “); } B(int t) { super(10); //Use of super to call parent class parameterized constructor and it must be the first line. System.out.println(“B Class Parameterized Constructor call “); } } Polymorphism
  • 152. 152 TEST YOUR SELF Success is the sum of small efforts, repeated day in and day out. Robert Collier
  • 153. 153 1) What will be the output of the following code? class A { A() { this(10); System.out.println(“A Class Default Constructor “); } A(int a) { System.out.println(“A class Parameterized Constructor “); } } class B extends A { B() { System.out.println(“B Class Default Constructor “); } public static void main(String args[]) { B obj=new B(); } } Polymorphism
  • 154. 154 Abstract Class  Abstract class Intro  Abstract Methods
  • 155. 155 Abstract class An abstract class never be instantiated. It is used by extending it. Abstract class has generic methods (Abstract methods) common to all sub – classes . Abstract methods are body less methods (Methods Prototypes) and child classes override the abstract methods. Example: abstract class Account { public void deposit() { } public void withdraw() { } public void checkBalance() { } public abstract float rateOfInterest(); public abstract String[] services(); } Abstract class
  • 156. 156 class SavingAccount extends Account { public float rateOfInterest() { } public String[] services() { } } class CurrentAccount extends Account { public float rateOfInterest() { } //Now this class become abstract , if you not override all the abstract methods //of abstract class, your class become abstract too. } Abstract class
  • 157. 157 TEST YOUR SELF The difference between a successful person and others is not a lack of strength, not a lack of knowledge, but rather a lack in will. Vince Lombardi
  • 158. 158 1) What will be the output of the following code? class Account { abstract void deposit(); } class SavingAccount extends Account { void deposit() { System.out.println(“Deposit Call “); } public static void main(String args[]) { SavingAccount obj=new SavingAccount(); obj.deposit(); } } Abstract class
  • 159. 159 2) What will be the output of the following code? abstract class Account { void deposit() { System.out.println(“Abstract class Deposit Call “); } } class SavingAccount extends Account { void deposit() { System.out.println(“Deposit Call “); } public static void main(String args[]) { SavingAccount obj=new SavingAccount(); obj.deposit(); } } Abstract class
  • 160. 160 3) What will be the output of the following code? abstract class Account { abstract void deposit(); } class SavingAccount extends Account { void deposit(int a) { System.out.println(“Deposit Call “); } public static void main(String args[]) { SavingAccount obj=new SavingAccount(); obj.deposit(11); } } Abstract class
  • 161. 161 Interface  Interface Introduction  Interface On Job  Interface Coding techniques
  • 163. 163 Interfaces Interface contains method prototypes (body less methods) and constants. When you create an interface, you're defining a contract for what a class can do, without saying anything about how the class will do it. Interface
  • 164. 164 Interface Example: interface Animal { int LEGS=4; //public static final LEGS=4; void eat(); //public abstract void eat(); void sound(); //public abstract void sound(); } class Dog implements Animal { public void eat() { System.out.println(“EAT MEAT “); } public void sound() { System.out.println(“BARK “); } } class Cow implements Animal { public void eat() { System.out.println(“EAT GRASS “); } public void sound() { System.out.println(“MOO “); } } Interface Sample Example
  • 165. 165 public interface CustOperation { public int insert(Customer obj) ; public int update(int custid,Customer obj); public int delete(Customer obj); public void select(Customer obj) ; } NOTE: Create a Customer Bean (Customerid, Customer Name, Gender, Address , Phone).  Interface on JOB Interface
  • 166. 166  Interface Coding techniques Example 1: interface A { int x=10; //internally public static final int x=10; void show(); //convert internally to public abstract void show() } interface B extends A { void disp(); //public abstract void disp(); } Example 2: interface A { void show(); } interface B { void disp(); } interface C extends A,B //Multiple inheritance can be possible using interface. { } Interface
  • 167. 167 Contd..... Example 3: interface Animal { void sleep(); void eat(); } interface Pet { void faithful(); } class Dog implements Animal,Pet { public void sleep() { } public void eat() { } public void faithful() { } } NOTE: 1) You implement an interface by properly and concretely overriding all of the methods defined by the interface. 2) A single class can implement many interfaces. Interface
  • 168. 168 TEST YOUR SELF He who has never learned to obey cannot be a good commander. Aristotle
  • 169. 169 Test Your Self 1) What will be the output of the following code? interface X { void show(); } class Y extends X { public void show() { System.out.println(“Inside Y Show “) } } Interface
  • 170. 170 2) what will be the output of the following code? interface X { void show(); } class Y implements X { void show() { System.out.println(“Inside Y Show “); } } Test Your Self contd…. Interface
  • 171. 171 3) what will be the output of the following code? interface X { void show(); } interface Y implements X { void disp(); } class Z extends Y { public void show() { System.out.println(“ Inside show “); } } Test Your Self contd…. Interface
  • 172. 172 Exercise: 1) Create an interface CustOperation which have insert, delete, print methods and a customer class implements CustOperation interface and overrides it's all methods. 2) Create three interfaces Account interface, Emp interface, Bank interface. Account interface has emp loan method, leave detail method. Emp interface has salary calculate method and bank has deposit and withdraw method. And finally we have a payroll interface which inherit all these interfaces. And Nucleus class implements all these interfaces.
  • 173. 173 Pass By Value And Pass By Reference
  • 174. 174 Pass by Value Pass By Reference It means passing a primitive variable into method. It means passing an object reference to the method. Pass by variable means Pass by copy of the variable. When you pass an object variable into method, you must keep in mind that you're passing the object reference, and not the actual object it self. So for the primitive variable, you are always passing a copy of bits in the variable. Passing the copy of reference variable to the method. In other words , both the caller and the called method will now have identical copies of the reference, and thus both will refer to the exact (not a copy ) object on the heap. Note: It makes no difference if you're passing primitive or reference variables, you are always passing a copy of bits in the variable.
  • 175. 175 class X { void modify(int x,int y) { x++; y++; System.out.println(“Value of x is “+x+” and y is “+y); } } class Test { public static void main(String args[]) { X obj=new X(); int a=100,int b=200; obj.modify(a,b); System.out.println(“After Modification Values are “+a+” “+b); } } a=100 b=200 x=101 y=201 Pass by value Example
  • 176. 176 Pass By Reference class X { int a,b; X() { a=100; b=200; System.out.println(“Inside X Default Constructor “); } void modify(X obj) { obj.a++; obj.b++; System.out.println(“Value of a is “+obj.a+” and b is “+obj.b); } } class Test { public static void main(String args[]) { X temp=new X(); temp.modify(temp); System.out.println(“Value of a and b inside main “+temp.a+temp.b); } } temp=1080 a=100 b=200 1080 HEAP obj=1080
  • 177. 177 Static member  Static Variable  Static Method
  • 178. 178 Static variable Value is the same for all instances of the class. Static variables are shared. All instances of the same class share a single copy of the static variables. Note : Instance variables 1 per instance. Static variables 1 per class Static member
  • 179. 179 class Emp { static int empCount; private int empno; Emp() { empCount++; } public void setEmpno(int empno) { this.empno=empno; } public int getEmpno() { return empno; } public static void main(String args[]) { Emp ram=new Emp(); ram.setEmpno(1001); Emp shyam=new Emp(); shyam.setEmpno(1002); } } Static example Static member Sample Example
  • 180. 180 Static Method Static methods are same like instance methods, but it is static so it is shareable to all objects. Static methods can use only static members or local variables , it cannot use non – static members. Static method access directly with-out creating an object of a class. Example: class A { static void show() { System.out.println(“Inside Show “); } } class Test { public static void main(String args[]) { A.show(); } } Static member Sample Example
  • 181. 181 TEST YOUR SELF Static member Experience is the child of thought, and thought is the child of action. We cannot learn men from books. Benjamin Disraeli
  • 182. 182 1) What will be the output of the following code? class Test { int a=100,b=200; static void add() { int c=a+b; System.out.println(“Sum is “+c); } public static void main(String args[]) { add(); } } Static member
  • 183. 183 2) What will be the output of the following code ? class Test { static int a; int b; Test() { a++; b++; System.out.println(“A Value is “+a); System.out.println(“B Value is “+b); } public static void main(String args[]) { Test obj1=new Test(); Test obj2=new Test(); Test obj3=new Test(); } } Static member
  • 184. 184 JDK 1.5 1. Enhance For Loop 2. Var – Args 3. AutoBoxing 4. Static import 5. Annotations 6. Generics 7. Enum
  • 186. 186 A Java virtual machine's main job is to load class files and execute the bytecodes they contain .
  • 188. 188
  • 189. 189
  • 191. 191 Treatment of boolean data type in the Java When a compiler translates Java source code into bytecodes, it uses ints or bytes to represent booleans. In the Java virtual machine, false is represented by integer zero and true by any non-zero integer. The Java virtual machine works with one other primitive type that is unavailable to the Java programmer: thereturnAddress type returnAddress types are pointers to the opcodes of JVM instructions.
  • 192. 192
  • 193. 193 An instance of class java.lang.Class is created by the Java virtual machine for every type it loads. The virtual machine must in some way associate a reference to the Class instance for a type with the type's data in the method area.
  • 194. 194 Object Representation in Memory a) Splitting an object across a handle pool and object pool. Advantage is Heap size is Compact. Two Reference need to maintain in Heap one for instance data and other for Method area. b) Keeping object data all in one place Only one reference need to maintain in heap is only for the method area
  • 195. 195 a) Splitting an object across a handle pool and object pool.
  • 196. 196 b) Keeping object data all in one place
  • 197. 197
  • 198. 198 Array Representation in Memory In Java, arrays are full-fledged objects. Like objects, arrays are always stored on the heap. Also like objects, implementation designers can decide how they want to represent arrays on the heap. Arrays have a Class instance associated with their class, just like any other object. All arrays of the same dimension and type have the same class. The length of an array (or the lengths of each dimension of a multidimensional array) does not play any role in establishing the array's class. For example, an array of threeints has the same class as an array of three hundred ints. The length of an array is considered part of its instance data. The name of an array's class has one open square bracket for each dimension plus a letter or string representing the array's type. For example, the class name for an array of ints is "[I"
  • 199. 199
  • 201. 201 The Java virtual machine makes types available to the running program through a process of loading, linking, andinitialization. 1. Loading is the process of bringing a binary form for a type into the Java virtual machine. 2. Linking is the process of incorporating the binary type data into the runtime state of the virtual machine. 3. Linking is divided into three sub-steps: verification, preparation, and resolution. 3.1 Verification ensures the type is properly formed and fit for use by the Java virtual machine. 3.2 Preparation involves allocating memory needed by the type, such as memory for any class variables. 3.3 Resolution is the process of transforming symbolic references in the constant pool into direct references. Implementations may delay the resolution step until each symbolic reference is actually used by the running program. NOTE : After verification, preparation, and (optionally) resolution are completed, the type is ready for initialization. Object Creation Steps
  • 202. 202 Garbage Collection Any garbage collection (GC) algorithm must do two basic things. First, it must detect garbage objects. Second, it must reclaim the heap space used by the garbage objects and make the space available again to the program. It determining reachability from the roots. An object is reachable if there is some path of references from the roots by which the executing program can access the object. The roots are always accessible to the program. Any objects that are reachable from the roots are considered "live." Objects that are not reachable are considered garbage,
  • 203. 203 to determine garbage collection, start your app as – java –verbose:gc HelloWorld The output of above change should be something like – GC 325407K->83000K(776768K), 0.2300771 secs GC – Indicates that it was a minor collection (young generation). If it had said Full GC then that indicates that it was a major collection (tenured generation). 325407K – The combined size of live objects before garbage collection. 83000K – The combined size of live objects after garbage collection. (776768K) – the total available space, not counting the space in the permanent generation, which is the total heap minus one of the survivor spaces. 0.2300771 secs – time it took for garbage collection to occur. Full GC Example: [Full GC [Tenured: 3485K->4095K(4096K), 0.1745373 secs] 61244K- >7418K(63104K), [Perm : 10756K->10756K(12288K)], 0.1762129 secs] [Times: user=0.19 sys=0.00, real=0.19 secs]
  • 204. 204 Inside Heap As we know objects are created inside heap memory and Garbage collection is a process which removes dead objects from Java Heap space and returns memory back to Heap in Java. For the sake of Garbage collection Heap is divided into three main regions named as New Generation, Old or Tenured Generation and Perm space. New Generation of Java Heap is part of Java Heap memory where newly created object are stored, During the course of application many objects created and died but those remain live they got moved to Old or Tenured Generation by Java Garbage collector thread. Perm space of Java Heap is where JVM stores Meta data about classes and methods, String pool and Class level details.
  • 205. 205 1) objects are created on heap in Java irrespective of there scope e.g. local or member variable. while its worth noting that class variables or static members are created in method area of Java memory space and both heap and method area is shared between different thread. 2) Garbage collection is a mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection. 3) Garbage collection relieves java programmer from memory management which is essential part of C++ programming and gives more time to focus on business logic. 4) Garbage Collection in Java is carried by a daemon thread called Garbage Collector. 5) Before removing an object from memory Garbage collection thread invokes finalize () method of that object and gives an opportunity to perform any sort of cleanup required. 6) You as Java programmer can not force Garbage collection in Java; it will only trigger if JVM thinks it needs a garbage collection based on Java heap size. 7) There are methods like System.gc () and Runtime.gc () which is used to send request of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen. 8) If there is no memory space for creating new object in Heap Java Virtual Machine throws OutOfMemoryError or java.lang.OutOfMemoryError heap space 9) J2SE 5(Java 2 Standard Edition) adds a new feature called Ergonomics goal of ergonomics is to provide good performance from the JVM with minimum of command line tuning.
  • 207. 207 Java Memory Types Java objects are created in Heap and Heap is divided into two parts or generations for sake of garbage collection in Java, these are called as Young generation or New Generation, Tenured or Old Generation. Young Generation or New Generation is further divided into three parts known as Eden space, Survivor 1 and Survivor 2 space. When an object first created in heap its gets created in new generation inside Eden space and after subsequent Minor Garbage collection if object survives its gets moved to survivor 1 and then Survivor 2. before Major Garbage collection moved that object toOld or tenured generation. Old Generation – It has 2 parts Tenured Generation and Permant Generation (PermGen) . After Surviour2 objects are move to Tenured Generation. Permanent generation or Perm Area is somewhat special and it is used to store Meta data related to classes and method in JVM. And only Perm Gen is part of Non-Heap Memory.
  • 208. 208 There are some GC algorithms which can be used by a Java VM. The following command line options allow to use a specific GC algorithm: -XX:+UseSerialGC -> single threaded, young generation, and old generation garbage collector (should be used only for small Java heap sizes such as -Xmx256m or smaller) -XX:+UseParallelGC -> only the young generation space utilizes a multithreaded (parallel) garbage collector.The old generation space uses a single-threaded garbage collector. -XX:+UseParallelOldGC -> both young and old generations use multithread garbage collector. -XX:+UseParNewGC -> enables a multithreaded, young generation garbage collector -XX:+UseConcMarkSweepGC -> enables the VM’s mostly concurrent garbage collector. It also auto-enables -XX:+UseParNewGC (use if If you are not able to meet your application’s worst case latency requirements due to full garbage collection duration being too long) -XX:+UseG1GC -> garbage first collector (default in java 7, can be also used in latest releases of java 6)
  • 209. 209 The G1 Garbage Collector The Garbage-First (G1) collector is a server-style garbage collector, targeted for multi-processor machines with large memories. It meets garbage collection (GC) pause time goals with a high probability, while achieving high throughput. The G1 garbage collector is fully supported in Oracle JDK 7 update 4 and later releases. The G1 collector is designed for applications that: Can operate concurrently with applications threads like the CMS collector. Compact free space without lengthy GC induced pause times. Need more predictable GC pause durations. Do not want to sacrifice a lot of throughput performance. Do not require a much larger Java heap. G1 is planned as the long term replacement for the Concurrent Mark-Sweep Collector (CMS). Comparing G1 with CMS, there are differences that make G1 a better solution. One difference is that G1 is a compacting collector. G1 compacts sufficiently to completely avoid the use of fine-grained free lists for allocation, and instead relies on regions. This considerably simplifies parts of the collector, and mostly eliminates potential fragmentation issues. Also, G1 offers more predictable garbage collection pauses than the CMS collector, and allows users to specify desired pause targets.
  • 210. 210 Monitoring the Garbage Collection GC is done by JVM, and since the GC monitoring tools disclose the GC information provided by JVM, you will get the same results no matter how you monitor GC. First, the GC monitoring methods can be separated into CUI and GUI depending on the access interface. The typical CUI GC monitoring method involves using a separate CUI application called "jstat", or selecting a JVM option called "verbosegc" when running JVM. GUI GC monitoring is done by using a separate GUI application, and three most commonly used applications would be "jconsole", "jvisualvm" .
  • 211. 211 CUI GC 1. java –verbose:gc HelloWorld 2. Java -XX:+PrintGCDetails HelloWorld 3. Java XX:+PrintGCTimeStamps HelloWorld 2. jstat is a monitoring tool in JVM jstat –gc <pid> Where pid is the process id and you can get the java process id. By using jps command jstat does not provide only the GC operation information display. It also provides class loader operation information or Just-in-Time compiler operation information.
  • 212. 212 GUI GC 1. Java Visual VM is a GUI profiling/monitoring tool. visualvm_134visualvm_134binvisualvm.exe – to run simple run the exe file.
  • 213. 213 GUI GC 2. Jconsole This command comes with jdk Syntax: Jconsole <processid> You can get the process id by using the jps
  • 214. 214 Summary on Garbage collection in Java 1) Java Heap is divided into three generation for sake of garbage collection. These are young generation, tenured or old generation and Perm area. 2) New objects are created into young generation and subsequently moved to old generation. 3) String pool is created in Perm area of Heap, garbage collection can occur in perm space but depends upon JVM to JVM. 4) Minor garbage collection is used to move object from Eden space to Survivor 1 and Survivor 2 space and Major collection is used to move object from young to tenured generation. 5) Whenever Major garbage collection occurs application threads stops during that period which will reduce application’s performance and throughput. 6) There are few performance improvement has been applied in garbage collection in java 6 and we usually use JRE 1.6.20 for running our application. 7) JVM command line options –Xmx and -Xms is used to setup starting and max size for Java Heap. Ideal ratio of this parameter is either 1:1 or 1:1.5 based upon my experience for example you can have either both –Xmx and –Xms as 1GB or –Xms 1.2 GB and 1.8 GB. 8) There is no manual way of doing garbage collection in Java.
  • 215. 215 How to increase size of Java Heap Default size of Heap space in Java is 128MB on most of 32 bit Sun's JVM but its highly varies from JVM to JVM. Maximum 64 MB Perm Space by Default and can extend to 128 MB in 32 Bit Window O/S. VM options -Xms and -Xmx java -Xms64m -Xmx256m HelloWorld Java -XX:PermSize 128m HelloWorld Java -Xss 1024m HelloWorld
  • 216. 216
  • 217. 217 Java Commands and Usage Javac command javac –verbose A.java Javac –source 1.4 A.java Javac –cp Javac –classpath Javap –verbose Java –verbose Java DeCompiler Usage
  • 218. 218 Using Runtime Class for GC and Heap Analysis Using System Class for GC and System Properties
  • 219. 219 NOTE: You cannot call this() from methods, only from constructors. If you do call this()in a constructor, you must call it first, before any other code in the constructor, and you can only call it once. Instance initialization methods When you compile a class, the Java compiler creates an instance initialization method for each constructor you declare in the source code of the class. Although the constructor is not a method, the instance initialization method is. It has a name, <init>, a return type, void, and a set of parameters that match the parameters of the constructor from which it was generated. For example, given the following two constructors in the source file for class CoffeeCup:
  • 220. 220 // In source packet in file init/ex8/CoffeeCup.java class CoffeeCup { public CoffeeCup() { //... } public CoffeeCup(int amount) { //... } // ... } the compiler would generate the following two instance initialization methods in the class file for class CoffeeCup, one for each constructor in the source file: // In binary form in file init/ex8/CoffeeCup.class: public void (CoffeeCup this) {...} public void (CoffeeCup this, int amount) {...} Note that <init> is not a valid Java method name, so you could not define a method in your source file that accidentally conflicted with an instance initialization method. (<init> is not a method in the Java language sense of the term, because it has an illegal name. In the compiled, binary Java class file, however, it is a legal method.) Also, the this reference passed as the first parameter to <init> is inserted by the Java compiler into the parameter list of every instance method. For example, the method void add(int amount) in the source file for class CoffeeCup would become the void add(CoffeeCup this, int amount) method in the class file. The hidden this reference is the way in which instance methods, including instance initialization methods, are able to access instance data.
  • 222. 222 We build software to solve problems. People have problems. Therefore, we build software for people. Good software not only solves immediate problems, but it can be maintained and modified to address the inevitable changes that the customer will want.
  • 223. 223 Three steps to great software 1. Make sure the software does what the customer wants 2. Apply good object-oriented principles 3. Strive for a maintainable, reusable design 223
  • 224. 224 We create software for a reason. We create software fro people. We need to know what the people want in the software we build. These are called REQUIREMENTS.
  • 225. 225 1 2 3 4 5 Who provides requirements? 225 We call these people Stakeholders Customer End user Development team members Management Technology providers
  • 226. 226 What is a requirement? 226 ‣ A requirement is a feature that your system must have in order to satisfy the customer. ‣ A requirement is something your system must do. Did we meet the requirements?
  • 227. 227 Define the problem • Talk to the customer • Talk to other stakeholders • Ask questions • Brainstorm • Look at the problem from many points of view 227
  • 229. 229 Welcome to use cases •A use case is – A complete sequence of steps that provides value to someone – Something your system must do – Initiated by an Actor (someone or something not part of your system) 229
  • 230. 230 230 ‣ Provide value ‣ Are complete ‣ Are initiated by an actor ‣ Describe a single goal of the system ‣ Be described by UML diagrams with text ‣ Be formally structured ‣ Be described using a language with formal semantics ‣ Be described by using software tools Use cases definitely… Use cases may… The essence of use cases
  • 231. 231 Parts of a use case 231 Name: Usually verb-noun (e.g. enroll in course) Description: A paragraph or two describing the purpose and value (results) Actors: Name the actor(s) involved Basic Flow: The most common or expected path through the use case Alternate Flows: Those paths or exceptions that can occur Preconditions: Things that must be true before the use case can begin Postconditions: Things that must be true when the use case ends successfully
  • 232. 232 232 And you’re responsible for changing your programs
  • 233. 233 What might change? 233 Hardware (new and modified) The use case The code (implementation and tests) Technology Upgrade 1 2 3 4

Editor's Notes

  1. You can write to a file by using System.out.println() method You just need to set the output stream by using System.setOut() This method takes PrintStream as an arguments Below is the code to set the PrintStream (as a File Stream), so your System.out.println(). Now print the values to the file not to the console. Sample Code package project1; import java.io.File; import java.io.IOException; import java.io.PrintStream; public class SystemDemo { public SystemDemo() { } public static void main(String[] args) throws IOException { // SystemDemo systemDemo = new SystemDemo(); File f=new File("e:\\test.txt"); boolean b= f.createNewFile(); if(b==false) { System.out.println("Error in File Creation !"); System.exit(0); } PrintStream ps=new PrintStream(f); System.setOut(ps); System.out.println("This is Test Data Written in File Instead of Console !"); } }
  2. Doug told us that the door had to open and close when the button was pushed. Is that really enough? If you think about why we write software, you should realize that we write software and develop systems to solve problems. The problems are defined by the requirements. So, what problem is described by what Doug told us?
  3. There are many different definitions of what a use case is or is not. This is yet another that is similar to all the rest. This can be confusing since there are so many different ways of expressing use cases. The next four slides will give you some more information about use cases. You don’t need them go move forward, but you better make sure your instructor thinks it’s okay to skip over them.
  4. The list here is just one of many that you can find if you search the Internet or look at books on use cases. These are the common parts that are referenced in several use case writing guidelines and descriptions.