Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Core Java2

The document discusses Java wrapper classes, which convert primitive types into object forms and provide utility functions. It covers constructors, methods for conversion between primitives and wrapper objects, and the concept of autoboxing and autounboxing introduced in Java 1.5. Additionally, it explains StringBuffer and StringBuilder, interfaces, and the differences between interfaces and abstract classes.

Uploaded by

ndibyalara
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Core Java2

The document discusses Java wrapper classes, which convert primitive types into object forms and provide utility functions. It covers constructors, methods for conversion between primitives and wrapper objects, and the concept of autoboxing and autounboxing introduced in Java 1.5. Additionally, it explains StringBuffer and StringBuilder, interfaces, and the differences between interfaces and abstract classes.

Uploaded by

ndibyalara
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 131

Java

Wrapper classes
 The main objectives of wrapper classes are:
 To wrap primitives into object form so that we can handle primitives also just like
objects.
 To define several utility functions which are required for the primitives.
 Constructors:
 All most all wrapper classes define the following 2 constructors one can
take corresponding primitive as argument and the other can take String as
argument.
 Example:
 Integer i=new Integer(10);
 Integer i=new Integer(“10”);
 If the String is not properly formatted then we will get runtime exception
saying “NumberFormatException”.
 Character class defines only one constructor which can take char primitive
as argument there is no String argument constructor.
Wrapper classes
 Boolean class defines 2 constructors with boolean primitive and String
arguments.
 If we want to pass boolean primitive the only allowed values are true, false
where case should be lower case.
 In all wrapper classes toString() method is overridden to return its content.
 In all wrapper classes .equals() method is overridden for content
compression.
 Utility methods:
 valueOf() method:We can use valueOf() method to create wrapper object for the given
primitive or String this method is alternative to constructor.
Form 1: Every wrapper class except Character class contains a static valueOf()
method to create wrapper object for the given String. public static wrapper valueOf(
String s);
Form 2: Every integral type wrapper class (Byte, Short, Integer, and Long) contains
the following valueOf() method to convert specified radix string to wrapper object.
Wrapper classes
 XXXValue() method: We can use xxxValue() methods to convert wrapper object to
primitive.
Every number type wrapper class (Byte, Short, Integer, Long, Float, Double) contains
the following 6 xxxValue() methods to convert wrapper object to primitives.
 parseXxx() method: We can use this method to convert String to corresponding primitive.
Form1: Every wrapper class except Character class contains a static parseXxx()
method to convert String to corresponding primitive. public static primitive parseXxx(
String s);
Form 2: integral type wrapper classes(Byte, Short, Integer, Long) contains the
following parseXxx() method to convert specified radix String form to corresponding primitive.
public static primitive parseXxx(String s,int radix);
 toString() method: We can use toString() method to convert wrapper object (or) primitive to
String.
Form 1: public String toString();
Whenever we are trying to print wrapper object reference internally this toString() method
only executed.
Form 2: Every wrapper class contains a static toString() method to convert primitive
to String.
Autoboxing and Autounboxing
 Until 1.4 version we can’t provide wrapper object in the place of primitive and
primitive in the place of wrapper object all the required conversions should be
performed explicitly by the programmer.
class AutoBoxingAndUnboxingDemo {
public static void main(String[] ags) {
Boolean b=new Boolean(true);
if(b) {
System.out.println("hello");
}}}
 But from 1.5 version onwards we can provide primitive value in the place of wrapper
and wrapper object in the place of primitive all required conversions will be
performed automatically by compiler. These automatic conversions are called
Autoboxing and Autounboxing.
 All wrapper objects are immutable that is once we created a wrapper object we
can’t perform any changes in the existing object. If we are trying to perform any
changes with those changes a new object will be created.
Autoboxing and Autounboxing example

Integer x=10;
Integer y=x;
++x;
StringBuffer
 StringBuffer
 If the content will change frequently then never class StringBufferDemo
recommended to go for String object because for {
every change a new object will be created internally. public static void main(String[] args)
 To handle this type of requirement we should go for {
StringBuffer concept. StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//16
 The main advantage of StringBuffer over String is, all
sb.append("abcdefghijklmnop");
required changes will be performed in the existing
object only instead of creating new object. System.out.println(sb.capacity());//16
sb.append("q");
 Constructors: System.out.println(sb.capacity());//34
 1)StringBuffer sb=new StringBuffer(); }

}
Creates an empty StringBuffer object with default
initialcapacity “16”.
 Once StringBuffer object reaches its maximum
capacity a new StringBuffer object will be created with
Newcapacity=(currentcapacity+1)*2.
StringBuffer
2)StringBuffer sb=new StringBuffer(int initialcapacity);
Creates an empty StringBuffer object with the specified initial capacity.
3) StringBuffer sb=new StringBuffer(String s);
Creates an equivalent StringBuffer object for the given String with capacity=s.length()
+16;
Important methods of StringBuffer:
1) public int length(); Return the no of characters present in the StringBuffer.
2) public int capacity(); Returns the total no of characters but a StringBuffer can
accommodate(hold).
3) public char charAt(int index); It returns the character located at specified index.
4) public void setCharAt(int index,char ch); To replace the character locating at
specified index with the provided character.
5) public StringBuffer append(String s); this is overloaded for all type of datatype.
6) public StringBuffer insert(int index,String s); Insert at specific location. and
method is been overloaded.
StringBuffer
7) public StringBuffer delete(int begin,int end); To delete characters from begin
index to end n-1 index.
8) public StringBuffer deleteCharAt(int index); To delete the character locating at
specified index.
9) public StringBuffer reverse();
10) public void setLength(int length); Consider only specified no of characters and
remove all the remaining characters.
11) public void trimToSize(); To deallocate the extra free memory such that
capacity and size are equal.
12) public void ensureCapacity(int initialcapacity); To increase the capacity
dynamically based on our requirement.
StringBuffer
Every method present in StringBuffer is declared as synchronized hence at a time only
one thread is allowed to operate on the StringBuffer object due to this, waiting time of
the threads will be increased and effects performance of the system.

StringBuffer StringBuilder
1) Every method present in 1) No method present in StringBuilder is
StringBuffer is synchronized. synchronized.
1) At a time only one thread is allow 1) Multiple Threads are allowed to
to operate on the StringBuffer operate simultaneously on the
object hence StringBuffer object is StringBuilder object hence
Thread safe. StringBuilder is not Thread safe.
1) It increases waiting time of the 1) Threads are not required to wait and
Thread and hence relatively hence relatively performance is high.
performance is low.
1) Introduced in 1.0 version. 1) Introduced in 1.5 versions.
Immutable program
final class CreateImmutable{
private int i;
CreateImmutable(int i){ this.i=i; }
public CreateImmutable modify(int i){
if(this.i==i) return this;
else return (new CreateImmutable(i));
}
public static void main(String[] args) {
CreateImmutable c1=new CreateImmutable(10);
CreateImmutable c2=c1.modify(100);
CreateImmutable c3=c1.modify(10);
System.out.println(c1==c2);//false
System.out.println(c1==c3);//true
CreateImmutable c4=c1.modify(100);
System.out.println(c2==c4);//false
}}
Import statement
 In any java program the following 2 packages are not require to import because these are
available by default to every java program. 1) java.lang package. 2) default package(current
working directory)
 We can used the class by package.class.
 There are 2 types of import statements.
 Explicit class import: import java.util.ArrayList;
This type of import is highly recommended to use because it improves readability of
the code.
 Implicit class import: import java.util.*;
It is never recommended to use because it reduces readability of the code.
 While resolving class names compiler will always gives the importance in the following order.
 Explicit class import
 Classes present in current working directory.
 Implicit class import.
 Whenever we are importing a package all classes and interfaces present in that package are by
default available but not sub package classes.
 “Import statement is totally compile time concept” if more no of imports are there then more will
be the compile time but there is “no change in execution time”.
static Import statement
 This concept introduced in 1.5 versions. According to sun static import improves readability of
the code but according to worldwide programming exports (like us) static imports creates
confusion and reduces readability of the code.
import static java.lang.Math.sqrt;
import static java.lang.Math.*;
class Test
{
public static void main(String args[]){
System.out.println(sqrt(4));
System.out.println(max(10,20));
System.out.println(random());
}}
 Two packages contain a class or interface with the same is very rare hence ambiguity problem is
very rare in normal import.
 But 2 classes or interfaces can contain a method or variable with the same name is very common
hence ambiguity problem is also very common in static import.
 While resolving static members compiler will give the precedence in the following order.
 Current class static members
 Explicit static import
 implict static import.
Package statement
 It is an encapsulation mechanism to group related classes and interfaces into a single module.
 The main objectives of packages are:
 To resolve name confects.
 To improve modularity of the application.
 To provide security.
 There is one universally accepted naming conversion for packages that is to use internet domain
name in reverse.
 How to compile package program: Javac –d . HydJobs.java
 -d means destination to place generated class files “.” means current working directory.
 Generated class file will be placed into corresponding package structure.
 D:\Java>javac -d c: HydJobs.java : If the specified destination is not available then we will get compile
time error.
 How to execute package program java package.ClassName
 At the time of execution compulsory we should provide fully qualified name.
 In any java program there should be at most one package statement
 In any java program the 1st non cement statement should be package statement
Interfaces
 Any service requirement specification (srs) is called an interface.
 From the client point of view an interface define the set of services what his excepting. From the
service provider point of view an interface defines the set of services what is offering. Hence an
interface is considered as a contract between client and service provider.
 Inside interface every method is always abstract whether we are declaring or not hence interface
is considered as 100% pure abstract class.
 Summery deination: Any service requirement specification (SRS) or any contract between
client and service provider or 100% pure abstract classes is considered as an interface.
 Interface Method
 Every method present inside interface is always public and abstract whether we are declaring
or not.
 we can’t use the following modifiers for interface methods. Private, protected, final, static,
synchronized, native, strictfp.
 Note1: Whenever we are implementing an interface compulsory for every method of that
interface we should provide implementation otherwise we have to declare class as
abstract in that case child class is responsible to provide implementation for remaining
methods.
 Note2: Whenever we are implementing an interface method compulsory it should be
declared as public otherwise we will get compile time error.
Interfaces
 Interface variables
 An interface can contain variables to define requirement level constants.
 Every interface variable is always public static and final whether we are declaring or not.
 we can’t declare with the following modifiers. private, protected, transient, volatile
 For the interface variables compulsory we should perform initialization at the time of declaration only
otherwise we will get compile time error.
 Extends vs implements
 A class can extend only one class at a time.
 A class can implements any no. Of interfaces at a time.
 A class can extend a class and can implement an interface simultaneously.
 An interface can extend any no. Of interfaces at a time.
 Method naming conflicts
 If two interfaces contain a method with same signature and same return type in the implementation
class only one method implementation is enough.
 if two interfaces contain a method with same name but different arguments in the implementation
class we have to provide implementation for both methods and these methods acts as a overloaded
methods.
 If two interfaces contain a method with same signature but different return types then it is not possible
to implement both interfaces simultaneously.
Interfaces
 Variable naming conflicts
 Two interfaces can contain a variable with the same name and there may be a chance variable
naming conflicts but we can resolve variable naming conflicts by using interface names.
 Marker interface: if an interface doesn’t contain any methods and by implementing that
interface if our object gets some ability such type of interfaces are called Marker interface (or)
Tag interface (or) Ability interface.
 Example 1: By implementing Serilizable interface we can send that object across the network
and we can save state of an object into a file.
 Example 2: By implementing SingleThreadModel interface Servlet can process only one client
request at a time so that we can get “Thread Safety”.
 Example 3: By implementing Cloneable interface our object is in a position to provide exactly
duplicate cloned object.
Difference between interface and abstract class
interface Abstract class
If we don’t’ know anything about If we are talking about implementation but not
implementation just we have requirement completely (partial implementation) then we should
specification then we should go for interface. go for abstract class.
Every method present inside interface is always Every method present inside abstract class need not
public and abstract whether we are declaring or be public and abstract.
not.
We can’t declare interface methods with the There are no restrictions on abstract class method
modifiers private, protected, final, static, modifiers.
synchronized, native, strictfp.
Every interface variable is always public static Every abstract class variable need not be public static
final whether we are declaring or not. final.

Every interface variable is always public static There are no restrictions on abstract class variable
final we can’t declare with the following modifiers.
modifiers. Private, protected, transient, volatile.

For the interface variables compulsory we It is not require to perform initialization for abstract
should perform initialization at the time of class variables at the time of declaration.
declaration otherwise we will get compile time
error.
Inside interface we can’t take static and Inside abstract class we can take both static and
instance blocks. instance blocks.
Inside interface we can’t take constructor. Inside abstract class we can take constructor.
Adapter class
 Adapter class is a simple java class that implements an interface only with empty
implementation for every method.
 If we implement an interface directly for each and every method compulsory we should provide
implementation whether it is required or not. This approach increases length of the code and
reduces readability.
interface X{
void m1();
void m2();
void m3();
void m4();
 Question: }
 Difference between Interface vs abstract class vs concrete class
abstract class AdapterX implements X{
public void m1(){}
public void m2(){}
public void m3(){}
public void m4(){}
}
 When we should go for interface, abstract class and concrete class?
 If we don’t know anything about implementation just we have requirement specification then we
should go for interface.
 If we are talking about implementation but not completely (partial implementation) then we
should go for abstract class.
 If we are talking about implementation completely and ready to provide service then we should
go for concrete class.
Exception Handling
 An unwanted unexpected event that disturbs normal flow of the program is called
exception.
 It is highly recommended to handle exceptions. The main objective of exception
handling is graceful (normal) termination of the program.
 What is the meaning of exception handling?
 Exception handling doesn’t mean repairing an exception. We have to define
alternative way to continue rest of the program normally. this way of “defining
alternative is nothing but exception handling”.
 Runtime stack mechanism: For every thread JVM will create a separate stack
all method calls performed by the thread will be stored in that stack. Each entry
in the stack is called “one activation record” (or) “stack frame”. After completing
every method call JVM removes the corresponding entry from the stack. After
completing all method calls JVM destroys the empty stack and terminates the
program normally.
Exception Handling(Runtime stack mechanism)
class Test{
public static void main(String[] args){
doStuff();
}
public static void doStuff(){
doMoreStuff();
}
public static void doMoreStuff(){
System.out.println("Hello");
}}
Default

exception handling in java
If an exception raised inside any method then the method is responsible to create Exception
object with the following information.
 Name of the exception.
 Description of the exception.
 Location of the exception.
 After creating that Exception object the method handovers that object to the JVM.
 JVM checks whether the method contains any exception handling code or not. If not contain
any handling code then JVM terminates that method abnormally and removes corresponding
entry form the stack.
 JVM identifies the caller method and checks whether the caller method contain any handling
code or not. If not contain handling code then JVM terminates that caller also abnormally
and the removes corresponding entry from the stack.
 This process will be continued until main() method and if the main() method also doesn’t
contain any exception handling code then JVM terminates main() method and removes
corresponding entry from the stack.
 Then JVM handovers the responsibility of exception handling to the default exception
handler.
 Default exception handler just print exception information to the console in the following
formats and terminates the program abnormally.
 Name of exception: description
 Location of exception (stack trace)
Exception Handling
 Exception hierarchy
 Throwable acts as a root for exception hierarchy.
 Throwable class contains the following two child classes.
 Exception: Most of the cases exceptions are caused by our program and these
are recoverable.
 Error: Most of the cases errors are not caused by our program these are due to
lack of system resources and these are non recoverable.
 Checked Vs Unchecked Exceptions
 Checked Exception in Java is all those Exception which requires being catches
and handled during compile time. If Compiler doesn’t see try or catch block
handling a Checked Exception, it throws Compilation error.
 Unchecked Exception in Java is those Exceptions whose handling is not
verified during Compile time. Unchecked Exceptions mostly arise due to
programming errors like accessing method of a null object, accessing element
outside an array bonding or invoking method with illegal arguments. In Java,
Unchecked Exception is direct sub Class of RuntimeException.
Exception Handling(Diagram)
Exception Handling using try catch
try{
risky code
}
catch(Exception e){
handling code
}
 In our program the code which may cause an exception is called risky code we have
to place risky code inside try block and the corresponding handling code inside
catch block.
 Within the try block if anywhere an exception raised then rest of the try block won’t
be executed even though we handled that exception. Hence we have to place/take
only risk code inside try and length of the try block should be as less as possible.
 If any statement which raises an exception and it is not part of any try block then it
is always abnormal termination of the program.
 There may be a chance of raising an exception inside catch and finally blocks also in
addition to try block.
Various methods to print exception information
 Throwable class defines the following methods to print exception information to
the console.
printStackTrace(): This method prints exception information in the following format.
Name of the exception: description of exception
Stack trace

toString(): This method prints exception information in the following format.


Name of the exception: description of exception

getMessage(): This method returns only description of the exception.


