Unit 1 - AJP
Unit 1 - AJP
Prepared By:
Dr. Dheresh Soni
Syllabus of Unit 1
• Overview of the Java • Arrays
platform • Packages
• Introduction to Java: Java • Inheritance
Architecture • Exception Handling and
• Advantages of Java
Threading: Try, Catch,
• PATH and CLASSPATH
Finally, Throws
variables
• Creating Multithreaded
• Compiling and Running Java
Programs Programs,
• Class and Object: Creating • Thread Life Cycle
Classes, Interfaces, Creating • Input/Output Serialization and
Objects Object Serialization.
• Access Modifiers
Object Oriented Programming
The major motivating factor - remove some of the flaws
encountered in the procedural approach.
OOP treats data as a critical element - does not allow it
to flow freely, Ties data more closely to the functions
OOP allows decomposition of a problem - number of
entities called objects and then builds data and
functions.
Object Oriented Programming
Object-oriented programming is not the right of any
particular language.
The languages should support several of the OOP
concepts to claim that they are object oriented.
Object-based programming languages
– Data encapsulation
– Data hiding and access mechanisms
– Automatic initialization and clear-up Of Objects
– Operator overloading
Object-oriented programming languages
– Object-based features + inheritance + dynamic
binding
Basic concepts OOP - These include:
1. Objects 2. Classes 3. Data abstraction
4. Data encapsulation 5. Inheritance 6. Polymorphism
7. Dynamic binding 8. Message passing
Object Oriented Programming
Procedure oriented Object oriented
programming (POP) programming (OOP)
Basic concepts
OOP
1. Objects
2. Classes
3. Data abstraction
4. Data encapsulation
Object Oriented Programming
5. Inheritance
Object Oriented Programming
6. Polymorphism
I. Static Binding
II. Dynamic Binding
7. Dynamic binding
8. Message passing
JDK
Introduction to Java, Java platform & Java
Architecture
JVM 4 main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment
JVM Architecture
1. Classloader - Subsystem used to load class files. Three
built-in classloaders in Java.
Bootstrap ClassLoader,
Extension ClassLoader,
System/Application ClassLoader.
2. Class Area – Stores per-class structures - runtime
constant pool, field and method data, the code for
methods.
3. Heap - Runtime data area in which objects are allocated.
Introduction to Java, Java platform & Java
Architecture
Introduction to Java, Java platform & Java
Architecture
4. Stack - Stores frames to holds local variables and partial
results.
5. Program Counter Register – Hold Address of the Java
virtual machine instruction currently being executed.
6. Native Method Stack - Hold all the native methods
7. Execution Engine -
A virtual processor
class classname
{
type instance-variable1; type instance-variable2;
type methodname1(parameter-list)
{ // body of method }
}
Methods –
Classes usually consist of two things: instance
variables and methods.
Java gives them so much power and flexibility. This
is the general form of a method:
Class and Object: Creating Classes, Interfaces,
Creating Objects
Syntax:
type name(parameter-list)
{ // body of method }
Adding a Method –
A class that contains only data, it rarely happens. You
will use methods to access the instance variables
Methods define the interface to most classes
Allows the class implementer to hide the specific
layout of internal data structures behind cleaner
method abstractions.
// This program includes a method inside the box class.
class Box
{
double width; double height; double depth;
void volume( ) // display volume of a box
{
Class and Object: Creating Classes, Interfaces,
Creating Objects
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class BoxDemo3
{
public static void main(String args[ ])
{
Box mybox1 = new Box(); Box mybox2 = new Box();
mybox1.width = 10; // assign values to mybox1's
instance variables mybox1.height = 20;
mybox1.depth = 15;
mybox2.width = 3; // assign different values to
mybox2's instance variables mybox2.height = 6;
mybox2.depth = 9;
mybox1.volume( ); // display volume of first box
mybox2.volume( ); // display volume of second box
Class and Object: Creating Classes, Interfaces,
Creating Objects
}
}
This program generates the following output.
Volume is 3000.0
Volume is 162.0
Example
class Client implements Callback
{ // Implement Callback's interface
public void callback(int param)
{System.out.println("callback called with " + param);}
}
Class and Object: Creating Classes, Interfaces,
Creating Objects
It is both permissible and common for classes - define
additional members of their own.
Example
class Client implements Callback
{
public void callback(int param) // Implement
Callback's interface
{
System.out.println("callback called with " + param);
}
void nonIfaceMeth()
{
System.out.println("Classes that implement
interfaces " + "may also define other
members, too.");
}
}
Class and Object: Creating Classes, Interfaces,
Creating Objects
Accessing Implementations Through Interface
References –
For example:
abstract class Incomplete implements Callback
{
int a, b;
void show();
{ System.out.println(a + " " + b); }
}
Multidimensional Arrays –
In Java, multidimensional arrays are actually arrays of
arrays.
To declare a multidimensional array variable, specify
each additional index using another set of square
brackets.
Example - int twoD[ ][ ] = new int[4][5];
Arrays
class TwoDArray
{
public static void main(String args[])
{
int twoD[ ][ ];
twoD[ ][ ]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++) for(j=0; j<5; j++)
{
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++)
{
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
Arrays
Arrays
}
}
Output:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
Importing Packages –
Packages are a good mechanism for compartmentalizing
diverse classes from each other, it is easy to see why all
of the built- in Java classes are stored in packages.
Packages
There is no core Java classes in the unnamed default
package; all of the standard classes are stored in some
named package.
It could become tedious to type in the long dot-separated
package path name for every class you want to use.
For this reason, Java includes the import statement to
bring certain classes, or entire packages, into visibility.
If you are going to refer to a few dozen classes in your
application, however, the import statement will save a lot
of typing.
import statements occur immediately following the
package statement (if it exists) and before any class
definitions.
This is the general form of the import statement:
Syntax: import pkg1[.pkg2].(classname|*);
Example: import java.util.Date;
import java.io.*;
Packages
All of the standard Java classes included with Java are
stored in a package called java.
The basic language functions are stored in a package
inside of the java package called java.lang.
To import every package or class that you want to use
import java.lang.*;
Inheritance
Inheritance is one of the cornerstones of object-oriented
programming because it allows the creation of
hierarchical classifications.
Using inheritance, you can create a general class that
defines behaviour common to a set of related items.
A class that is inherited is called a superclass. The class
that does the inheriting is called a subclass.
Subclass is a specialized version of a superclass. It
inherits all of the instance variables and a method
defined by the superclass and adds its own elements.
To inherit a class, you simply incorporate the definition of
one class into another by using the extends keyword.
Output :
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24
Inheritance
You can only specify one superclass for any subclass that
you create. Java does not support the inheritance of
multiple superclasses into a single subclass.
You can, create a hierarchy of inheritance in which a
subclass becomes a superclass of another subclass. No
class can be a superclass of itself.
Member Access and Inheritance –
Although a subclass includes all of the members of its
superclass
It cannot access those members of the superclass that have
been declared as private.
For example - This program contains an error and will not
compile.
class A // Create a superclass.
{
int i; // public by default
Inheritance
private int j; // private to A
void setij(int x, int y)
{
i = x;
j = y;
}
}
class B extends A // A's j is not accessible here.
{
int total; void sum()
{ total = i + j; } // ERROR, j is not accessible here
class Access
{
public static void main(String args[])
{
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
Inheritance
System.out.println("Total is " + subOb.total);
}
}
Using super –
When you will want to create a superclass that keeps
the details of its implementation to itself
In this case, there would be no way for a subclass to
directly access or initialize these variables on its own.
Since encapsulation is a primary attribute of OOP.
Java provides a solution to this problem. Whenever a
subclass needs to refer to its immediate superclass, it can
do so by use of the keyword super.
Super has two general forms.
1. calls the superclass constructor.
2. To access a member of the superclass that has been
hidden by a member of a subclass.
Inheritance
Using super to Call Superclass Constructors –
A subclass can call a constructor method defined by its
superclass by use of the following
super(parameter-list);
super( ) must always be the first statement executed inside
a subclass’ constructor. Example:
class Box // A complete implementation of BoxWeight
{
private double width;
private double height;
private double depth;
Box(Box ob) // construct clone of an object
{
width = ob.width; // pass object to constructor
height = ob.height;
depth = ob.depth;
}
Inheritance
Box(double w, double h, double d)
// constructor used when all dimensions specified
{ width = w; height = h; depth = d; }
double volume() // compute and return volume
{ return width * height * depth; }
}
Uncaught Exceptions –
What happens when you don’t handle them.
Example - Divide-by-zero error.
class Exc0
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
} }
Exception Handling and Threading: Try, Catch,
Finally, Throws
System detects the attempt to divide by zero, it
constructs a new exception object and then throws
this exception. The execution of Exc0 to stop, because
once an exception has been thrown, it must be caught by
an exception handler and dealt with immediately.
We haven’t supplied any exception handlers of our own,
so the exception is caught by the default handler
provided by the Java run-time system. Any exception
that is not caught by your program will ultimately be
processed by the default handler.
The default handler displays a string describing the
exception, Here is the output generated when this
example is executed.
java.lang.ArithmeticException: / by zero at
Exc0.main(Exc0.java:4)
Exception Handling and Threading: Try, Catch,
Finally, Throws
Try and catch block –
Default exception handler provided by the Java run-
time system is useful for debugging - handle an
exception yourself.
Doing so provides two benefits.
1. fix the error.
2. Prevents the program from automatically
terminating.
To guard against and handle a run-time error, simply
enclose the code that you want to monitor inside a try
block.
Immediately following the try block, include a catch
clause that specifies the exception type that you wish
to catch. Example - division-by-zero error:
class Exc2
{
public static void main(String args[])
Exception Handling and Threading: Try, Catch,
Finally, Throws
{
int d, a;
try // monitor a block of code.
{
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e) // catch divide-by-zero
error
{ System.out.println("Division by zero."); }
System.out.println("After catch statement.");
}
}
Output:
Division by zero.
After catch statement.
Exception Handling and Threading: Try, Catch,
Finally, Throws
Displaying a Description of an Exception –
Finally block –
When exceptions are thrown, execution in a method
takes a rather abrupt, nonlinear path that alters the
normal flow through the method.
Depending upon how the method is coded, it is even
possible for an exception to cause the method to return
prematurely. This could be a problem in some methods.
So the finally keyword is designed to address this
contingency.
Exception Handling and Threading: Try, Catch,
Finally, Throws
finally creates a block of code that will be executed
after a try/catch block has completed
The finally block will execute whether or not an
exception is thrown.
Any time a method is about to return to the caller from
inside a try/catch block, via an uncaught exception or an
explicit return statement, the finally clause is also
executed just before the method returns.
Useful for closing file handles and freeing up any
other resources that might have been allocated at the
beginning of a method with the intent of disposing of
them before returning.
The finally clause is optional. However, each try
statement requires at least one catch or a finally
clause.
Exception Handling and Threading: Try, Catch,
Finally, Throws
Example -
class FinallyDemo // Demonstrate finally.
{
static void procA() // Exception out of the method.
{
try
{
System.out.println("inside procA");
throw new RuntimeException("demo");
}
finally
{ System.out.println("procA's finally"); }
}
static void procB()// Return from within a try block.
{
try
{
Exception Handling and Threading: Try, Catch,
Finally, Throws
System.out.println("inside procB");
return;
}
finally
{ System.out.println("procB's finally"); }
}
static void procC()// Execute a try block normally.
{
try
{ System.out.println("inside procC"); }
finally
{ System.out.println("procC's finally"); }
}
public static void main(String args[])
{
try
{ procA(); }
Exception Handling and Threading: Try, Catch,
Finally, Throws
catch (Exception e) Output
{ System.out.println("Exception inside procA
caught"); } procA’s finally
procB(); Exception caught
procC(); inside procB
} procB’s finally
} inside procC
procC’s finally
Throw and throws keywords –
Throw - Catching exceptions that are thrown by the Java
run-time system. However, it is possible for your program
to throw an exception explicitly, using the throw
statement. The general form of throw is shown here:
throw ThrowableInstance;
ThrowableInstance must be an object of type Throwable
or a subclass of Throwable.
Exception Handling and Threading: Try, Catch,
Finally, Throws
There are two ways you can obtain a Throwable object:
1. using a parameter into a catch clause, or
2. creating one with the new operator.
The flow of execution stops immediately after the throw
statement; any subsequent statements are not
executed.
The nearest enclosing try block is inspected to see if it
has a catch statement that matches the type of the
exception.
1. If it does find a match, control is transferred to that
statement.
2. If not, then the next enclosing try statement is
inspected, and so on.
3. If no matching catch is found, then the default
exception handler halts the program and prints the
stack trace.
Exception Handling and Threading: Try, Catch,
Finally, Throws
Example -
class ThrowDemo // Demonstrate throw.
{
static void demoproc()
{
try
{ throw new NullPointerException("demo"); }
catch(NullPointerException e)
{
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[])
{
try
{ demoproc(); }
catch(NullPointerException e)
Exception Handling and Threading: Try, Catch,
Finally, Throws
{ System.out.println("Recaught: " + e); }
}
}
Output:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo
The program also illustrates how to create one of Java’s
standard exception objects. Pay close attention to this
line:
throw new NullPointerException("demo");
All of Java’s built- in run-time exceptions have at least
two constructors:
class ThrowsDemo
// This program contains an error and will not compile.
{
static void throwOne()
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{ throwOne(); }
Exception Handling and Threading: Try, Catch,
Finally, Throws
}
Two changes.
First, you need to declare that throwOne( ) throws
IllegalAccessException.
Second, main( ) must define a try/catch statement that
catches this exception.
Output:
inside throwOne
caught java.lang.IllegalAccessException: demo
Creating Multithreaded Programs
Multithreading: Fundamentals –
Output
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
Creating Multithreaded Programs
New thread: Thread[Three,5,main] One: 2
One: 5 Three: 2
Two: 5 Two: 2
Three: 5 One: 1
One: 4 Three: 1
Two: 4 Two: 1
Three: 4 One exiting.
One: 3 Two exiting.
Three: 3 Three exiting.
Two: 3 Main thread exiting
Thread Life Cycle
In Java, a thread always exists in any one of the following
states.
1. New –
A new thread is created,
Code has not been run yet
2. Active-
When a thread invokes the start() method,
Active state contains two states within it: one
is runnable, and the other is running.
3. Runnable-
A thread may be running or may be ready to run at any
given instant of time.
It is the duty of the thread scheduler
A program implementing multithreading acquires a fixed
slice of time to each individual thread.
Thread Life Cycle
Each and every thread runs for a short span of time
and when that allocated time slice is over.
All those threads that are willing to run, waiting for their
turn to run, lie in the runnable state.
In the runnable state, there is a queue where the
threads lie.
4. Running:-
When the thread gets the CPU, it moves from the
runnable to the running state.
Generally, the most common change in the state of a
thread is from runnable to running and again back to
runnable.
5. Blocked or Waiting-
Thread is inactive for a span of time (not permanently)
then, either the thread is in the blocked state or is in the
waiting state.
Thread Life Cycle
6. Timed Waiting –
To avoid starvation, a timed waiting state is given to
thread for a specific span of time, and not forever.
The sleep() method puts the thread in the timed wait
state. After the time runs out, the thread wakes up and
start its execution from when it has left earlier.
7. Terminated –
A thread reaches the termination state because of the
following reasons:
1. Normal termination: When a thread has finished its
job, then it exists or terminates normally.
2. Abnormal termination: It occurs when some
unusual events such as an unhandled exception or
segmentation fault.
A terminated thread means the thread is no more in the
system. In other words, the thread is dead, and there is
no way one can respawn (active after kill) the dead
thread.
Thread Life Cycle
Thread Life Cycle
Implementation of Thread States –
Get the current state of a thread using
the Thread.getState() method.
The java.lang.Thread.State class of Java provides the
constants ENUM to represent the state of a thread.
These constants are:
1. public static final Thread.State NEW - It represents
the first state of a thread that is the NEW state.
2. public static final Thread.State RUNNABLE - It
represents the runnable state.It means a thread is
waiting in the queue to run.
3. public static final Thread.State BLOCKED - It
represents the blocked state. In this state, the thread
is waiting to acquire a lock.
4. public static final Thread.State WAITING - It
represents the waiting state. A thread will go to this
state when it invokes the Object.wait() method, or
Thread Life Cycle
Thread.join() method with no timeout. A thread in
the waiting state is waiting for another thread to
complete its task.
5. public static final Thread.State TIMED_WAITING -
It represents the timed waiting state. Difference -
Waiting has no time constraint, whereas timed
waiting has the time constraint. A thread invoking
the following method reaches the timed waiting
state.
1. sleep
2. join with timeout
3. wait with timeout
4. parkUntil
5. parkNanos
6. public static final Thread.State TERMINATED - It
represents the final state of a thread that is
terminated or dead. A terminated thread means it
has completed its execution.
Input/Output & Object Serialization
How data is sent over the network or how to save files on a
disk. This is possible with mechanism
called Serialization and Deserialization.
Serialization
It is the process of converting the state of an object into
a byte stream.
A byte-stream is a Java I/O (Input/Output) stream
which is essentially flows of data that a programmer can
either read from or write.
Byte Streams read or write one byte of data at a time.
Now we have converted the object into a byte-stream
which can be saved onto a disk, communicated over the
network, etc.
It is mainly used in Hibernate, RMI, JPA, EJB and JMS
technologies.
Input/Output & Object Serialization
Input/Output & Object Serialization
Deserialization
The reverse operation of serialization is
called deserialization
Byte-stream is converted into an object.
To use them again, we need to convert these byte-
streams back to their respective Objects. This reverse
process of converting object into byte-stream is
called Deserialization.
The serialization and deserialization process is platform-
independent, it means you can serialize an object on
one platform and deserialize it on a different platform.
Example - The image is a simple illustration of the
Serialization-Deserialization process in Java.
Why Do We Need Serialization in Java-
Serialization mechanism is usually used when there is a need
to send your data (objects) over the network or to store in
files.
Input/Output & Object Serialization
Hardware components like network infrastructure, hard
disk etc understands only bytes and bits, not the java
objects.
Serialization is used in this case which translates Java
object's state to byte-stream to send it over the network
or save it in file.
Student deserializedStudent;
// To hold the deserialized byte-stream
Input/Output & Object Serialization
try
{
// Serializing the student object – std
FileOutputStream fileOut = new
FileOutputStream("storeObject.txt");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(std);
out.close();
fileOut.close(); // Serialization complete
System.out.printf("Object serialized");
// Deserialization process
FileInputStream fileIn = new
FileInputStream("storeObject.txt");
ObjectInputStream in = new ObjectInputStream(fileIn);
deserializedStudent = (Student) in.readObject();
//Deserialization
in.close();
fileIn.close();
Input/Output & Object Serialization
// Printing the deserialized object.
System.out.println("Deserialized Student...");
System.out.println("Name: " + deserializedStudent.stu_Name);
System.out.println("Address: " +deserializedStudent.stu_Addr);
}
catch (IOException i)
{ i.printStackTrace(); }
catch (Exception e)
{
System.out.println("Class not found");
e.printStackTrace();
return; Output:
} Deserialized Student...
} Name: George
} Address: ABC,XYZ
Input/Output & Object Serialization
Input/Output & Object Serialization
While Serialization the writeObject() method is used.
Whereas, in Deserialization the readObject() method is
used.
An object to be made serializable it is absolutely
mandatory for the object’s class to implement the
Serializable interface.
An interface is like a class but with some differences, It is
used to show only the important things to the user and
hide internal working details away from the user.
The Serializable interface tells the JVM (Java Virtual
Machine) that the objects of this class are ready for
serialization and/or deserialization.
Machines do not understand the human language - Source
code. To bridge the gap we need to translate the source
code. This is where the JVM comes in.
Input/Output & Object Serialization
Java Serialization with Inheritance (IS-A Relationship)
Java Serialization with Aggregation (HAS-A Relationship)
Java Serialization with the static data member
Java Serialization with array or collection
Externalizable in java:
SerialVersionUID: