Core Java2
Core Java2
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
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 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.
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.
}
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.*;
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.
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.
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.
The ServerSocket class can be used to create a server socket. This object is used to
establish communication with the clients.
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