Description.
Try with multiple catch blocks:
 The way of handling an exception is varied from try{
exception to exception hence for every exception .
raise a separate catch block is required that is .
try with multiple catch blocks is possible and catch(FileNotFoundException e){
recommended to use. use local file
 If try with multiple catch blocks presents then }
order of catch blocks is very important it should catch(ArithmeticException e){
be from child to parent by mistake if we are perform these Arithmetic operations
taking from parent to child then we will get }
Compile time error saying “exception xxx has catch(SQLException e){
already been caught”. don't use oracle db, use mysql db
}
catch(Exception e){
default handler
}
Finally block
 It is never recommended to take clean up code inside try block because there is
no guarantee for the execution of every statement inside a try.
 It is never recommended to place clean up code inside catch block because if
there is no exception then catch block won’t be executed.
 We require some place to maintain clean up code which should be executed
always irrespective of whether exception raised or not raised and whether
handled or not handled such type of place is nothing but finally block.
 Hence the main objective of finally block is to maintain cleanup code.
 The specialty of finally block is it will be executed always
irrespective of whether the exception raised or not raised try{
and whether handled or not handled. risky code
}catch(x e){
handling code
}finally{
cleanup code
}
Return Vs Finally try{
 Even though return present in try or catch System.out.println("try block executed");
blocks first finally will be executed and return;
after that only return statement will be }catch(ArithmeticException e){
considered that is finally block dominates System.out.println("catch block executed");
return statement. }finally{
System.out.println("finally block executed");
 If return statement present try catch and }
finally blocks then finally block return
statement will be considered.
try{
 There is only one situation where the finally System.out.println(10/0);
block won’t be executed is whenever we return 777;
are using System.exit(0) method. }catch(ArithmeticException e){
return 888;
}finally{
return 999;
}
Output : 999
Difference between final, finally, and finalize
 Final:
 Final is the modifier applicable for class, methods and variables.
 If a class declared as the final then child class creation is not possible.
 If a method declared as the final then overriding of that method is not possible.
 If a variable declared as the final then reassignment is not possible.
 Finally:
 It is the block always associated with try catch to maintain clean up code which
should be executed always irrespective of whether exception raised or not raised
and whether handled or not handled.
 Finalize:
 It is a method which should be called by garbage collector always just before
destroying an object to perform cleanup activities.
Throw statement
 Sometime we can create exception object explicitly and we can hand over to the
JVM manually by using throw keyword.

 In general we can use throw keyword for customized exceptions but not for
predefined exceptions.
 Case 1: throw e; -> If e refers null then we will get
NullPointerException
 Case 2: After throw statement we can’t take any statement directly
otherwise we will get compile time error saying unreachable statement.
 Case 3: We can use throw keyword only for Throwable types otherwise we
will get compile time error saying incomputable types.
Throws statement
 in our program if there is any chance of raising checked exception compulsory we
should handle either by try catch or by throws keyword otherwise the code won’t
compile.
By using try catch By using throws keyword
We can use throws keyword to delicate the
class Test3{
responsibility of exception handling to the caller
public static void main(String[] args){ method. Then caller method is responsible to handle
try{ that exception.
Thread.sleep(5000); class Test3{
}catch(InterruptedException e){} public static void main(String[] args)throws
} InterruptedException{
} Thread.sleep(5000);
}}
Output:
Output:
Compile and running successfully
Compile and running successfully

 “throws” keyword required only checked exceptions. Usage of throws for unchecked
exception there is no use.
 “throws” keyword required only to convenes complier. Usage of throws keyword
doesn’t prevent abnormal termination of the program.
Throws statement
 Case 1: we can use throws keyword only for Throwable types otherwise we will get
compile time error saying incompatible types.
 In our program if there is no chance of rising an exception then we can’t right catch
block for that exception otherwise we will get compile time error saying exception XXX
is never thrown in body of corresponding try statement. But this rule is applicable only
for fully checked exception.
 Exception handling keywords summary:
 try: To maintain risky code.
 catch: To maintain handling code.
 finally: To maintain cleanup code.
 throw: To handover our created exception object to the JVM manually.
 throws: To delegate responsibility of exception handling to the caller method.
 Various possible compile time errors in exception handling:
1. Exception XXX has already been caught.2. Unreported exception XXX must be caught
or declared to be thrown. 3. Exception XXX is never thrown in body of corresponding try
statement.4. Try without catch or finally.5. Catch without try.6. Finally without try.7.
Incompatible types. A) Found:test B) Requried:java.lang.Throwable; 8. Unreachable
statement.
Customized Exceptions (User defined Exceptions)
 You can create your own exception class by defining a subclass of Exception.
 The Exception class does not define any methods of its own. It inherits methods provided by
Throwable.
 All exceptions have the methods defined by Throwable available to them.
 They are:
 Throwable fillInStackTrace( ) Returns a Throwable object that contains a completed stack trace.
 Throwable getCause( ) Returns the exception that underlies the current exception.
 String getLocalizedMessage( ) Returns a localized description.
 String getMessage( ) Returns a description of the exception.
 StackTraceElement[ ] getStackTrace( ) Returns an array that contains the stack trace.
 Throwable initCause(Throwable causeExc) Associates causeExc with the invoking exception as a
cause of the invoking exception.
 void printStackTrace( ) Displays the stack trace.
 void printStackTrace(PrintStream stream) Sends the stack trace to the stream.
 void printStackTrace(PrintWriter stream) Sends the stack trace to the stream.
 void setStackTrace(StackTraceElement elements[ ]) Sets the stack trace to the elements passed in
elements.
 String toString( ) Returns a String object containing a description of the exception.
Customized Exceptions (User defined Exceptions)

class MyException extends Exception {


private int detail; public class Main {
MyException(int a) { static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
detail = a; if (a > 10)
} throw new MyException(a);
System.out.println("Normal exit");
public String toString() {
}
return "MyException[" + detail + "]";public static void main(String args[]) {
try {
}
compute(1);
} compute(20);
} catch (MyException e) {
System.out.println("Caught " + e);
}
}
}
Chained Exceptions
 Java 2, version 1.4 added a new feature to the exception subsystem
 The chained exception feature allows you to associate another exception with an
exception. This second exception describes the cause of the first exception.

class ChainExcDemo {
static void demoproc() {
// create an exception
NullPointerException e =new NullPointerException("top layer");
// add a cause
e.initCause(new ArithmeticException("cause"));
throw e;
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Caught: " + e);
System.out.println("Original cause: " + e.getCause());
}}}
Multi Threading
 Multitasking: Executing several tasks simultaneously is the concept of
multitasking. There are two types of multitasking’s.

 Process based multitasking: Executing several tasks simultaneously where each


task is a separate independent process such type of multitasking is called process
based multitasking.
 Example: While typing a java program in the editor we can able to listen mp3
audio songs at the same time we can download a file from the net. This type of
multitasking is best suitable at “os level”.
Multi Threading
Thread based multitasking: Executing several tasks simultaneously where each
task is a separate independent part of the same program, is called Thread based
multitasking. And each independent part is called a “Thread”.
 This type of multitasking is best suitable for “programmatic level”.
 Multithreading is very easy in java because java provides in built support for
multithreading through a rich API (Thread, Runnable, ThreadGroup,
ThreadLocal….etc).
 In multithreading on 10% of the work the programmer is required to do and 90% of
the work will be down by java API.
 The main important application areas of multithreading are:
 To implement multimedia graphics.
 To develop animations.
 To develop video games etc.

Whether it is process based or Thread based the main objective of multitasking is to


improve performance of the system by reducing response time.
Multi Threading
 Thread is basically a lightweight sub-process, a smallest unit of processing.
 Advantage of Java Multithreading
 1) It doesn't block the user because threads are independent and you can perform
multiple operations at same time.
 2) You can perform many operations together so it saves time.
 3) Threads are independent so it doesn't affect other threads if exception occur in a
single thread.
 We can define a Thread in the following 2 ways.
 By extending Thread class.
 By implementing Runnable interface.
Life cycle of a Thread
 The life cycle of the thread in java is controlled by JVM. The java thread states are
as follows:
 New
 Runnable
 Running
 Non-Runnable (Blocked)
 Terminated(Dead)
 Once we created a Thread object then the Thread is said to be in new state or born
state.
 Once we call start() method then the Thread will be entered into Ready or Runnable
state.
 If Thread Scheduler allocates CPU then the Thread will be entered into running
state.
 Once run() method completes then the Thread will entered into dead state.
 when the thread is still alive, but is currently not eligible to run is called Non-
Runnable (Blocked) state
Thread class
Thread class provide constructors and methods to create and perform operations on a thread.
Thread class extends Object class and implements Runnable interface.
Commonly used Constructors
 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)
Commonly used methods
 public void run(): is used to perform action for a thread.
 public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
 public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
 public void join(): waits for a thread to die.
 public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
 public int getPriority(): returns the priority of the thread.
 public int setPriority(int priority): changes the priority of the thread.
Thread class
 public String getName(): returns the name of the thread.
 public void setName(String name): changes the name of the thread.
 public Thread currentThread(): returns the reference of currently executing thread.
 public int getId(): returns the id of the thread.
 public Thread.State getState(): returns the state of the thread.
 public boolean isAlive(): tests if the thread is alive.
 public void yield(): causes the currently executing thread object to temporarily pause
