Java Class Notes
Java Class Notes
Q) What is Java?
Java is a platform independent, object oriented, partly compiled & partly
interpreted programming language, developed in the year 1995 by James Gosling & team
members. Before 2009 it was a product of Sun Microsystems. From 2009 onwards Java is
a product of Oracle.
PATH:-
Path is an environment variable, using which we make JDK and its related programs
available to the operating system. Thus we have to mention the complete path of
JDK\bin in the environment variable path.
variable name = PATH
variable value = C:\Program Files\Java\jdk1.6.0\bin;
1
First Step to Create a Sample Java Program:-
D:\> md MYJAVAPRG
D:\> cd MYJAVAPRG
D:\ MYJAVAPRG> copy con Sample.java
public class Sample
{
public static void main( String args[])
{
int i = 1;
System.out.println(“God is great”);
System.out.println(“Sample Program No-”+i);
}
}
To Compile the Program :- (D:\MYJAVAPRG> javac <source-file-name> )
D:\MYJAVAPRG> javac Sample.java
Explanation of Program:-
public :- It is a keyword, known as an access specifier.
Access Specifier :-Which specifies how to access a member of a class or the class itself. In
Java there are four types of access specifier present.
class :- It is a keyword, which is used to define a class. Every java program must have
at least a single class. Usually class name starts with upper case letter.
modifier :-Which have some capability to change the original property of a program. In
java there are 8 modifier present namely -
abstract
final
native
static
synchronized
strictfp
transient
volatile
2
void :- It is the return type of main method. Which specifies no value will be returned to
main. In java there are 3 return type present.
void type
data type
type class type
package :- It is a container or directory that contains classes and interfaces. There are
other several packages present in java namely java.lang, java.io, java.util, java.awt,
java.applet, java.rmi, java.sql, java.text etc.
String args[] :- This will hold the command line arguments, through this we can take
input at the runtime from command line.
Keywords Descriptions
It is a primitive data type in java. it can have either true and false value. Internally, boolean
is represented as an integral value in JVM. When boolean variable is used as an instance or
boolean static variable, its default value is false. Whenever a condition checking is done in java,
boolean value is returned by the condition checking operator. Size of boolean variable is 8
bits.
3
break It is used inside loops and switch case to break the normal flow of the program.
It is primitive data type in java. Its size is 1 byte or 8 bits. Its default value is zero when
byte
used as an instance variable or static variable.
It is used to create individual cases in a switch statement. Case clause precedes integer
case constant and enum members. In place of integer constant one can have character constants
and bytes since they are auto-converted to integers.
It is a primitive data type in Java. Unlike C/C++, it is of 16 bits and is used to hold the
char
unicode character.
class It is a keyword through which a programmer defines the user defined class template.
When this keyword is encountered, the control jumps to the condition checking part of do,
continue do-while loop, and the increment part of for loop. continue statement can be followed
with a level name in order to resume execution from the specified level name.
This is an optional component of switch case. When no condition is satisfied, default case
default
is executed in switch case.
do It has no existence of its won. It is always entangled with the do-while loop.
double It is a primitive data type in java. It is of 64 bits and is used to store real numbers.
It has no existence of its won. It is used along with if statement following if block. It is
else used for condition checking. When if part is not executed, control jumps to else part. In an
if-else statement the else part is optional.
JDK 1.5 has introduced this keyword. It is used to create a constant. Enum is a class in
enum
java.
It is used in case of variables to create constants. If it is used in the case of class, that class
final cannot be inherited. When it is used in the case of methods, that method cannot be
overridden.
4
It is a component of exception handling in java. Whenever try block is executed, it is
finally
mandatory that the codes inside the finally block be executed.
import It is used to import existing packages, packages are the collection of class files.
instanceof It is a binary operator used to determine the parent-child relationship between two objects.
It is used to support multiple inheritance in java. By default all the methods declared in an
interface interface are public and abstract. To use the methods declared inside an interface, one has to
override it in the child class.
Like abstract methods the body of native method is defined elsewhere in foreign language.
native It is used to have communication between java and the system dependent native codes
written in C/C++ to improve the performance and efficiency.
package This keyword is used to declare a package. Package is a collection of class files.
It is an access modifier. When an entity inside the class is declared as private, it cannot be
private
inherited to its child class. Private variables are only accessed inside the class.
It is an access specifier. Protected entities are accessed outside the package through
protected
inheritance.
5
public It is an access specifier. Public variables can be accessed from anywhere.
This keyword is associated with a method and a constructor. Static variables are treated
static
as class variables. Static entities are accessed through a class name.
synchronized It is a keyword used to avoid a deadlock in a thread. It can be used for block or method.
It is used along with the method signature. It is used by the called method to throw the
throws
unhandled exception to the calling method.
transient It is used for the variables, if the programmer does not want to store them permanently.
If a method does not return anything then void is used to denote its return type during
void
the definition of the method.
It is used along with a variable name. A volatile variable changes its value without
volatile
informing the JVM. The system clock values are stored in volatile variables.
6
Data Types in Java
Integer Data Type Memory Size Minimum and Maximum Value
byte 1 byte -128 to +127
short 2 bytes -32768 to +32767
int 4 bytes -2147483648 to +2147483647
long 8 bytes -9223372036854775808 to
+9223372036854775807
Float Data Type Memory Size Minimum and Maximum Value
float 4 bytes -3.4e38 to -1.4e-45 for negative values and
1.4e-45 to 3.4e38 for positive values
double 8 bytes -1.8e308 to -4.9e-324 for negative values and
4.9e-324 to 1.8e308 for positive values
Char Data Type Memory Size Minimum and Maximum Value
char 2 bytes 0 to 65535
Boolean Data Type Memory Size Minimum and Maximum Value
boolean 1 bit true and false
Q) What is method?
A method is a self-contained block of statements or instructions.
A method is having following two parts
Method Prototype
Method Body
7
Q) What is Method Signature?
A method signature consists of method name and the parameter types.
Example: int add ( int x, int y)
{
return(x+y);
}
The signature of the above method is:-
add (int, int);and
The prototype is :-
int add(int, int);
If the class is declared as public then the file name & class name must be same. If it is not
declared as public then file name & class name may or may not be same.
The name of all predefined class starts with upper case letter. If the class name is multi
worded, then each word beginning letter must be upper case. Similarly in case of method
name, except the first word each word beginning will be in upper case. This rule should
be followed for the user defined class and methods also.
8
After successful compilation the source code is converted into [Byte Code]. This byte
code will be stored inside an auto created [.class] file by the JVM (Java Virtual
Machine).
The [.class] file of a program is same for different OS. The [.class] file of a program can
be run in different OS and it will give same result.
If we change the OS then [.class] file cannot be change. Only JVM will change from OS
to OS.
Q) What is Platform?
Basically operating system is called as platform.
Q) What is Code?
Code means a group of statements.
Byte Code is a highly optimized set of instructions, which will be understood by JVM
Only. It is not specific to any OS. Thus it is platform independent.
Q) Why C & C++ are platform dependent, whereas java is platform independent?
C compiler generates executable code, hence C is platform dependent.
The executable code created for a C or C++ program by the PC having Linux Operating
system can only be executed in another PC having OS Linux. The .exe file generated
from OS Linux or a particular OS, cannot be executed in a different PC having different
OS. So C & C++ are platform dependent.
9
Java compiler generates intermediate code (byte code), hence java is platform
independent.
The Java byte code generated by a PC having OS “Unix” can be executed in another PC
irrespective of OS. Hence Java is platform independent.
We cannot blindly take the byte code (.class file) and execute it in any OS we like.
Before executing the byte code, it should be confirmed that JVM is present in the target
OS.
Q) What is JVM and what are the advantages of JVM (Java Virtual Machine)?
JVM is a collection of programs, which provides the complete environment that is
required to execute byte code or a java application in the system. JVM makes the
procedure to execute the byte code based on the concept of dynamic loading.
It is responsible for taking the [.class] file and converting each byte code instruction into
the machine language instruction or executable code, which can be executed by the
microprocessor.
In JVM, their present a module (or program) called class loader sub system through
which it loads the [.class] file into the RAM.
Then it verifies whether all byte code instructions are proper or not, if it finds any
instruction suspicious, then the execution is rejected immediately.
If the byte code instructions are proper, then it allocates necessary memory to execute the
program. And also it De-Allocates the memory after execution.
JVM is an interpreter for the java byte code. Java is once interpreted because of the
JIT(Just in time) compiler.
JVM is platform dependent, means for different OS different JVM is required. Though
JVM is platform dependent, it makes java platform independent.
To run a Java program, we must have JVM present in our system, running a Java
program without JVM is not possible.
To get JVM, we need to install JDK or JRE software into our system.
Execution
Engine
Operating System
11
The memory used by class loader sub-system is divided into five parts called run time
data areas, which contains the data and results while running the program. These area’s are:-
Method Area:- Method area is the memory block, which stores the class code, code of the
Heap:- This is the area where objects are created. Whenever JVM loads a class, a method
Java Stacks:- Method code is stored on method area. But while running a method, it needs
some more memory to store the data and results. This memory is allotted on java stacks. So,
java stacks are memory areas where java methods are executed. While executing methods, a
separate frame will be created in the java stack, where the method is executed. JVM uses a
PC (Program Counter) Registers:- These are the registers memory areas, which contain
memory address of the instructions of the methods. If there are 3 methods, 3 PC registers will
Native Method Stacks:- java methods are executed on java stacks. Similarly, native
methods (for example C/C++ functions) are executed on native method stacks. To execute
the native methods, generally native method libraries (for example C/C++ header files) are
required. These header files are located and connected to JVM by a program, called native
method interface.
12
Syntax to create a class in Java:
<access specifier> class <class name>
{
// attributes / instance variable / constructors / methods
}
Syntax to create an object in Java:
<class name> <reference variable name> = new <constructor call>
Variables and methods declared inside a class are treated as members of that class.
members = variables + methods
Always non static members are placed inside the object.
Non static variables declared within a class are called as attributes.
Constructors are never treated as members of the class.
Access Specifiers
An access specifier specifies how the members of a class and the class itself can be accessed
in a program.
An access specifier provides scope to the members of a class.
There are four access specifiers present in java.
1) private 2) public 3) protected 4) <default>
Out of these four access specifiers the 1st three are keywords, where as default is not a
keyword of java.
private: In java a class cannot be defined with private access specifier, This is because a
private class will never be available to JVM, however members of a class can be made
private, where the scope of the members will become limited, that is the private members
of a class will be accessible within the class, to whom they will belong, but they cannot
be accessible to other classes of the same program as they are not visible to other classes.
default: If a class or any of its member defined without any access specifier, then we say
the class or its members are under default or friendly access specifier.
Other than package there is no difference between public, protected, default.
Constructor:-
Q) What is Constructor?
It’s a special method used for object initialization, it is special because :-
Name of the constructor must be same as class name.
13
Constructor never returns any value hence it doesn’t have any return type.
We can’t call a constructor explicitly like a method, constructor is called only once i.e.
during the object creation time.
Constructors are never treated as member of any class.
It cannot be attached with static, abstract and final keyword.
14
Use of “static” keyword in java:
Variables and methods, declared within a class are called as members of that class.
In java there are two types of member present, they are:-
1) Static members 2) Non-static members
1) Members declared with static k/w 1) Members declared w/o static k/w
2) Can be accessed directly through 2) Can be accessed only through
class name or interface name object reference
3) Can be accessed before object creation 3) Can be accessed only after object creation
4) Occupies memory from the context area 4) Occupies memory from the heap area
5) Occupies one time fixed memory, which 5) Occupies separate memory for separate
is common for all objects objects.
All the static members of a class are accessible in three ways within the same class,
irrespective of (static method and non static method). The ways are,
( i ) directly (ii) object reference (iii) class name or interface name.
A static method can’t access non-static members of the same class, directly. It always
requires object reference.
But a non-static method can access non static members of the same class, in two ways that is
( i ) directly (ii) object reference
As Constructors are never treated as members, hence we can’t apply static key word for
the constructors.
From one class we can access both static and non-static members of other class.
Through the class name we can access static members, but to access non-static members, it is
must to create an object of that class.
15
Inheritance :-
Q) What is inheritance?
It’s a mechanism used to acquire the properties of an existing old class by a newly created
class. The existing class is called as Parent (or Base or Super) class and the newly created
class is called as Child (or Derived or Sub) class.
Over-riding Over-loading
Signature and return type should be same Signature should be different & return type
may or may not be same
Which method will execute that depends Which method will execute that depends on
on type of the object. no. and type of arguments we are passing.
JVM decides which method to execute at Compiler decides which method to execute
Run-Time at Compile-Time
17
NOTE:
We have to declare abstract methods and abstract classes with abstract key-word otherwise
we will get Compile time error.
We can’t create object of abstract class, but we can create reference object of abstract class.
Child class has to provide implementation to all the abstract methods, otherwise child class
will become abstract.
Both Parent and Child class methods must be defined with same access specifier in order to
achieve Runtime Polymorphism.
NOTE:
Final Variables ------------------------ Modification not possible.
18
Interface :-
It’s a mechanism in java used to achieve abstraction.
All the methods inside an interface should be abstract.
All the variables inside an interface should be final.
We can’t create object of an interface, but we can create reference object of it.
After compilation the Compiler attaches :-
public static final to each interface variable and
abstract public to each interface method
A child class has to implement all the interface methods otherwise, we will get compile time
error.
Creating an implementation class for an interface means, we have to create a child class of
that interface & within that child class we have to override all the interface methods.
Static members of interface can be accessed directly through interface name.
Within the child class we must override all the interface methods as public else we will get
compile time error.
Interface is used to define different role or behaviour of an Object.
we can achieve multiple inheritance through interface but not through classes in Java.
Requirement:
Class A wants to access show( ) method present in Class B.
package pack;
public class B {
Class A Class B
public void show() {
System.out.println(“show() of B”);
} Show(
}
D:\> javac –d . B.java
Present out Package Pack
import pack.B; side of the package pack
class A{ d:\>
public static void main ( String[] args) {
B b = new B();
b.show();
}
}
D:\> java A
20
NOTE:
We can access only the public classes and public members from outside of the package.
To access a class ( present within a package) from another class ( present outside of the
package), we need to place import statement within the accessing class.
package pack1.pack2;
class A
{ Pack1
void show()
{ Pack2
System.out.println( “show() of A”); Class A
}
public static void main(String[] args) show()
main()
{
A x = new A();
x.show();
d:\>
}
}
D:\> javac –d . A.java
21
Use of ‘*’ in import statement :-
package pack3; Pack3
class B { Class B Class C Class D
void m1() { m1()
System.out.println (“m1() of B”);
}
m1() m2() m3()
}
package pack3;
class C {
void m2() {
System.out.println (“m2() of C”);
}
}
package pack3;
class D{
void m3() {
System.out.println (“m3() of D”);
}
}
import pack3.B;
import pack3.C;
import pack3.D;
// or
import pack3.*;
class A
{
public static void main(String[] args)
{
B x = new B ();
x.m1();
C y = new C();
y.m2();
D z = new D();
z.m3();
}
}
22
D:\> javac A.java
D:\> java A
Compile time error will occur because the classes and methods present in pack3 are not in
public access.
NOTE :-
‘*’ in import statement only imports the classes within a package but not the classes within a
sub package. Hence to import the classes within a sub package, we have to specify the sub
package name in the import statement.
Requirement: ‘A’ want to access all the classes present in package pack5
Pack-4
Class B Class C Class D
//import pack4.*;
import pack4.pack5.*; M1() M2() M3()
class A { Pack-5
public static void main ( String[] args) {
E e = new E();
Class E Class F
e.m4();
} M4() M5()
}
Alternative way to import statement :-
Fully qualified class name is an alternate way to the import statement.
Pack-1
import pack1.pack2.B;
Pack-2
class A {
Psvm(--) { Class B
B x = new B( ); M1()
x.m1 ( );
}
}
class A {
psvm(--){
pack1.pack2.B x = new pack1.pack2.B( );
x.m1 ( );
}
}
23
NOTE :
Within the package there is no difference between public, protected and default.
public : Any one can access and any where it is accessible .
protected : All classes of the same package and only the child class can access the protected
members of a class, no matter in which package the child class is present.
<default> : Only within the package we can access the default members.
private : Only within the same class, we can access.
D E
24
class C extends B
{
private int x1;
private void m1()
{
// CE : attempting to assign weaker access privileges
System.out.println (“m1() method of C..”);
}
}
Command Line Argument :-
If we want, we can also pass arguments from the command line to our java program,
arguments passed from the command prompt are known as command line arguments.
Arguments passed from the command line are always treated as String type.
Command line arguments are stored in the String array ( String [ ]) of main( ) method, we
can retrieve these values by specifying index position.
main( ) method :-
Q) Why signature of main is static?
JVM always calls main( ) method through the class name, hence it needs to be static.
25
class Parent
{
public static void main ( String [ ]args)
{
System.out.println ( “\n\t Parent class main( ) method”);
}
}
class Child extends Parent
{
}
>java Child
o/p : - Parent class main( ) method
Exception Handling :-
Exception Hierarchy Diagram :-
Object
Unchecked
Exception
Throwable
Exception Error
Q) What is Throwable?
Throwable is the Root of entire Exception Hierarchy. Throwable is a class that represents
all errors and exceptions, which may occur in java.
If a method is throwing any checked exception, then calling to that method is a risky code. If
our code contains such type of risky code, then compiler won’t compile our code unless and
until we have placed that method call within try block or we have used throws key word in
the calling methods prototype.
But finally block executes always irrespective of exception raise or not in the try block.
28
Q) What are the methods available to print exception related message?
Throwable class defines the following three methods to print exception message.
Keyword Purpose
try : To maintain Risky Code.
catch : To maintain Handling Code.
finally : To maintain Clean up Code.
throws : To delegate responsibility of Exception Handling to the caller.
throw : To hand over our own exception object to the JVM explicitly.
java.lang package:-
To develop a java program the most required java classes and interfaces are packaged into
java.lang package.
Object class:
Directly or indirectly Object is the super class for every java class.
class A { Object Direct super class of A
------------
}
class A
{ Object Direct super class of A
------------- &
}
class B extends A Indirect super class of B
{
-------------
}
29
Methods of Object Class:-
1) getClass( ) :-
It returns the run time class object for this class.
2) hashCode( ) :-
JVM assigns an unique number to every object, which is known as hashCode, it is not the
address of an object.
We can get it by calling hashCode() method.
hashCode is helpful while storing an object into hash-based data structure like Hash-Table,
Hash-Map, Hash-Set( i.e. JVM stores objects into these data structures based on their
hashCode).
3)clone( ) :-
It will create a clone object.
Creating exactly duplicate copy of an existing object is called cloning.
Cloning is of two types
Deep Cloning(Creating duplicate object)
Shallow Cloning(Creating duplicate reference)
We can perform cloning only on cloneable object, if we try to perform cloning on non
cloneable object then we will get runtime exception.
The object whose corresponding class implements Cloneable interface, that object is called
as Cloneable object.
4) toString( ) :-
We can use this method to get the string representation of any object.
Whenever we try to print any object reference, internally toString() method is called,
Object class toString() method is implemented to return in the format
< className > @ < hashCode ( in hexa-decimal format) >
We can also over-ride Object class toString() method in our class, according to our
requirement.
5) equals( ) :-
equals() method is used to check the equality of 2 objects ( i.e. the reference number referred
by two objects will be checked)
It returns true if reference number referred by two objects is same else it will return false
Object class equals( ) method and (= =) operator both performs reference comparison.
30
String Class :-
It’s a predefined class belongs to java.lang package.
String objects are Immutable in nature (i.e. Once a String object is created, It can’t be
changed through invoking method).
Q) What is the process of creating String object using String class constructor?
1) public String( )
String s = new String( );
31
Q) What are the methods available in String Class?
1) public char charAt ( int index )
String s = “Techbuzz”;
Sop ( s.charAt(4) ); // b
Sop ( s.charAt (9) ); // RE: StringIndexOutOfBoundsException
32
9) public String toLowerCase( )
String s1 = “Core Java”;
Sop ( s1.toLowerCase ( ) ); // core java
Q) What is the difference between equals() method of Object Class and String Class?
class A class B
{ {
psvm(String args[]) psvm(String args[])
{ {
A x = new A(); String s1 = new String(“Hello”);
A y = new A(); String s2 = new String(“Hello”);
Sop(x.equals(y)); Sop(s1.equals(s2));
} }
} o/p : false } o/p : true
Object class equals() method is meant for reference comparison.
String class equals() method is meant for content comparison.
33
String Buffer Class :-
It’s a predefined class belongs to java.lang package.
It’s a final class.
StringBuffer objects are Mutable in nature.
Length : No of Characters already Present.
Capacity : No of Characters that can be accommodated( placed).
1) public StringBuffer ( )
Creates a StringBuffer object with default initial capacity 16. if StringBuffer reaches its
max capacity, then a new StringBuffer object will be created with.
34
3) public char charAt ( int index)
StringBuffer sb = new StringBuffer (“abcdef” );
Sop ( sb.charAt ( 2) ); // c
Sop ( sb.charAt ( 8) ); // RunTimeException
s.concat(“World”); sb.append(“World” );
sb
s
String class over-rides the Object class StringBuffer class doesn’t over-ride the equals( )
equals( ) method for content comparison. method, hence in the above case Object class
equals( ) method will be invoked.
36
StringBuilder Class :-
StringBuffer StringBuilder
All methods of StringBuffer are synchronized No method in StringBuilder is synchronized
At a time only one thread can access the At a time any number of threads can access
StringBuffer object the StringBuilder object
Thread safe Not thread safe
Introduced in 1.0 Introduced in 1.5
Wrapper Class :-
In java we are having following 8 Wrapper Classes.
Byte, Short, Integer, Long, Float, Double, Character, Boolean.
Wrapper objects are Immutable i.e. once a wrapper object is created we can’t change its
content, if we try to do so, then with those changes a new Wrapper object will be created.
1) valueOf ( )
2) xxxValue ( ) [ intValue ( ), longValue ( ), floatValue ( ) etc ]
3) parseXxx ( ) [ parseInt ( ), parseFloat ( ), parseDouble ( ) etc ]
4) toString ( )
1) valueOf( ) method:
37
It is used to convert primitives and String into Wrapper Object.
Integer I = Integer.valueOf ( 10 );
Integer I = Integer.valueOf ( “10” );
2) xxxValue( ) method:
It is used to extract the primitive value from the Wrapper object.
3) parseXxx ( ) method:
It is used to convert String values into primitive values.
4) toString( ) method:
It is used to convert primitives and Wrapper objects into String.
String s = I.toString ( );
38
String
valueOf( ) parseXxx( )
Q) What is Auto-boxing and Auto-unboxing?
Auto-boxing: Converting a Primitive value into Wrapper object.
Auto-unboxing: Converting a Wrapper object into primitive value.
From java 1.5 onwards we can provide Wrapper objects and primitives interchangeably,
meaning, wherever Wrapper object is required, we can provide primitives and wherever
primitive is required, we can provide Wrapper object, compiler will do the required
conversion.
39
valueOf()
toString( ) toString( )
Primitive
Wrapper Object
Type
xxxValue( )
Auto-unboxing ()
xxxValue()
valueOf( )
class Test
{
static Integer I = 10; // AB
java.io package :-
40
Java.io pkg
Q) What is stream?
Flow of data from one place to another place in form of bytes, is called as Stream.
It is of two types.
o i/p Stream -----------> Stream in which input data flows.
o o/p Stream -----------> Stream in which output data flows.
InputStream Class :-
It is an abstract class.
It is used to read data from an input stream.
It contains 3 read methods, out of which the 1st read method is abstract.
1) public abstract int read( ) throws IOException
2) public int read( byte [ ]b ) throws IOException
3) public int read( byte [ ]b, int off, int len ) throws IOException
Hence the child class of InputStream should provide implementation to the no argument
read() method.
3) public int read( byte [ ]b, int off, int len ) method :
It reads up to len bytes of data from the input stream into byte array b.
The first byte read is stored into b[off], the next one into b[off+1], and so on.
It returns the no of bytes read into the byte [ ]b, and returns -1 if no more data is available
to read.
FileInputStream :-
It’s a child class of InputStream and has provided implementation to the no argument read( )
method of InputStream.
InputStream
abstract read( );
read(byte[] ) {- - - }
read( byte[], int, int ) {- - -}
FileInputStream
read ( )
{
---------
}
fis abc.txt
Note :-
42
FileInputStream constructor :- throws FileNotFoundException
read( ) method :- throws IOException
Hence we have to handle these exceptions using try- catch or we have to use throws clause in
main( ) method.
FileNotFoundException, IOException, FileInputStream :- All belong to java.io package,
hence we have to import java.io package in our class.
DataInputStream :-
The limitation with FIS is we can’t read line by line, rather we can read one char at a time.
But DIS supports reading one line at a time.
To read one line at a time DIS contains readLine( ) method.
public String readLine( ) throws IOException
It reads one line and returns it as String. It returns null if no more line is there to read.
We can’t directly attach the DIS object into a file, hence
1) We have to create a FIS object and attach it to the fie
2) Create a DIS object and attach it to the FIS object.
SequenceInputStream :-
It supports reading from multiple files.
For reading operation it contain following 2 read methods.
1) read( ) : no argument read method
2) read( byte[ ], int, int ) : byte array argument read method
Here also we can’t attach the SIS object directly to the file, hence
1) We have to create FIS object and attach it to the file
2) Create a SIS object and attach it to the FIS object
OutputStream :-
It is an abstract class.
It is used to write data to a output stream.
It contains 3 write methods, out of which the 1st write method is abstract.
1) public abstract void write( int b) throws IOException
2) public void write ( byte[ ] b ) throws IOException
3) public void write( byte[ ] b, int off, int len) throws IOException
Hence the child class of OutputStream should provide implementation to the 1st write ( )
method.
43
FileOutputStream :-
It’s Child class of OutputStream and has provided implementation to the int argument
write( ) method of OutputStream.
OutputStream
abstract write( int);
write( byte[] ) {- - - }
write( byte[], int, int ) {- - -}
FileInputStream
write (int b)
{
---------
}
If the file doesn’t exist, then the specified file will be created and a FOS object will be
attached with that file.
If the file already exists, then a FOS object will be attached with that file.
FileOutputStream fos = new FileOutputStream(“abc.txt”);
Note :-
If the specified file doesn’t exist then a new file with that name will be created and FOS
object will be attached with that file.
If the specified file exists then only the FOS object will be attached with that file.
Note :-
To append ‘A’ with current file content we should pass true as 2nd arg to the FOS constructor,
as follows
44
DataOutputStream :-
The limitation with FOS is, we can’t write one line at time. Hence to overcome this
limitation we should go for DataOutputStream.
DataOutputStream contains writeBytes( ) method to write one line of data at a time.
public void writeBytes( String s ) throws IOException
PrintStream :-
To perform line by line write operation, we should go for PrintStream instead of
DataOutputStream.
Serialization vs Deserialization :-
Serialization : The process of storing the state information of an object into a file.
Deserialization : The process of creating an object by reading it’s state information from
the file.
45
Multi Threading :-
Multi threading is the concept to perform multiple operations concurrently.
Q) What is Thread?
Thread means execution sequence (set of statements).
Approach-1 Approach-2
class MyThread extends Thread class MyThread implements Runnable
{ {
public void run( ) public void run( )
{ {
// Job of a thread // Job of a thread
} }
} }
No matter in which approach we are creating a thread class, but we must over-ride the run()
method within our thread class.
Code within run() method is called as JOB of child thread.
46
Methods of Thread Class :-
1) run( )
2) interrupt( )
3) join( ), join( long ms), join( long ms, int ns)
4) setName( String name)
5) getName( )
6) setPriority( int newPriority)
7) getPriority( )
8) sleep( long ms), sleep( long ms, int ns)
9) yield( )
10) start( )
Requirement: Child thread should print 1 to 10 and Main thread should print 11 to 20
Class MyThread extends Thread {
//Over-riding Thread class run( ) method
public void run( ) {
// job of child thread
for( int k=1; k<=10; k++) {
System.out.println(“Child Thread: “ + k);
}
}
}
class Test {
public static void main( String[] args) {
MyThread t = new MyThread ( );
t.start( );
// job of main thread
for (int i=11; i<=20; i++) {
System.out.println(“Main Threads: “ + i);
}
}
}
Thread
run ( )
run ( ) MyThread
start ( )
t.start( ) Now the thread t will go into
t Ready state.
Unless until a thread goes into
Ready state, it’s run( ) method
Object of MyThread won’t execute.
47
Thread Life Cycle ( Thread State Diagram )
Let’s thread t2 wants to wait for thread t1, then t2 has to call join( ) method on t1.
It has three join() method, they are :-
case 1: If there is no waiting thread or all the waiting threads have lower priority then,
current thread will continue its execution.
case 2: If all remaining waiting threads have same priority then, which thread will execute
that depends upon Thread Scheduler.
Thread Priority :-
Each and every thread in java has some priority ( an integer number)
If we want we can get and set the priority of a thread using 2 methods
1) public final void setPriority (int newPriority )
2) public final int getPriority ( )
Priority of a thread ranges from 1 to 10
Priority 1 = Min priority
Priority 5 = Norm priority (Default Priority)
Priority 10 = Max priority
If we try to set any value other than this range, then we will get exception
IllegalArgumentException
NOTE :-
Priority of a thread traverse from parent to child, meaning what priority parent has, that will
be assigned to the child.
Thread Synchronization :-
It is a technique used in java to avoid Data Inconsistency Problem.
Synchronized is the key word applicable only for methods and blocks, but NOT for classes
and variables
Synchronized --------> methods, blocks
Synchronized --------> classes, variables
o Advantage of Synchronization
Data Inconsistency Problem resolved
o Disadvantage of Synchronization
49
Waiting time of thread increases, hence performance decreases
Internally Thread-Synchronization has been implemented using lock concept. So before
executing any synchronized method or synchronized block, a thread has to first acquire this
lock and after completion of it’s job, the thread has to release that lock.
Inter-Thread Communication :-
One thread can communicate with another thread, communication between threads is called
as inter-thread communication.
One thread can communicate with another thread by wait( ), notify( ) and notifyAll( )
methods.
+
1) public final void wait( ) throws InterruptedException
2) public final native void wait( long ms) thows InterruptedException
3) public final void wait( long ms, int ns) throws InterruptedException
Producer-Consumer Problem :-
P = > Producer
C = > Consumer
Q = > Queue
Conditions :-
‘P’ has to produce item for ‘Q’ and ‘C’ has to consume item form ‘Q’
If ‘Q’ is empty ‘C’ has to wait ( ‘C’ has to call wait ( ) method on ‘Q’ )
After producing the items in the ‘Q’, ‘P’ has to inform the ‘C’ (‘P’ has to call notify ( )
method on ‘Q’, so that waiting thread ‘C’ can get the notification & consume the items)
At a time ‘P’ should produce the item OR ‘C’ should consume the item.
50
P Q C
Collection ( interface)
If we want to maintain group of objects as a single unit, where we don’t want duplicacy & don’t
want to preserve insertion order, then we should go for Set.
51
If we want to maintain group of objects as a single unit, where duplicacy is allowed & insertion
order must be preserved, then we should go for List.
List :-
ArrayList :- It’s an implementation class for list interface.
Constructor of ArrayList :-
Public ArrayList( ) : It creates an empty ArrayList Object with default capacity 10.
Once ArrayList reaches its maximum capacity, a new ArrayList object will be created with new
capacity.
New Capacity = ( Current Capacity * 3 / 2 ) + 1
What happens internally on adding 11th element to ArrayList
A new ArrayList object will be created with capacity 16 i:e (10 * 3 / 2) + 1 = 16
All elements in old ArrayList will be copied into new ArrayList. Now 11th element will be added
into new ArrayList object & finally this new ArrayList object will be returned.
add() method :-
add is an overloaded method within ArrayList.
add( - ) : It will add an element at the next available index
add( -, -) : It will add an element at a specified index position
Constructor of Vector :-
52
public vector() :- Creates an empty vector object with default capacity 10.
Once vector reaches its maximum capacity, a new vector object will be created with new
capacity.
New capacity = 2 * current capacity.
Vector is a Legacy class i.e. old class because it was introduced in 1.0 version.
53
HashMap( child class) Hashtable( child class)
Map ( interface):-
Map is not a child interface of collection. It is an independent interface.
If we want to represent a group of objects as key-value pairs then we should go for Map.
Map is NOT the child interface of collection.
In Map both key and value should be of object type.
Each key value is called one entry.
Duplicate keys are NOT allowed but values can be duplicated.
Applet
54
An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java
application because it has the entire Java API at its disposal.There are some important
differences between an applet and a standalone Java application, including the following –
An applet is a Java class that extends the java.applet.Applet class.
Java.applet.* is the smallest package in java.This package has only one calss i.e Applet
class.
We can draw something on the applet through a designing package i.e java.awt.*.
A main() method is not invoked on an applet, and an applet class will not define main().
Applets are designed to be embedded within an HTML page.
When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
Applets have strict security rules that are enforced by the Web browser. The security of
an applet is often referred to as sandbox security, comparing the applet to a child playing
in a sandbox with various rules that must be followed.
Other classes that the applet needs can be downloaded in a single Java Archive (JAR)
file.
We can write an applet program through the following steps.
init() − This method is intended for whatever initialization is needed for an applet. The
init() will execute when the applet will start or restart or at the maximize time.
start() − This method is automatically called after the browser calls the init() method. It
is also called whenever the user returns to the page containing the applet after having
gone off to other pages. And also executes at the maximize time.
paint() − Invoked immediately after the start() method, and also any time the applet
needs to repaint itself in the browser. The paint() method is actually inherited from the
java.awt. paint() takes a graphics class type argument.
stop() − This method is automatically called when the user moves off the page on which
the applet sits. It can, therefore, be called repeatedly in the same applet.
destroy() − This method is only called when the browser shuts down normally. Because
applets are meant to live on an HTML page.
import java.applet.*;
import java.awt.*;
public class HelloWorldApplet extends Applet {
public void paint (Graphics g) {
g.drawString ("Hello World", 25, 50);
}
}
These import statements bring the classes into the scope of our applet class −
java.applet.Applet
java.awt.Graphics
Without those import statements, the Java compiler would not recognize the classes Applet and
Graphics, which the applet class refers to.
56