and allow other threads to execute.
 public void suspend(): is used to suspend the thread(depricated).
 public void resume(): is used to resume the suspended thread(depricated).
 public void stop(): is used to stop the thread(depricated).
 public boolean isDaemon(): tests if the thread is a daemon thread.
 public void setDaemon(boolean b): marks the thread as daemon or user thread.
 public void interrupt(): interrupts the thread.
 public boolean isInterrupted(): tests if the thread has been interrupted.

Runnable interface
 The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method
named run().
 public void run(): is used to perform action for a thread.
 By extending Thread class
Thread Scheduler
 If multiple Threads are waiting to execute then which Thread will execute 1 st is
decided by “Thread Scheduler” which is part of JVM.
 Which algorithm or behavior followed by Thread Scheduler we can’t expect exactly
it is the JVM vendor dependent hence in multithreading examples we can’t expect
exact execution order and exact output.
The following are various possible outputs for the above program.
 By implementing the Runnable interface

Best approach to define a Thread:


 Among the 2 ways of defining a Thread, implements Runnable approach is always
recommended.
 In the 1st approach our class should always extends Thread class there is no chance of
extending any other class hence we are missing the benefits of inheritance.
 But in the 2nd approach while implementing Runnable interface we can extend some other
class also. Hence implements Runnable mechanism is recommended to define a Thread.
Sleep method example
The sleep() method of Thread class is used to sleep a thread for the specified amount
of time
 public static void sleep(long miliseconds)throws InterruptedException
 public static void sleep(long miliseconds, int nanos)throws InterruptedException
class TestSleepMethod1 extends Thread{
public void run(){
for(int i=1;i<5;i++){
Output
try{Thread.sleep(500);}
---------------------
catch( InterruptedException e){
1
System.out.println(e);
1
}
2
System.out.println(i);
2
} }
3
public static void main(String args[]){
3
TestSleepMethod1 t1=new
4
TestSleepMethod1();
4
TestSleepMethod1 t2=new
TestSleepMethod1();
t1.start();
t2.start();
The join() method Example
The join() method can be used to pause the current thread execution until unless the
specified thread is dead.
 public void join()throws InterruptedException Output
 public void join(long milliseconds)throws InterruptedException ---------------------
1
class TestJoinMethod1 extends Thread{
2
public void run(){
for(int i=1;i<=5;i++){ 3
try{ Thread.sleep(500); 1
}catch(Exception e){System.out.println(e);} 4
System.out.println(i); 1
} } 2
public static void main(String args[]){ 5
TestJoinMethod1 t1=new TestJoinMethod1(); 2
TestJoinMethod1 t2=new TestJoinMethod1();
3
TestJoinMethod1 t3=new TestJoinMethod1();
t1.start(1500); 3
try{ t1.join(); 4
}catch(Exception e){System.out.println(e);} 4
t2.start(); 5
t3.start(); 5
} }
Sleep() method
 If a Thread don’t want to perform any operation for a particular amount of time
then we should go for sleep() method.
 public static native void sleep(long ms) throws InterruptedException
 public static void sleep(long ms,int ns)throws InterruptedException
class ThreadJoinDemo{
public static void main(String[] args)
throws InterruptedException {
System.out.println("M");
Thread.sleep(3000);
System.out.println("E");
Thread.sleep(3000);
System.out.println("G");
Thread.sleep(3000);
System.out.println("A");
}}
Output:
M
E
G
A
Thread Priorities
 Every Thread in java has some priority it may be default priority generated by JVM
(or) explicitly provided by the programmer.
 The valid range of Thread priorities is 1 to otherwise we will get runtime exception
saying “IllegalArgumentException”.
 Thread class defines the following constants to represent some standard priorities.
 Thread. MIN_PRIORITY----------1
 Thread. MAX_PRIORITY----------10
 Thread. NORM_PRIORITY--------5
 Thread scheduler uses these priorities while allocating CPU.
 The Thread which is having highest priority will get chance for 1st execution.
 If 2 Threads having the same priority then we can’t expect exact execution order it
depends on Thread scheduler whose behaviour is vendor dependent.
 We can get and set the priority of a Thread by using the following methods.
 public final int getPriority()
 public final void setPriority(int newPriority);//the allowed values are 1 to 10
Synchronization
 Synchronized is the keyword applicable for methods and blocks but not for classes and
variables.
 If a method or block declared as the synchronized then at a time only one Thread is allow
to execute that method or block on the given object.
 The main advantage of synchronized keyword is we can resolve date inconsistency
problems.
 But the main disadvantage is it increases waiting time of the Thread and effects
performance of the system.
 Internally synchronization concept is implemented by using lock concept.
 Every object in java has a unique lock. Whenever we are using synchronized keyword then
only lock concept will come into the picture.
 If a Thread wants to execute any synchronized method on the given object 1 st it has to get
the lock of that object. Once a Thread got the lock of that object then it’s allow to execute
any synchronized method on that object. If the synchronized method execution completes
then automatically Thread releases lock.
 While a Thread executing any synchronized method the remaining Threads are not allowed
execute any synchronized method on that object simultaneously. But remaining Threads
are allowed to execute any non-synchronized method simultaneously. [lock concept is
implemented based on object but not based on method].
Synchronization
class Display{ class SynchronizedDemo{
public synchronized void wish(String name){ public static void main(String[] args){
for(int i=0;i<5;i++){ Display d1=new Display();
System.out.print("good morning:"); MyThread t1=new MyThread(d1,“t1");
try{ MyThread t2=new MyThread(d1,“t2");
Thread.sleep(1000); t1.start();
}catch (InterruptedException e) t2.start();
{} }
System.out.println(name); }
} }
} class MyThread extends Thread{ • If we are not declaring wish() method as
Display d; synchronized then both Threads will be
String name; executed simultaneously and we will get
MyThread(Display d,String name){ irregular output.
this.d=d; • If we declare wish()method as synchronized
this.name=name; then the Threads will be executed one by one.
} • Even though we declared wish() method as
public void run(){ synchronized but we will get irregular output
d.wish(name); in this case, because both Threads are
}} operating on different objects.
Inter Thread communication (wait(),notify(), notifyAll())
 Two Threads can communicate with each other by using wait(), notify() and
notifyAll() methods.
 The Thread which is excepting updation it has to call wait() method and the Thread
which is performing updation it has to call notify() method. After getting notification
the waiting Thread will get those updations.
 wait(), notify() and notifyAll() methods are available in Object class.
 To call wait(), notify() and notifyAll() methods compulsory the current Thread should
be owner of that object that is current Thread should has lock of that object that is
current Thread should be in synchronized area. Hence we can call wait(), notify()
and notifyAll() methods only from synchronized area otherwise we will get runtime
exception saying IllegalMonitorStateException.
 Once a Thread calls wait() method on the given object 1st it releases the lock of
that object immediately and entered into waiting state.
 Once a Thread calls notify() (or) notifyAll() methods it releases the lock of that
object but may not immediately.
 Except these (wait(),notify(),notifyAll()) methods there is no other place(method)
where the lock release will be happen.
(wait(),notify(), notifyAll())Example
class ThreadA{ class ThreadB extends Thread{
public static void main(String[] args) int total=0;
throws InterruptedException{ public void run() {
ThreadB b=new ThreadB(); synchronized(this){
b.start(); System.out.println("child thread starts
synchronized(b){ calcuation");//step-2
System.out.println("main Thread calling for(int i=0;i<=100;i++){
wait() method");//step-1 total=total+i;
b.wait(); }
System.out.println("main Thread got System.out.println("child thread giving
notification call");//step-4 notification call");//step-3
System.out.println(b.total); this.notify();
}}} }}}
Output:
main Thread calling wait() method
child thread starts calculation
child thread giving notification call
main Thread got notification call
5050
Dead lock
 If 2 Threads are waiting for each other forever(without end) such type of
situation(infinite waiting) is called dead lock.
 There are no resolution techniques for dead lock but several prevention(avoidance)
techniques are possible.
 Synchronized keyword is the cause for deadlock hence whenever we are using
synchronized keyword we have to take special care.
 Daemon Threads: The Threads which are executing in the background are called
daemon Threads. The main objective of daemon Threads is to provide support for
non daemon Threads.
 public final boolean isDaemon();
 public final void setDaemon(boolean b);
Stream
 Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O
system to make input and output operation in java. In general, a stream means continuous
flow of data.
 Java encapsulates Stream under java.io package. Java defines two types of streams. They
are,
 Byte Stream : It provides a convenient means for handling input and output of byte.
 Character Stream : It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.
 Byte stream is defined by using two abstract class at the top of hierarchy, they
are InputStream and OutputStream.
 Character stream is also defined by using two abstract class at the top of
hierarchy, they are Reader and Writer.
 Two most important are
 read() : reads byte of data.
 write() : Writes byte of data.
class DemoRead{
public static void main( String args[]) {
BufferedReader br = new Bufferedreader(new
InputstreamReader(System.in));
char c = (char)br.read(); //Reading character
text = br.readLine(); //Reading String
System.out.println(text);
}
}
Java.IO Package
 File f=new File("abc.txt");
import java.io.*;
class FileDemo{
public static void main(String[] args)throws IOException{
File f=new File("cricket.txt");
System.out.println(f.exists());//false
f.createNewFile();
System.out.println(f.exists());//true
}
}

 NOTE : in UNIX everything is a file, java “file IO” is based on UNIX operating system hence in
java also we can represent both files and directories by File object only.
 File f=new File(String name);
 Creates a java File object that represents name of the file or directory.
 File f=new File(String subdirname,String name);
 Creates a File object that represents name of the file or directory present in specified sub directory.
 File f=new File(File subdir,String name);
Java.IO Package
 Import methods of file class:
 boolean exists(); Returns true if the physical file or directory available.
 boolean createNewFile(); This method 1st checks whether the physical file is
already available or not if it is already available then this method simply returns
false. If this file is not already available then it will create a new file and returns true
 boolean mkdir();
 boolean isFile(); Returns true if the File object represents a physical file.
 boolean isDirectory();
 String[] list(); It returns the names of all files and subdirectories present in the
specified directory.
 long length(); Returns the no of characters present in the file.
 boolean delete(); To delete a file or directory.
Java.IO Package(FileWriter)
 FileWriter:
 By using FileWriter we can write character data to the file.
 Constructors:
 FileWriter fw=new FileWriter(String name);
 FileWriter fw=new FileWriter(File f);
 FileWriter fw=new FileWriter(String name,boolean append);
 FileWriter fw=new FileWriter(File f,boolean append);
 If the specified physical file is not already available then these constructors will create that
file.
 Methods:
 write(int ch); To write a single character to the file.
 write(char[] ch); To write an array of characters to the file.
 write(String s); To write a String to the file.
 flush(); To give the guarantee the last character of the data also added to the file.
 close(); To close the stream.
Java.IO Package
Example:
import java.io.*;
class FileWriterDemo {
public static void main(String[] args)throws IOException {
FileWriter fw=new FileWriter("cricket.txt",true);
fw.write(98);//adding a single character
fw.write("haskar\nsoftware solutions");
fw.write("\n");
char[] ch={'a','b','c'};
fw.write(ch);
fw.write("\n");
fw.flush();
fw.close();
}
}
Output:
Bhaskar
Software solutions
ABC
Java.IO Package(FileReader)
 FileReader: By using FileReader we can read character data from the file.
 Constructors:
 FileReader fr=new FileReader(String name);
 FileReader fr=new FileReader (File f);
 Methods:
 int read();
 It attempts to read next character from the file and return its Unicode value. If the
next character is not available then we will get -1.
 int read(char[] ch);
 It attempts to read enough characters from the file into char[] array and returns the
no of characters copied from the file into char[] array.
 void close();
Java.IO Package(FileReader)
import java.io.*;
class FileReaderDemo
{
public static void main(String[] args)throws IOException
{
FileReader fr=new FileReader("cricket.txt");
int i=fr.read();
while(i!=-1)
{
System.out.print((char)i);
i=fr.read();
}
}
}
Output:
Bhaskar
Software solutions
ABC
Java.IO Package(BufferedWriter)
 Usage of FileWriter and FileReader is not recommended because:
 While writing data by FileWriter compulsory we should insert line separator(\n)
manually which is a bigger headache to the programmer.
 While reading data by FileReader we have to read character by character which is
not convent to the programmer.
 To overcome these limitations we should go for BufferedWriter and BufferedReader
concepts.
 BufferedWriter: By using BufferedWriter object we can write character data to
the file.
 Constructors:
 BufferedWriter bw=new BufferedWriter(writer w);
 BufferedWriter bw=new BufferedWriter(writer w,int buffersize);
 Note: BufferedWriter never communicates directly with the file it should
communicates via some writer object.
Java.IO Package(BufferedWriter)
Methods:
 write(int ch);
 write(char[] ch);
 write(String s);
 flush();
 close();
 newline();
 Inserting a new line character to the file.
Java.IO Package(BufferedWriter)
import java.io.*;
class BufferedWriterDemo {
public static void main(String[] args)throws IOException {
FileWriter fw=new FileWriter("cricket.txt");
BufferedWriter bw=new BufferedWriter(fw);
bw.write(100);
bw.newLine();
char[] ch={'a','b','c','d'};
bw.write(ch); bw.newLine();
bw.write("bhaskar"); bw.newLine();
bw.write("software solutions");
bw.flush(); bw.close();
}
}
Output:
d
abcd
bhaskar
software solutions
Java.IO Package(BufferedReader)
 BufferedReader: This is the most enhanced(better) Reader to read character
data from the file.
 Constructors:
 BufferedReader br=new BufferedReader(Reader r);
 BufferedReader br=new BufferedReader(Reader r,int buffersize);
 Note:
 BufferedReader can not communicate directly with the File it should communicate
via some Reader object. The main advantage of BufferedReader over FileReader is
we can read data line by line instead of character by character.
 Methods:
 int read();
 int read(char[] ch);
 String readLine(); It attempts to read and return next line from the File. if the
next line is not available then this method returns null.
 void close();
Java.IO Package(FileReader)
Example:
import java.io.*;
class BufferedReaderDemo {
public static void main(String[] args)throws IOException {
FileReader fr=new FileReader("cricket.txt");
BufferedReader br=new BufferedReader(fr);
String line=br.readLine();
while(line!=null) {
System.out.println(line);
line=br.readLine();
}
br.close();
}
}
Java.IO Package(PrintWriter)
 PrintWriter: This is the most enhanced Writer to write text data to the file.
 By using FileWriter and BufferedWriter we can write only character data to the File
but by using PrintWriter we can write any type of data to the File.
 Constructors:
 PrintWriter pw=new PrintWriter(String name);
 PrintWriter pw=new PrintWriter(File f);
 PrintWriter pw=new PrintWriter(Writer w);
 PrintWriter can communicate either directly to the File or via some Writer object
also.
 Methods:
 write(int ch); write (char[] ch); write(String s); flush(); close();
print(char ch); print (int i);
 print (double d); print (boolean b); print (String s); println(char ch);
 println (int i); println(double d); println(boolean b); println(String s);
Java.IO Package(PrintWriter)
Example:
import java.io.*;
class PrintWriterDemo {
public static void main(String[] args)throws IOException {
FileWriter fw=new FileWriter("cricket.txt");
PrintWriter out=new PrintWriter(fw);
out.write(100);
out.println(100); out.println(true);
out.println('c'); out.println("bhaskar");
out.flush(); out.close();
}
}
Output:
d100
true
c
bhaskar
java.util (Collections)
 Limitations of Object[] array:
 Arrays are fixed in size that is once we created an array there is no chance of
increasing (or) decreasing the size based on our requirement hence to use arrays
concept compulsory we should know the size in advance which may not possible
always.
 Arrays can hold only homogeneous data elements.
 But we can resolve this problem by using object type array(Object[]).
 Example:
 Object[] o=new Object[10000];
 o[0]=new Student();
 o[1]=new Customer();
 Arrays concept is not implemented based on some data structure hence ready-
made methods support we can’t expert. For every requirement we have to write
the code explicitly.
java.util (Collections)
 To overcome the above limitations we should go for collections concept.
1. Collections are growable in nature that is based on our requirement we can
increase (or) decrease the size hence memory point of view collections concept is
recommended to use.
2. Collections can hold both homogeneous and heterogeneous objects.
3. Every collection class is implemented based on some standard data structure
hence for every requirement ready-made method support is available being a
programmer we can use these methods directly without writing the functionality on
our own. Arrays Collections
1) Arrays are fixed in size. 1) Collections are growable in nature.
1) Memory point of view arrays are not 1) Memory point of view collections are highly
recommended to use. recommended to use.
1) Performance point of view arrays are 1) Performance point of view collections are not
recommended to use. recommended to use.
1) Arrays can hold only homogeneous data type 1) Collections can hold both homogeneous and
elements. heterogeneous elements.
1) There is no underlying data structure for 1) Every collection class is implemented based on
arrays and hence there is no readymade some standard data structure and hence
method support. readymade method support is available.
1) Arrays can hold both primitives and object 1) Collections can hold only objects but not
types. primitives.
java.util (Collections)
 Collection: If we want to represent a group of objects as single entity then we
should go for collections.
 Collection framework: It defines several classes and interfaces to represent a
group of objects as a single entity.
 9(Nine) key interfaces of collection framework:
 1. Collection 2. List 3. Set
 4. SortedSet 5. NavigableSet 6. Queue
 7. Map 8. SortedMap 9. NavigableMap

 Collection:
 If we want to represent a group of “individual objects” as a single entity then we
should go for collection.
 In general we can consider collection as root interface of entire collection framework.
 Collection interface defines the most common methods which can be applicable for
any collection object
java.util (Collections)
 List:
 It is the child interface of Collection.
 If we want to represent a group of individual objects as a single entity where
“duplicates are allow and insertion order must be preserved” then we should go for
List interface.
java.util (Collections)
 Set:
 It is the child interface of Collection.
 If we want to represent a group of individual objects as single entity “where
duplicates are not allow and insertion order is not preserved” then we should go for
Set interface.
java.util (Collections)
 Queue:
 It is the child interface of Collection.
 If we want to represent a group of individual objects prior to processing then we
should go for queue concept.
java.util (Collections)
 Map:
 Map is not child interface of Collection.
 If we want to represent a group of objects as key-value pairs then we should go for
Map interface.
 Duplicate keys are not allowed but values can be duplicated.
java.util (Collections)
List of methods present in Collection interface.
 boolean add(Object o);
 boolean addAll(Collection c);
 boolean remove(Object o);
 boolean removeAll(Object o);
 boolean retainAll(Collection c);
 To remove all objects except those present in c.
 Void clear();
 boolean contains(Object o);
 boolean containsAll(Collection c);
 boolean isEmpty();
 Int size();
 Object[] toArray();
 Iterator iterator();
java.util (Collections)
 List interface defines the following specific methods.
1) boolean add(int index,Object o); 2) boolean addAll(int
index,Collectio c);
3) Object get(int index); 4) Object remove(int
index);
5) Object set(int index,Object new);//to replace
6) int indexOf(Object o); Returns index of first occurrence of “o”.
7) int lastIndexOf(Object o); 8) ListIterator listIterator();
 ArrayList:
 The underlying data structure is resizable array (or) growable array.
 Duplicate objects are allowed.
 Insertion order preserved.
 Heterogeneous objects are allowed.
 Null insertion is possible.
java.util (Collections)
Constructors:
1) ArrayList a=new ArrayList(); Creates an empty ArrayList object with
default initial capacity “10” reaches max capacity then New
capacity=(current capacity*3/2)+1
2) ArrayList a=new ArrayList(int initialcapacity);
3) ArrayList a=new ArrayList(collection c);
import java.util.*;
class ArrayListDemo {
public static void main(String[] args) {
ArrayList a=new ArrayList();
a.add("A"); a.add(10);
a.add("A"); a.add(null);
System.out.println(a);//[A, 10, A, null]
a.remove(2);
System.out.println(a);//[A, 10, null]
a.add(2,"m"); a.add("n");
System.out.println(a);//[A, 10, m, null,
n]
}
}
java.util (Collections)
 LinkedList:
 The underlying data structure is double LinkedList
 If our frequent operation is insertion (or) deletion in the middle then LinkedList is
the best choice.
 If our frequent operation is retrieval operation then LinkedList is worst choice.
 Duplicate objects are allowed.
 Insertion order is preserved.
 Heterogeneous objects are allowed.
 Null insertion is possible.
 Implements Serializable and Cloneable interfaces but not RandomAccess.
 methods
void addFirst(Object o); void addLast(Object o); Object getFirst();
Object getLast(); Object removeFirst(); Object
removeLast();
java.util (Collections)
 Constructors:
 LinkedList l=new LinkedList(); Creates an empty LinkedList object.
 LinkedList l=new LinkedList(Collection c); To create an equivalent LinkedList
object for the given collection.
import java.util.*;
class LinkedListDemo {
public static void main(String[] args) {
LinkedList l=new LinkedList();
l.add("bhaskar"); l.add(30);
l.add(null); l.add("bhaskar");
System.out.println(l);//[bhaskar, 30, null, bhaskar]
l.set(0,"software");
System.out.println(l);//[software, 30, null, bhaskar]
l.set(0,"venky");
System.out.println(l);//[venky, 30, null, bhaskar]
l.removeLast();
System.out.println(l);//[venky, 30, null]
l.addFirst("vvv");
System.out.println(l);//[vvv, venky, 30, null]
}}
java.util (Collections)
 Vector:
 The underlying data structure is resizable array (or) growable array.
 Duplicate objects are allowed.
 Insertion order is preserved.
 Heterogeneous objects are allowed.
 Null insertion is possible.
 Implements Serializable, Cloneable and RandomAccess interfaces.
Note: Every method present in Vector is synchronized and hence Vector is Thread safe.
Vector specific methods To remove elements
 addElement(Object o);-----Vector removeElement(Object o);----Vector
removeElementAt(int index);-----Vector
To get objects
removeAllElements();-----Vector
 Object elementAt(int index);-----Vector
 Object firstElement();--------------Vector
 Object lastElement();---------------Vector
java.util (Collections)
Constructors:
 Vector v=new Vector();Creates an empty Vector object with default initial
capacity 10
 Vector v=new Vector(int initialcapacity);
 Vector v=new Vector(int initialcapacity, int incrementalcapacity);
 Vector v=new Vector(Collection c);
import java.util.*;
class VectorDemo {
public static void main(String[] args) {
Vector v=new Vector();
System.out.println(v.capacity());//10
for(int i=1;i<=10;i++) {
v.addElement(i);
}
System.out.println(v.capacity());//10
v.addElement("A");
System.out.println(v.capacity());//20
System.out.println(v);//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, A]
}
}
SERIALIZATION
Serialization: The process of saving (or) writing state of an object to a file is called
serialization but strictly speaking it is the process of converting an object from java
supported form to either network supported form (or) file supported form.
 By using FileOutputStream and ObjectOutputStream classes we can achieve
serialization process.

De-Serialization: The process of reading state of an object from a file is called


DeSerialization but strictly speaking it is the process of converting an object from file
supported form (or) network supported form to java supported form.
 By using FileInputStream and ObjectInputStream classes we can achieve
DeSerialization.
We can perform Serialization only for Serilizable objects.
 An object is said to be Serilizable if and only if the corresponding class implements
Serializable interface.
 Serializable interface present in java.io package and does not contain any
methods. It is marker interface. The required ability will be provided automatically
by JVM.
 We can add any no. Of objects to the file and we can read all those objects from the
file but in which order we wrote objects in the same order only the objects will
come back. That is order is important.
oos.writeObject(d1);
import java.io.*; oos.writeObject(c1);
class Dog implements Serializable System.out.println("Serialization ended");
{ System.out.println("Deserialization started");
int i=10; FileInputStream fis=new FileInputStream("abc.ser");
int j=20; ObjectInputStream ois=new ObjectInputStream(fis);
} Dog d2=(Dog)ois.readObject();
class Cat implements Serializable Cat c2=(Cat)ois.readObject();
{ System.out.println("Deserialization ended");
int i=30; System.out.println(d2.i+"................"+d2.j);
int j=40; System.out.println(c2.i+"................"+c2.j);
} }
class SerializableDemo } Output:
{ Serialization started
public static void main(String args[])throws Exception{ Serialization ended
Dog d1=new Dog(); Deserialization started
Cat c1=new Cat(); Deserialization ended
System.out.println("Serialization started"); 10................20
FileOutputStream fos=new FileOutputStream("abc.ser"); 30................40
ObjectOutputStream oos=new ObjectOutputStream(fos);
Transient keyword:
 While performing serialization if we don’t want to serialize the value of a particular
variable then we should declare that variable with “transient” keyword.
 At the time of serialization JVM ignores the original value of transient variable and
save default value.
 That is transient means “not to serialize”.
Static Vs Transient:
 static variable is not part of object state hence they won’t participate in
serialization because of this declaring a static variable as transient these is no use.
Transient Vs Final:
 final variables will be participated into serialization directly by their values. Hence
declaring a final variable as transient there is no use.
Java Applet
 A Java applet is a special kind of Java program that a browser enabled
with Java technology can download from the internet and run. An applet is
typically embedded inside a web page and runs in the context of a
browser. An applet must be a subclass of the java.applet.Applet class. The
Applet class provides the standard interface between the applet and the
browser environment.
 Swing provides a special subclass of the Applet class called
javax.swing.JApplet. The JApplet class should be used for all applets that
use Swing components to construct their graphical user interfaces (GUIs).
 Advantage of Applet
 It works at client side so less response time.
 Secured
 It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.
 Drawback of Applet
 Plugin is required at client browser to execute applet.
Java Applet
import java.applet.*;
import java.awt.*;

public class HelloWorldApplet extends Applet


{
public void paint (Graphics g)
{
g.drawString ("Hello World", 25, 50);
}
}

Lifecycle of Java Applet


 Applet is initialized.
 Applet is started.
 Applet is painted.
 Applet is stopped.
 Applet is destroyed.
Java Applet(Lifecycle methods for Applet)
 java.applet.Applet class: For creating any applet java.applet.Applet class must
be inherited. It provides 4 life cycle methods of applet.
 public void init(): is used to initialized the Applet. It is invoked only once.
 public void start(): is invoked after the init() method or browser is maximized. It
is used to start the Applet.
 public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
 public void destroy(): is used to destroy the Applet. It is invoked only once.

 java.awt.Component class: The Component class provides 1 life cycle method of


applet.
 public void paint(Graphics g): is used to paint the Applet. It provides Graphics
class object that can be used for drawing oval, rectangle, arc etc.
Java Applet
 There are two ways to run an applet
 By html file.
 By appletViewer tool (for testing purpose).
//First.java
<html> import java.applet.Applet;
<body> import java.awt.Graphics;
<applet code="First.class" public class First extends Applet{
width="300" height="300">
</applet> public void paint(Graphics g){
</body> g.drawString("welcome to applet",150,150);
</html> }

}
c:\>javac First.java /*
c:\>appletviewer First.java <applet code="First.class" width="300" height="300">
</applet>
*/
Commonly used methods of Graphics class
public abstract void drawString(String str, int x, int y)
public void drawRect(int x, int y, int width, int height)
public abstract void fillRect(int x, int y, int width, int height)
public abstract void drawOval(int x, int y, int width, int height)
public abstract void fillOval(int x, int y, int width, int height)
public abstract void drawLine(int x1, int y1, int x2, int y2)
public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer)
public abstract void drawArc(int x, int y, int width, int height, int
startAngle, int arcAngle)
public abstract void fillArc(int x, int y, int width, int height, int
startAngle, int arcAngle)
public abstract void setColor(Color c)
public abstract void setFont(Font font)
Java Applet
import java.applet.Applet;
import java.awt.*;

public class GraphicsDemo extends Applet{

public void paint(Graphics g){


g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);

g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
Java Applet(Event Handling)
 Any program that uses GUI (graphical user interface) such as Java application
written for windows, is event driven. Event describes the change of state of any
object. Example : Pressing a button, Entering a character in Textbox.

 Event handling has three main components,


 Events : An event is an object that describes a state change in a source..
 Events Source : Event source is an object that generates an event.
 Listeners : A listener is an object that listens to the event. A listener gets notified
when an event occurs.

 How Events are handled ?


 A source generates an Event and send it to one or more listeners registered with
the source. Once event is received by the listener, they processed the event and
then return. Events are supported by a number of Java packages, like java.util,
java.awt and java.awt.event.
Java Applet(Event Handling)
Java Applet(Event Handling)
 Important Event Classes and Interfaces
Event Classe Description Listener Interface
generated when button is pressed, menu-item is
ActionEvent ActionListener
selected, list-item is double clicked
generated when mouse is dragged,
MouseEvent moved,clicked,pressed or released also when the enters MouseListener
or exit a component
KeyEvent generated when input is received from keyboard KeyListener
ItemEvent generated when check-box or list item is clicked ItemListener
generated when value of textarea or textfield is
TextEvent TextListener
changed
MouseWheelEve MouseWheelListene
generated when mouse wheel is moved
nt r
generated when window is activated, deactivated,
WindowEvent WindowListener
deiconified, iconified, opened or closed
ComponentEven generated when component is hidden, moved, resized ComponentEventLis
t or set visible tener
generated when component is added or removed from
ContainerEvent ContainerListener
container
AdjustmentEven
generated when scroll bar is manipulated AdjustmentListener
t
Java Applet(Event Handling)
import java.awt.*;
import java.awt.event.*;
import java.applet.*; public void keyTyped(KeyEvent k) {
import java.applet.*; msg = msg+k.getKeyChar();
import java.awt.event.*; repaint();
import java.awt.*; }
public void paint(Graphics g) {
public class Test extends Applet g.drawString(msg, 20, 40);
implements KeyListener{ }
String msg=""; }
public void init() {
addKeyListener(this);
}
public void keyPressed(KeyEvent k) {
showStatus("KeyPressed");
}
public void keyReleased(KeyEvent k) {
showStatus("KeyRealesed");
}
Sources of Events
 Button: Generates action events when the button is pressed.
 Checkbox: Generates item events when the check box is selected or deselected.
 Choice Generates item events when the choice is changed.
 List Generates action events when an item is double-clicked; generates item
events when an item is selected or deselected.
 Menu Item Generates action events when a menu item is selected; generates item
events when a checkable menu item is selected or deselected.
 Scrollbar Generates adjustment events when the scroll bar is manipulated.
 Text components Generates text events when the user enters a character.
 Window Generates window events when a window is activated, closed,
deactivated, deiconified, iconified, opened, or quit.
Event Listener Interfaces
 Listeners are created by implementing one or more of the interfaces defined by the
java.awt.event package. When an event occurs, the event source invokes the
appropriate method defined by the listener and provides an event object as its
argument.
 ActionListener Defines one method to receive action events.
 AdjustmentListener Defines one method to receive adjustment events.
 ComponentListener Defines four methods to recognize when a component is
hidden, moved, resized, or shown.
 ContainerListener Defines two methods to recognize when a component is added to
or removed from a container.
 FocusListener Defines two methods to recognize when a component gains or loses
keyboard focus.
 ItemListener Defines one method to recognize when the state of an item changes.
 KeyListener Defines three methods to recognize when a key is pressed, released, or
typed.
Event Listener Interfaces
 MouseListener Defines five methods to recognize when the mouse is clicked,
enters a component, exits a component, is pressed, or is released.
 MouseMotionListener Defines two methods to recognize when the mouse is
dragged or moved.
 MouseWheelListener Defines one method to recognize when the mouse wheel is
moved. (Added by Java 2, version 1.4)
 TextListener Defines one method to recognize when a text value changes.
 WindowFocusListener Defines two methods to recognize when a window gains or
loses input focus. (Added by Java 2, version 1.4)
 WindowListener Defines seven methods to recognize when a window is activated,
closed, deactivated, deiconified, iconified, opened, or quit.
Event Listener Interfaces
ActionListener Interface : void actionPerformed(ActionEvent ae)
AdjustmentListener Interface : void adjustmentValueChanged(AdjustmentEvent ae)

ComponentListener Interface:
 void componentResized(ComponentEvent ce)
 void componentMoved(ComponentEvent ce)
 void componentShown(ComponentEvent ce)
 void componentHidden(ComponentEvent ce)
ContainerListener Interface
 void componentAdded(ContainerEvent ce)
 void componentRemoved(ContainerEvent ce)
FocusListener
 void focusGained(FocusEvent fe)
 void focusLost(FocusEvent fe)
Event Listener Interfaces
ItemListener : void itemStateChanged(ItemEvent ie)
KeyListener
 void keyPressed(KeyEvent ke)
 void keyReleased(KeyEvent ke)
 void keyTyped(KeyEvent ke)
MouseListener
 void mouseClicked(MouseEvent me)
 void mouseEntered(MouseEvent me)
 void mouseExited(MouseEvent me)
 void mousePressed(MouseEvent me)
 void mouseReleased(MouseEvent me)
MouseMotionListener
 void mouseDragged(MouseEvent me)
 void mouseMoved(MouseEvent me)
Event Listener Interfaces
MouseWheelListener: void mouseWheelMoved(MouseWheelEvent mwe)
TextListener void textChanged(TextEvent te)
WindowFocusListener
 void windowGainedFocus(WindowEvent we)
 void windowLostFocus(WindowEvent we)
WindowListener
 void windowActivated(WindowEvent we)
 void windowClosed(WindowEvent we)
 void windowClosing(WindowEvent we)
 void windowDeactivated(WindowEvent we)
 void windowDeiconified(WindowEvent we)
 void windowIconified(WindowEvent we)
 void windowOpened(WindowEvent we)
MouseListener Example
public void mouseExited(MouseEvent me) {
import java.awt.*; mouseX = 0; mouseY = 10;
import java.awt.event.*; msg = "Mouse exited."; repaint();
import java.applet.*; }
/*<applet code="MouseEvents" public void mousePressed(MouseEvent me) {
width=300 height=100></applet>*/ mouseX = me.getX(); mouseY = me.getY();
public class MouseEvents extends Applet msg = "Down"; repaint();
implements MouseListener { }
String msg = ""; public void mouseReleased(MouseEvent me) {
int mouseX = 0, mouseY = 0; mouseX = me.getX(); mouseY = me.getY();
public void init() { msg = "Up"; repaint();
addMouseListener(this); }
} public void paint(Graphics g) {
public void mouseClicked(MouseEvent me) { g.drawString(msg, mouseX, mouseY);
mouseX = 0; mouseY = 10; }
msg = "Mouse clicked.";repaint(); } }
public void mouseEntered(MouseEvent me) {
mouseX = 0; mouseY = 10;msg = "Mouse entered.";
repaint();}
Adapter Classes
 An adapter class provides an empty implementation of all methods in an event
listener interface.

Adapter Class Listener Interface


ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
Adapter Classes Example

import java.awt.*; class MyMouseMotionAdapter extends


import java.awt.event.*; MouseMotionAdapter {
import java.applet.*; AdapterDemo adapterDemo;
/*<applet code="AdapterDemo" public MyMouseMotionAdapter(
width=300 height=100></applet>*/ AdapterDemo adapterDemo) {
public class AdapterDemo extends Applet { this.adapterDemo = adapterDemo;
public void init() { }
addMouseListener(new MyMouseAdapter(this)); // Handle mouse dragged.
addMouseMotionListener( public void mouseDragged(MouseEvent me) {
new MyMouseMotionAdapter(this)); adapterDemo.showStatus("Mouse dragged");
}} }
class MyMouseAdapter extends MouseAdapter { }
AdapterDemo adapterDemo;
public MyMouseAdapter(
AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo; }
public void mouseClicked(MouseEvent me) {
adapterDemo.showStatus("Mouse clicked");
}}
Anonymous Inner Classes Example
An anonymous inner class is one that is not
assigned a name.

// Anonymous inner class demo.


import java.applet.*;
import java.awt.event.*;
/*
<applet code="AnonymousInnerClassDemo" width=200 height=100>
</applet>
*/
public class AnonymousInnerClassDemo extends Applet {
public void init() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
showStatus("Mouse Pressed");
}
});
}
}
AWT
AWT
 AWT contains large number of classes and methods that allows you to create and
manage windows GUI application. AWT is the foundation upon which Swing is
made.
AWT
 Component class is at the top of AWT hierarchy. Component is an abstract class
that encapsulates all attribute of visual component. A component object is
responsible for remembering the current foreground and background colours and
the currently selected text font.
 Container is a component in AWT that contains another component like button,
text field, tables etc. Container is a subclass of component class. Conatiner class
keeps track of components that are added to another component.
 Panel class is concrete sub class of Container. Panel does not contain title bar,
menu bar or border.
 Window class creates a top level window. Window does not have borders and
menu bar.
 Frame is a sub class of Window and have resizing canvas. It is a container that
contain several different components like button, title bar, textfield, label etc. In
Java, most of the AWT applications are created using Frame window. Frame class
has two different constructors,
 Frame() throws HeadlessException
 Frame(String title) throws HeadlessException
AWT
Creating a Frame
 By Instantiating Frame class
 By extending Frame class
Creating Frame Window by Instantiating Frame class

import java.awt.*;
public class Testawt {
Testawt() {
Frame fm=new Frame(); //Creating a frame.
Label lb = new Label("welcome to java graphics"); //Creating a label
fm.add(lb); //adding label to the frame.
fm.setSize(300, 300); //setting frame size.
fm.setVisible(true); //set frame visibilty true.
}
public static void main(String args[]) {
Testawt ta = new Testawt();
}
}
AWT
Creating Frame window by extending Frame class
package testawt;
import java.awt.*;
import java.awt.event.*;
public class Testawt extends Frame {
public Testawt() {
Button btn=new Button("Hello World");
add(btn); //adding a new Button.
setSize(400, 500); //setting size.
setTitle("StudyTonight"); //setting title.
setLayout(new FlowLayout()); //set default layout for frame.
setVisible(true); //set frame visibilty true.
}
public static void main (String[] args) {
Testawt ta = new Testawt(); //creating a frame.
}
}
Control Fundamentals
The AWT supports the following types of controls:
 Labels
 Push buttons
 Check boxes
 Choice lists
 Lists
 Scroll bars
 Text editing
Adding and Removing Controls
 To include a control in a window, you must add it to the window. To do this, you
must first create an instance of the desired control and then add it to a window by
calling add( ),which is defined by Container. Component add(Component
compObj)
 Sometimes you will want to remove a control from a window. To do this, call
remove( ). This method is also defined by Container. void remove(Component
obj)
Layout Manager
Layout Manager
The layout manager automatically positions all the components within the container.
By default the components are positioned by the default layout manager.
Java provide us with various layout manager to position the controls. The properties
like size, shape and arrangement varies from one layout manager to other layout
manager. When the size of the applet or the application window changes the size,
shape and arrangement of the components also changes in response.
A layout manager is an instance of any class that implements the LayoutManager
interface. The layout manager is set by the setLayout( ) method.
LayoutManager & Description
1 BorderLayout : The borderlayout arranges the components to fit in the five
regions: east, west, north, south and center.
Layout Manager
2 CardLayout : The CardLayout object treats each component in the container as a
card. Only one card is visible at a time.

3 FlowLayout : The FlowLayout is the default layout. Components are laid out from
the upper-left corner, left to right and top to bottom.When no more components fit on
a line, the next one appears on the next line.
Layout Manager
4 GridLayout : GridLayout lays out components in a two-dimensional grid. When you
instantiate a GridLayout, you define the number of rows and columns.

5 GridBagLayout : This is the most flexible layout manager class.The object of


GridBagLayout aligns the component vertically,horizontally or along their baseline
without requiring the components of same size.
Layout Manager
// Demonstrate GridLayout
import java.awt.*;
import java.applet.*;
/*<applet code="GridLayoutDemo" width=300 height=200></applet>*/
public class GridLayoutDemo extends Applet {
static final int n = 4;
public void init() {
setLayout(new GridLayout(n, n));
setFont(new Font("SansSerif", Font.BOLD, 24));
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
int k = i * n + j;
if(k > 0)
add(new Button("" + k));
}
}
}
}
Java Socket Programming
 Java Socket programming is used for communication between the applications running on
different JRE
 Java Socket programming can be connection-oriented or connection-less
 Socket and ServerSocket classes are used for connection-oriented socket programming
and DatagramSocket and DatagramPacket classes are used for connection-less socket
programming

Java Networking Terminology


 IP address is a unique number assigned to a node of a network e.g. 192.168.0.1
 A protocol is a set of rules basically that is followed for communication.
 The port number is used to uniquely identify different applications. It acts as a
communication endpoint between applications.
 MAC (Media Access Control) Address is a unique identifier of NIC (Network Interface
Controller)
 A socket is an endpoint between two way communication.
Java Socket Programming
 The java.net package provides many classes to deal with networking applications in
Java.
Java Socket Programming
 The Socket class can be used to create a socket
1) public InputStream getInputStream() returns the InputStream attached with this
socket.
2) public OutputStream returns the OutputStream attached with
getOutputStream() this socket.
3) public synchronized void close() closes this socket

 The ServerSocket class can be used to create a server socket. This object is used to
establish communication with the clients.

1) public Socket accept() returns the socket and establish a


connection between server and client.
2) public synchronized void close() closes the server socket.
Java Socket Programming

MyServer.java

import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
Java Socket Programming
MyClint.java file

import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
To execute this program open two command prompts and execute
each program at each command prompt
Remote Method Invocation
 Remote method invocation(RMI) allow a java object to invoke method on an object
running on another machine. RMI provide remote communication between java
program. RMI is used for building distributed application. The RMI provides remote
communication between the applications using two objects stub and skeleton.
Concept of RMI application
 A RMI application can be divided into two part,Client program and Server program.
A Server program creates some remote object, make their references available for the
client to invoke method on it. A Client program make request for remote objects on
server and invoke method on them. Stub and Skeleton are two important object used
for communication with remote object.
Remote Method Invocation

Stub
 In RMI, a stub is an object that is used as a Gateway for the client-side. All the outgoing
request are sent through it. When a client invokes the method on the stub object
following things are performed internally:
 A connection is established using Remote Virtual Machine.
 It then transmits the parameters to the Remote Virtual Machine. This is also known as Marshals
 After the 2nd step, it then waits for the output.
 Now it reads the value or exception which is come as an output.
 At last, it returns the value to the client.
Remote Method Invocation

Skeleton
 In RMI, a skeleton is an object that is used as a Gateway for the server-side.All the
incoming request are sent through it. When a Server invokes the method on the
skeleton object following things are performed internally:
 All the Parameters are read for the remote method.
 The method is invoked on the remote object.
 It then writes and transmits the parameters for the result. This is also known as
Marshals

Stub and Skeleton


 Stub act as a gateway for Client program. It resides on Client side and communicate
with Skeleton object. It establish the connection between remote object and transmit
request to it.
 Skeleton object resides on server program. It is responsible for passing request
from Stub to remote object
Remote Method Invocation

Creating a Simple RMI application involves following steps


 Define a remote interface.
 Implementing remote interface.
 create and start remote application
 create and start client application

You might also like