Core Java Soft PDF
Core Java Soft PDF
Core Java Soft PDF
(J2SE)
Read – Understand – Imagine – Think – Apply – Create – Deliver – Update
Note:
1. As a programmer, we need to develop applications/interfaces.
2. Using interfaces every End-user can easily interact with the machine without having
background knowledge.
3. Interface is nothing but application/software.
4. A screen which provides instructions to end-user to perform the transaction.
Note:
1. All the programming languages are pre-defined applications.
2. And these applications are standalone.
3. We must install programming language software into machine, dependents on OS.
Platform dependency:
C & C++ languages are platform dependent. Hence we can develop only standalone apps.
C-compiler is OS-dependent; hence it translates source code into specific OS understandable
instructions.
Hence the instructions generated by C-compiler become platform-dependent.
Java versions:
Following diagram describes release of different versions of Java software.
Learning these things is not that much important but it is recommended to be good at basic
things of Java programming language also.
First Versions released by “Sun Micro Systems”
In the year 2010, “Oracle Corporation” acquired “Sun Micro Systems” and the next 2 versions
released by “Oracle”
Installation of JDK:
The following diagram describes, what are the things will be installed into machine when we
install JDK-kit.
JRE:
Stands for Java Runtime Environment.
To execute any program “Environment setup” is required, for example to take the java class
– we need class room environment, to watch a movie – theatre environment ….
C and C++ applications run in Original OS environment. But java and .net applications having
their own environments called JVM(Java Virtual Machine)….
JIT:
Stands for Just In-time interpreter.
Translates JVM understandable code into a specific machine understandable code.
Works under JVM.
Works in Virtual Environment.
Platform Independency:
Java is the Platform independent language.
Java compiler plays key role in independency.
C-compiler is platform dependent; hence it generates only a specific OS understandable
instruction set.
Java compiler is dependent to JVM (virtual OS), hence it generates, JVM understandable
instructions.
JVM instructions once again interpreted by JIT into a specific OS understandable instructions.
Examples:
Object type: Human
Identity : Shyam
Properties : Color, Height, Weight, Age, Qualification......
Functionality : read( ) , see() , walk( ), swim( ), drive( ), teach( )......
Note:
1. Objects will participate in the process of communication using functionality (methods).
2. In the process of communication, Objects will share properties information.....
Encapsulation:
Concept coming from "capsule".
Whatever the content which is inside the capsule is sensitive, hence protected with cap.
We need to protect complete information of object......
Encapsulation is the concept of protecting object information by placing properties and
functionality as a block...
class / Encapsulation{
properties
+
methods
}
By Srinivas (C/DS/Java trainer) Page 11
Encapsulation ---> theory...
class ---> technical implementation in object oriented programming.....
Inheritance:
Defining new Object with the help of existing object.
Releasing next version of existing object.....
Existing system ---> proposed system....
Abstraction:
Hiding unnecessary details of Object and shows only essential features to communicate.
Abstraction lets you know how to communicate with object
Abstraction cannot provide information about what is happening in the background.
General example:
Generally static context of Object we can access directly.
Freely accessible area must be defined as static in java
Specific functionality of object must be declared as non-static.
Permissions are required to access non-static area.
Mostly permissions are available to access non-static area in static only.
Following example describes clearly.
Technical example: The following example represents the technical way, how we are defining and
access members of static and non-static.
Variable:
1) Providing identities to standard memory locations.
2) Without identities we cannot access the data once it has been stored.
3) Named memory location.
4) Using variables we can process the information effectively.
Block:
1) Set of Instructions having no identity…..
2) We cannot call explicitly (because of no identity)….
3) JVM invokes implicitly every block in the process of application execution…….
4) Block providing basic information to start communicates with object.
5) General blocks such as while, for, if… used to define logical programming.These blocks also
cannot be called explicitly in the program.
Questions:
1. What is the use of block?
2. What type of information need to place inside the block?
3. When block get executes?
Answer:
To start communicating with any object, basic information is required.
By Srinivas (C/DS/Java trainer) Page 16
Static block & non-static blocks are responsible for providing basic info of object
We can communicate with any object with the available information only.
Method:
1. A block of instructions having Identity.
2. Every method is taking input, processing input and returns output.
3. Every method must be called explicitly (using its identity).
Block Method
Block of instructions Block of Instructions
No identity Having identity
Can’t take input Can take input
Can’t produce output Can produce output
Can’t call explicitly Must be called explicitly
Note:
Every java developer should maintain this documentation to develop java applications.
Instead of searching the documents online, free downloads available for basic java
developers.
Instead of maintain data connection (internet) we can go for website downloads.
Accept the license agreement and download the jdk kit depends on OS you are using…
Program.java :
class Test
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
class Test
{
// empty ….
}
class Test
{
public static void main(String arg[ ])
{
System.out.println("Main method....");
}
}
class Test
{
static
{
System.out.println("Static block....");
}
public static void main(String arg[ ])
{
System.out.println("Main method....");
}
}
class Test
{
public static void main(String arg[ ])
{
By Srinivas (C/DS/Java trainer) Page 29
System.out.println("Main method....");
}
static
{
System.out.println("Static block....");
}
}
class Test
Question : When we use more than one static block in the application?
Answer : If class loading info(basic info) is lengthy, we divide into
modules(static blocks).
Modularity:
Dividing logic into blocks
For example in Bank application divides into modules like “savings
account”, car loan, home loan, current account…..
Advantages are
o We can share the work
o Easy to integrate
o Easy to debug (error).
class Test
{
public static void main(String[] args)
{
System.out.println("Main method starts....");
Test.fun( ); // method call --> single statement
System.out.println("Main method ends....");
}
class Test
{
public static void main(String[] args)
{
System.out.println("main starts");
Test.fun();
System.out.println("ctrl back to main method....");
}
class Test
{
static void f1( )
{
System.out.println("ctrl in f1....");
}
static
{
System.out.println("static block starts....");
System.out.println("Calling f1 method...");
Test.f1();
System.out.println("control back to static block from f1");
System.out.println("static block ends....");
}
Local variable:
Declaration of variable inside the block or method.
Local variable must be initialized before its use.
Local variables we can access directly.
class Test
{
public static void main(String[] args)
{
int a ; // local variable
// System.out.println(a); // Error : Not yet initialized...
a = 10 ;
System.out.println(a);
}
}
class Test
{
static
{
int a = 10 ; // local
System.out.println(a); // allowed to access
}
public static void main(String[] args)
{
// System.out.println(a); // Error : undefined symbol
}
}
JVM architecture:
Every java application run by JVM
JVM is having many areas (mainly 3) to run java application.
Generally every application will be processed in main memory (RAM).
As soon as application has invoked, processor allocates memory to JVM
inside RAM memory.
Once application has been completed, the memory will be destroyed.
Static variable:
class Test
{
static int a = 100 ;
static
{
System.out.println("Static block");
System.out.println(Test.a);
}
public static void main(String[] args)
{
System.out.println("Main method");
System.out.println(Test.a);
}
By Srinivas (C/DS/Java trainer) Page 39
}
Note: Static block & static variable is having equal priority. Hence these
members execute in the defined order.
class Test
{
public static void main(String[] args)
{
System.out.println("Main method");
By Srinivas (C/DS/Java trainer) Page 40
System.out.println(Test.a);
}
static
{
System.out.println("Static block");
System.out.println(Test.a);
}
static int a = 100 ;
}
/*
static variable : access using class name
local variable : direct access
*/
class Test
{
static int a = 100 ;
public static void main(String[] args)
{
System.out.println(Test.a); // access static variable directly
System.out.println(a); // first it is looking for local variable. if it is
not present, it will access global variable
}
}
class Test
{
static int a = 10 ;
public static void main(String[] args)
{
int a = 20;
By Srinivas (C/DS/Java trainer) Page 42
Test.a = Test.a + a ;
a = a + Test.a ;
Test.a = Test.a + a + Test.a ;
System.out.println(Test.a);
System.out.println(a);
}
}
class Test
{
static
{
int a = 20 ;
System.out.println("Global a : "+Test.a);
Test.a = Test.a + a ;
}
static int a = 10 ;
public static void main(String[] args)
{
System.out.println("Global a : "+Test.a);
}
}
class Test
{
static
{
int a = 20 ;
Test.a = Test.a + a ;
a = a + Test.a ;
Test.a = a + a ;
}
static int a = 10 ;
public static void main(String[] args)
{
System.out.println("Global a : "+Test.a);
}
By Srinivas (C/DS/Java trainer) Page 43
}
class Test
{
static
{
int a = 20 ;
Test.a = Test.a + a ;
a = a + Test.a ;
Test.a = a + a ;
}
static int a ;
public static void main(String[] args)
{
System.out.println("Global a : "+Test.a);
}
}
class Test
{
static
{
int a = 20 ;
Test.a = a + a ;
}
static int a ;
public static void main(String[] args)
{
System.out.println("Global a : "+Test.a);
}
static
{
a = a + Test.a ;
}
}
class Test
{
static int a ;
class Test
{
static int a ;
public static void main(String[] args)
{
System.out.println(Test.a);
Test.a = Test.initialize();
System.out.println(Test.a);
}
static int initialize()
{
return 100 ;
}
}
class Test
{
static int a ;
public static void main(String[] args)
{
System.out.println(Test.a);
Test.initialize(100);
System.out.println(Test.a);
}
static void initialize(int x)
By Srinivas (C/DS/Java trainer) Page 45
{
Test.a = x ;
}
}
class Pro1
{
By Srinivas (C/DS/Java trainer) Page 47
static int a = 50 ;
public static void main(String[] args)
{
System.out.println(Pro1.fun()+Pro1.a);
}
static int fun()
{
Pro1.a = Pro1.a +100;
return Pro1.a;
}
}
class Pro1
{
static int a = Pro1.fun();
public static void main(String[] args)
{
System.out.println(Pro1.a);
}
static
{
System.out.println(Pro1.a);
Pro1.a = Pro1.a+20 ;
}
static int fun()
{
Pro1.a = 50;
return Pro1.fun1();
}
static int fun1()
{
System.out.println(Pro1.a);
return 100;
}
}
Constructor:
Special java method.
Constructor name & Class name should be same.
Return type is not allowed.
Used to initialize non-static(instance) variables.
We need to call constructor explicitly in the process of object creation.
Non-static block:
Defining a block with no identity.
We can’t access explicitly.
JVM invokes implicitly as soon as object has created.
class Test
{
int a ; // non-static variable
By Srinivas (C/DS/Java trainer) Page 50
Test()
{
System.out.println("Constructor");
}
{
System.out.println("Non-static block");
}
Note: static block executes only once in the application at the time of class loading.
But non-static block and constructor executes every time in the process of object creation.
class Test
{
By Srinivas (C/DS/Java trainer) Page 51
static
{
System.out.println("Class loading...");
}
Test()
{
System.out.println("Object initialization process....");
}
{
System.out.println("Object creation process....");
}
Note: In the process of Compilation, compiler is looking for constructor definition in the java
source file. If not present, Compiler will supply a default constructor.
Default constructor is not taking any arguments and with empty definition.
class Test
{
public static void main(String[] args)
By Srinivas (C/DS/Java trainer) Page 52
{
new Test(); // No error : invokes default constructor
}
/*Test()
{
System.out.println("Constructor");
}*/
}
this:
It is a keyword.
It is a pre-defined non static variable.
It holds object address.
It must be used only in non-static context.
class Test
{
static
{
System.out.println(this); // Error :
}
{
System.out.println(this); // allowed
}-
}
Note : “this” keyword points to only one object at a time among available objects in Heap
area
class Test
{
public static void main(String args[ ])
{
new Test();
new Test();
new Test();
}
Test()
{
System.out.println(this);
}
}
class Employee
{
int eno ;
By Srinivas (C/DS/Java trainer) Page 56
String ename ;
float esal ;
public static void main(String[] args)
{
Employee e = new Employee();
System.out.println("Eno : "+e.eno);
System.out.println("Ename : "+e.ename);
System.out.println("Esal : "+e.esal);
}
}
Create object inside static block and assign object reference to static variable:
class Test `
{
static int a ;
static
{
System.out.println(Test.a);
Test.a = 100 ;
}
Create object inside static user method and assign it to static variable:
class Test class Test
{ {
static int a ; static Test obj ;
public static void main(String[] args) public static void main(String[] args)
{ {
System.out.println(Test.a); System.out.println(Test.obj);
Test.initialize(); Test.initialize();
System.out.println(Test.a); System.out.println(Test.obj);
} }
static void initialize() static void initialize()
{ {
Test.a = 100 ; Test.obj = new Test() ;
} }
} }
Default initialization:
class Test
{
int a ;
public static void main(String[] args)
{
Test obj = new Test();
System.out.println("a value : "+obj.a);
}
}
class Test
{
int a ;
Test(int x)
{
a = x ; // local variable value assigned to non-static variable(with the name ‘a’ local
variable is not present)
}
public static void main(String[] args)
{
Test obj = new Test(10);
System.out.println("a value : "+obj.a);
}
}
class Test
{
By Srinivas (C/DS/Java trainer) Page 59
int a ;
Test(int a)
{
a = a ; //local variable value re-assigned to local variable only.
}
public static void main(String[] args)
{
Test obj = new Test(10);
System.out.println("a value : "+obj.a);
}
}
class Test
{
int a ;
Test(int a)
{
this.a = a ; // local variable value is assigned to non-static variable
}
public static void main(String[] args)
{
Test obj = new Test(10);
System.out.println("a value : "+obj.a);
}
}
void fun()
{
System.out.println("non-static user method....");
}
}
class Test
{
static Test obj = new Test() ; // 'obj' is static variable
public static void main(String[] args)
{
Test.obj.fun();
}
void fun()
{
System.out.println("non-static user method....");
}
}
1. Create object inside static block and assign address to static variable.
2. Access non-static user method using object reference variable from main method.
class Test
{
static Test obj ;
static
{
Test.obj = new Test();
}
public static void main(String[] args)
{
System.out.println("Main method");
Test.obj.fun();
}
void fun()
{
System.out.println("non-static user method");
}
}
class Test
{
static
{
System.out.println("a value : "+Test.a);
}
public static void main(String[] args)
{
System.out.println("a value : "+Test.a);
}
static int a = 100 ;
static
{
Output should be :
class loaded with static block
execution starts at main method
non-static block
constructor
execution ends at main method
class Test
{
int a ;
Test( )
{
this.a = 100 ;
}
public static void main(String[] args)
{
new Test();
}
}
a. declare a static variable of class type and initialize directly using object reference.
b. define static block.
c. define main method.
d. define non-static user method
e. invoke non-static user method from static block and main method.
class Test
{
static Test obj = new Test();
static
{
Test.obj.fun();
}
public static void main(String[] args)
{
Test.obj.fun();
}
void fun()
{
System.out.println("non-static user method.....");
}
}
class Test
{
static Test obj ;
Test( )
{
Test.obj = this ;
}
public static void main(String[] args)
{
new Test( ) ;
System.out.println(Test.obj);
}
}
class Demo
{
static Demo obj1 ;
Demo obj2 ;
Demo()
{
this.obj2 = this ;
}
public static void main(String[] args)
{
Demo.obj1 = new Demo();
Demo.obj1.obj2.fun();
}
void fun()
{
System.out.println("User method....");
}
}
class Demo
{
Demo obj2 ;
Demo()
{
this.obj2 = this ;
}
public static void main(String[] args)
{
Demo obj1 = new Demo();
obj1.obj2.fun();
}
void fun()
{
By Srinivas (C/DS/Java trainer) Page 66
System.out.println("User method....");
}
}
Question: Can we define more than one class in a single source file?
Answer: Yes allowed.
class Login
{
static
{
System.out.println("Login page is loading....");
}
public static void main(String[] args)
{
System.out.println("Communication starts....");
Inbox.mailInfo(); // It loads the Inbox class first.
}
}
class Inbox
{
static
{
System.out.println("Inbox page is loading....");
}
static void mailInfo()
{
System.out.println("Recent mail info.....");
}
}
class Bank
{
public static void main(String[] args)
{
System.out.println("Processing Account.....");
amount = 4000 ;
acc.withdraw(amount);
By Srinivas (C/DS/Java trainer) Page 69
System.out.println("Balance after withdrawal : "+acc.getBalance());
amount = 2000 ;
acc.deposit(amount);
System.out.println("Final balance : "+acc.getBalance());
}
}
class First
{
public static void main(String[] args)
{
Second addr = new Second();
addr.check();
}
}
class Second
{
void check()
{
System.out.println("Second class non-static method....");
}
}
class First
{
static Second addr = new Second();
public static void main(String[] args)
{
First.addr.check();
}
}
class Second
{
void check()
{
System.out.println("Second class non-static method....");
}
}
System.out.println() :
By Srinivas (C/DS/Java trainer) Page 70
class System
{
static PrintStream out = new PrintStream();
public static void main(String[] args)
{
System.out.println();
}
}
class PrintStream
{
void println()
{
// prints a msg on console.....
}
}
Syntax:
data_type <variable_name> ;
Example:
int sum = 0 ;
Classification:
Java data types classified into 2 types
Primitive data types and user defined.
Class is the user-defined data type
User defined data types are reference(object) type in java application
2. Why character occupy 2 bytes memory in java and .net where as it occupies only 1 byte in C
and C++?
Java & .net apps are web apps.
Web app need to represent more than one language character set a time. Hence it
occupies 2 bytes.
C & C++ are platform dependent. These can represent only one language at a time.
5. What is ASCII?
6. What is UNICODE?
Explanation:
Generally, compiler needs to convert all the symbols of java source file into class file.
To convert all the characters of 1 language into machine code, compiler uses character
system.
Character system introduced along with computer languages.
We have so many character systems but Popular one is "ASCII"
Character system represents all the symbols of one language using constant integer values.
In the following diagram standalone application (photo shop) supports “n” number of
languages but at a time it has to represent only one language.
Suppose in our mobile, at a time we can select only language (radio button) hence it is also
standalone.
To represent one language character set completely, I byte (256) number enough.
In this diagram, a web-application need to represent more than one language character set as we
can run the web application from different machines at a time in different languages.
class DataTypes {
public static void main(String[] args) {
byte a=10 , b=20 ;
Type casting:
Conversion of data from one data type to another data type.
Casting happens at runtime.
Java allows
o Primitive casting
o Object casting
Casting can be either
o implicit (internal) by JVM
o Explicit (external) by Programmer.
Programs :
class ImplicitCast {
public static void main(String[] args) {
byte b = 100 ;
int i ;
i = b ; //implicit cast.....
System.out.println("i value : "+i);
char ch = 'A' ;
int j ;
j = ch ; //implicit cast.....
System.out.println("j value : "+j);
By Srinivas (C/DS/Java trainer) Page 76
}
}
class ExplicitCast {
public static void main(String[] args) {
int i = 100 ;
byte b ;
int j = 97 ;
char ch = (char)j ;
System.out.println("ch value : "+ch);
}
}
class ExplicitCast {
public static void main(String[] args) {
int i = 130 ;
byte b ;
b = (byte)i ;
System.out.println("b value : "+b);
}
}
class ExplicitCast {
public static void main(String[] args) {
int i1 = 256 , i2 = 512 , i3 =1024 ;
byte b1, b2, b3 ;
b1 = (byte)i1 ;
b2 = (byte)i2 ;
By Srinivas (C/DS/Java trainer) Page 77
b3 = (byte)i3 ;
class ExplicitCast {
public static void main(String[] args) {
int i1 = -131 ;
byte b1 ;
b1 = (byte)i1 ;
System.out.println("b1 value : "+b1);
}
}
Note : Using type casting, we can conserve/save the memory in the application….
class DataTypes {
public static void main(String[] args) {
byte a=10 , b=20 ;
class DataTypes {
public static void main(String[] args)
{
int x=5 , y=2 ;
int z = x/y ;
System.out.println("z value : "+z);
By Srinivas (C/DS/Java trainer) Page 78
}
}
/* int / int --> int
int / float --> float
float / int--> float
float / float --> float
*/
class DataTypes {
public static void main(String[] args) {
int x=5 , y=2 ;
float z = x/y ;
System.out.println("z value : "+z);
}
}
class DataTypes {
public static void main(String[] args) {
int x=5 , y=2 ;
float z = (float)x/y ;
System.out.println("z value : "+z);
}
}
class DataTypes {
public static void main(String[] args) {
int x=5 , y=2 ;
float z = (float)x/(float)y ;
System.out.println("z value : "+z);
}
}
Note: If any language supports primitive types as well as OOP features, referred as "Partial OOPL".
Using primitive data types we cannot develop fully object oriented java application.
We use wrapping to convert primitive data into objects and object data into primitives
In the above example, we use static method of Byte class to convert primitive byte to Object
Byte type.
UN boxing:
Conversion of Object Byte to primitive byte.
We use non-static method of Byte class for this conversion.
Primitive to String :
Byte class having 2 pre-defined constructors to construct Byte class Object from primitive
byte and String.
Among all the 6 data conversion, it is possible to perform 2 conversion using constructors
also.
class ByteConstructors
{
public static void main(String[] args)
String x2 = "100" ;
Byte y2 = new Byte(x2); // byte -> String
String x3 = "abcd" ;
Byte y3 = new Byte(x3); //Exception : Invalid data conversion
}
}
Byte class is having not only methods & constructor, it has set of variables.
All these variables represent limits & size of byte data type.
class ByteFields
{
public static void main(String[] args)
{
System.out.println("byte MIN value : "+Byte.MIN_VALUE);
System.out.println("byte MAX value : "+Byte.MAX_VALUE);
System.out.println("byte SIZE in bits : "+Byte.SIZE);
}
}
For example…
byte b = Byte.parseByte(“10”); //String -> byte
int I = Integer.parseInt(“10”); //String -> int
boolean b = Boolean.parseBoolean(“false”); //String -> boolean
System.out.println(Float.MIN_VALUE);
System.out.println(Float.MAX_VALUE);
System.out.println((int)Character.MIN_VALUE);
System.out.println((int)Character.MAX_VALUE);
}
}
Note:
Type casting can be applicable only on primitive data types.
We cannot convert Object to primitive through type casting.
For example…
String s = “100”;
byte b = (byte)s ;
Note : Scanner class is having number of pre-defined non-static methods to read different kinds of
input from End-user.
import java.util.Scanner ;
class Reading
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
Program :
import java.util.Scanner ;
class ScannerDemo
{
public static void main(String[] args)
{
Scanner obj = new Scanner(System.in); //Constructs Scanner obj with input
source "keyboard".
int z = x+y ;
System.out.println("sum : "+z);
}
}
/*
class Random
{
public Random()
{
Creates Random integer generator
}
public int nextInt()
{
Returns a random integer number.
int --> 4 bytes ---> 32 bits ---> 2^32
}
}
*/
Program:
import java.util.Random ;
class RandomNumbers
{
public static void main(String[] args)
{
Random r = new Random();
Program to generate a random number within the range of given integer limit:
/*
class Rando
{
public int nextInt(int n)
{
Returns a random int value between 0(inclusive) and the specified value
(exclusive), drawn from this random number generator's sequence.
By Srinivas (C/DS/Java trainer) Page 89
}
}
*/
Program:
import java.util.Random;
class RandomDemo
{
public static void main(String[] args)
{
Random obj = new Random();
int no = obj.nextInt(100);
System.out.println(no);
}
}
Whatever the input type collected from the command prompt will be implicitly converted
into String type.
To process the command line arguments, it is mandatory to convert String type into
corresponding primitive types using parseXxx() methods.
If we don't pass any arguments, the array size will be "zero" .
The size increases depends on number of arguments passed.
In C or C++, if we are not working with command line arguments, main method will be..
main( ) { }
void main( ) { }
In java, Whether or not you are working with command line arguments, it is mandatory to specify the
signature of main() method.
main(String args[ ])
class Arguments
{
public static void main(String list[ ])
{
int len = list.length ;
System.out.println("Number of arguments : "+len);
}
}
class Arguments
{
public static void main(String args[ ])
{
int len = args.length ;
if(len == 0)
{
System.out.println("Please pass few arguments...");
}
else
{
System.out.println("List of arguments : ");
for(int i=0 ; i<len ; i++)
{
System.out.println("args["+i+"] --> "+args[i]);
}
By Srinivas (C/DS/Java trainer) Page 92
}
}
}
class Arguments
{
public static void main(String args[ ])
{
System.out.println("First arg : "+args[0]);
System.out.println("Last arg : "+args[args.length-1]);
System.out.println("Out of array : "+args[args.length]);
}
}
class CmdLineArgs
{
public static void main(String args[ ])
{
int a,b,c;
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
c = a+b;
By Srinivas (C/DS/Java trainer) Page 93
System.out.println(a+" + "+b+" = "+c);
}
}
private:
Private member belongs to particular object. Complete hiding from outside world.
We can’t apply to class.
If we apply to class, complete object will be hidden; hence no one can communicate with
that object. Such type of objects is useless.
We can apply private functionality only to class members such as variable, methods &
constructors.
Private members of class can be accessed only within that class in which those are defined.
public:
We can apply public modifier to class and its members.
Public class can be accessed anywhere in java application.
In real time applications, all the classes must be defined as public.
protected:
Can be applied only to class members.
protected members can be accessed within the package and only from the subclasses of
outer package.
Code1:
class PrivateMembers
{
private static int a = 10 ;
public static void main(String[] args)
{
System.out.println("a : "+PrivateMembers.a);
PrivateMembers pm = new PrivateMembers();
pm.method();
}
private void method()
{
System.out.println("Private method");
}
}
Code2:
class Test
{
private static int a = 10 ;
}
class PrivateMembers
{
public static void main(String[] args)
{
System.out.println(Test.a); // Error : Private member
}
}
Code4:
protected class Test
{
public static void main(String[] args)
{
System.out.println("A class can't be protected...");
}
}
Code5:
/*These 2 classes belongs to default package*/
class Test
{
private void m1(){ }
void m2(){ } //package level
}
class PrivateMembers
{
public static void main(String[] args)
{
Test obj = new Test();
obj.m2();
obj.m1(); // Error :
}
}
Code6:
To dis-allow outside class to instantiate, constructor must be defined as private.
Without constructor calling, no one can create object in java application.
class Test
{
private Test()
{
//empty
}
}
class PrivateMembers
By Srinivas (C/DS/Java trainer) Page 98
{
public static void main(String[] args)
{
Test obj = new Test(); //can't create object -> private constructor
}
}
class Test
{
public static void main(String[] args)
{
private int a = 100 ; // Error : not allowed here
System.out.println("a value : "+a);
}
}
Note : “lang” package classes available directly to every java application. These classes mainly
used by basic java programmer.
System, String, Byte, Integer…. belongs to “lang” package….
Example :
package nit ;
package nit ;
import java.lang.System ; //optional
class First
{
By Srinivas (C/DS/Java trainer) Page 100
public static void main(String args[ ])
{
System.out.println("nit.First class main method.....");
}
}
Compiling java program including package statement : After setting java path to
JDK kit, go to command prompt and type
Cmd/> javac.exe
Provides information about javac.exe
Accessing the members of one class from another class of same package:
Default access permissions in Java application is package level.
Hence we can access one class members from another class directly.
package nit ;
import java.lang.System ; //optional
class First
{
void fun( )
{
System.out.println("nit.First class fun method.....");
}
}
import:
1. It is a pre-defined keyword.
2. Used to connect classes in java application of different packages.
3. Import statement creates an internal pointer either “to package” or “to class”.
4. Using internal pointer, it loads the class dynamically while application is running.
Question : Can we place more than one public class in a single source file?
Answer : not allowed.
Demo.java :
class Check {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
Note: If class is “public”, we must save with the same name of class name.
One.java Two.java
package p1 ; package p2 ;
public class One import p1.One ; //to import, class must be public
Note:
“import” statement doesn’t load the class directly.
It creates only internal pointer to package or class.
“import” statement only loads the class at runtime, on use.
un used classes will not be loaded into JVM.
Practical example that proves, “import” statement doesn’t load the class directly:
As a java programmer, we can analyze whether a class is loading or not into JVM, we
need to define a static block.
Static block executes implicitly at the time of class loading.
package p1 ; package p2 ;
public class One import p1.One ;
{ class Two
static {
{ static
System.out.println("p1.One class loading"); {
} System.out.println("p2.Two class is loading.");
public One() }
{ public static void main(String[] args)
System.out.println("p1.One object creating"); {
} System.out.println("p2.Two main method");
} new One(); // it loads "One-class" first.
}
}
Advantages:
The main advantage of packages is, “Avoiding collisions between class names”.
Consider, we need to define 2 classes with the same identity in java app, we need to place
these 2 classes in 2 different packages.
And we can access only by using “Fully Qualified Name”.
package p1 ;
public class Y {
static {
System.out.println("p1.Y is loading.....");
}
}
package p2 ;
public class X {
static {
System.out.println("p2.X is loading....");
}
}
package p2 ;
public class Z {
static {
System.out.println("p2.Z is loading.....");
}
}
import p1.*;
import p2.*;
class ABC {
public static void main(String[] args) {
new Y();
new Z();
}
}
By Srinivas (C/DS/Java trainer) Page 107
package p3 ;
import p1.*;
import p2.*;
class ABC
{
public static void main(String[] args)
{
new X(); //CE : collisions
}
}
package p3 ;
import p1.*;
import p2.*;
class ABC
{
public static void main(String[] args)
{
new p1.X();
new p2.X();
}
}
class System
{
public static void main(String[] args)
{
//System.out.println("Hello World!"); //CE :
java.lang.System.out.println("Hello World!");
}
}
Note: After practiced above application, please delete System related files, if not, every time it
collects the information of System class from local drive.
class String
{
Creation of Sub packages : Using “package” keyword, we can create sub packages.
Syntax :
package parent_package.child_package ;
Example :
package maths.operators ;
package maths.operators.arithmetic ;
Note: In the process of sub package creation, the required directories to generate the class file will
be created implicitly by the Compiler.
Notes:
OOP features neither belong to java nor to any programming language.
Every language can adopt OOP features to become Object Oriented Language.
Implementation of OOP functionalities in java only through "class" and "Object".
for example :
Object1: Human
Identity: Amar
Properties: Color, Height, Weight, Age, Qualification…
Functionalities: walk () , see() , run() , teach(), swim() , drive()....
Object2: Laptop
Identity: Lenovo
Properties: Color, Model , Price , Configuration..
Functionalities: calculate () , play() , store() , send()....
State: Every Object should have properties called state of Object. It can be modified only by
Behavior of Object.
Behavior: Functionalities (methods) of Object is called Behavior. Only Behavior can change state of
Object.
Definition: A class is a complete representation of real world entity (Object) which includes
Note: All the above classes description will see in the following concepts...
POJO rules: In java app, object shoud follow at least POJO rules
(Plain Old Java Object)
1) Class must be public
2) Properties must be private
3) Should have the definition of public zero arguments constructor.
4) Can have optional arguments constructor (if required)
5) Every property must having public setter and getter.
public Emp()
{
// assign default values...
}
class AccessEmp
{
public static void main(String[] args)
{
Emp e1 = new Emp();
e1.setEno(101);
e1.setEname("Hari");
e1.setEsal(50000) ;
System.out.println("e1-ename : "+e1.getEname());
System.out.println("e2-ename : "+e2.getEname());
}
}
Encapsulation:
Writing data (variables) and code (methods) into a single unit.
In the communication world, we should make outer visibility of Object but not properties and
methods.
Encapsulation is the concept of protecting object functionality from outside view.
Class is a cap of object as shown in diagram.
In java Encapsulation can be achieved through a keyword called "class".
this:
By Srinivas (C/DS/Java trainer) Page 117
It is a keyword.
It is a pre-defined non-static variable.
It holds reference of Object.
It must be used only in “non-static context”.
It is used to access the complete functionality of Object(static & non-static)
Access class members from different contexts using class_name, object_reference , this?
Generally we access “static members” using “class-name”
But we can use “obj-reference” also to access static members.
System.out.println(this.a); //Error :
}
}
class Test
{
int a ;
public static void main(String[] args)
{
System.out.println(Test.a); // Error :
System.out.println(this.a); //Error :
class Test
{
static int a = 100 ;
public static void main(String[] args)
{
Test obj = new Test();
obj.check();
}
void check()
{
System.out.println(Test.a);
System.out.println(this.a);
}
}
class Test
{
System.out.println(this.a);
}
}
class Test
{
int a ;
public static void main(String[] args)
{
Test obj = new Test();
System.out.println(obj.a);
}
}
Above 2 programs represents, Object reference variable can access both static & non-static
members.
Question: How to access the members if static and non-static variables having same name?
We can define either static or non-static members in the application with one identity.
Hence, Object reference variable will not get any confusion while accessing either static or
non-static members(because both should not be present with single identity).
class Test
{
static int a = 100 ;
int a ; // not allowed
}
For example….
In bank_app,
By Srinivas (C/DS/Java trainer) Page 122
Static int branch_code = 12345.
If branch_code is static(common), there is no specific branch_code(non-static)
Int balance ;
If balance is non-static(specific), there is no common balance(static)
this():
this() is used to invoke current(same) class constructor explicitly.
Used to initialize an object via multiple constructors.
Connecting constructors using this(), is called Constructor Chaining.
We must use this() only inside another constructor of same method.
Call to this(), must be the first statement in another constructor.
class Emp
{
int eno ;
String ename ;
Emp()
{
System.out.println("Employee is present.....");
}
Emp(int eno, String ename)
{
this( ) ;
this.eno = eno ;
this.ename = ename ;
System.out.println("Employee initialized....");
}
public static void main(String[] args) {
Emp obj = new Emp(101 , "Hari");
}
}
Question: Can we connect more than one constructor from one constructor?
Answer: Not allowed, call to this() must be the first statement.
class Ex
{
Ex()
{
this(10,20);
System.out.println("zero args....");
}
Ex(int x)
{
this( );
// this(10,20); // Error : we can connect only one constructor
By Srinivas (C/DS/Java trainer) Page 123
System.out.println("one args....");
}
Ex(int x, int y)
{
System.out.println("two args....");
}
public static void main(String[] args)
{
new Ex(10);
}
}
Terminology:
After implementing "Is-A relation" between Object, we can referred as
a. Parent class - Child class
b. Base class - Derived class
c. Super class - Sub class
Is-A relation:
After inheriting the complete functionality of existing Object, the Sub Object working like
Parent objects also.
The main advantage of Inheritance concept is “Code Reusability”.
For example...
1) Car "is a" Vehicle
2) Swift "is a" Car
3) Nokia "is a" Mobile
Types of inheritance: Java supports only 3 types of Inheritance out of all the types supported by
Object Oriented Programming.
/*
class Object{
hashCode(){ }
getClass(){ }
}
*/
class SingleInheritance {
public static void main(String[] args) {
Sample obj = new Sample();
obj.f1(); //defined in Child(Sample) class....
obj.hashCode(); //defined in Parent(Object) class
By Srinivas (C/DS/Java trainer) Page 126
}
}
Multi-Level inheritance:
Accessing the functionality of Objects in more than one level.
Child class accessing Grandparent functionality through parent.
Note:
In the process of Child object creation, JVM first create Parents Object.
Question: How can we analyze “JVM instantiating Parent class first, in the process of Child
instantiation”?
Ans : As a java programmer we can analyze
1) whether “class is loading or not” by defining “static block”
2) whether “Object is creating or not” by defining “Constructor”
Note: In the process of Object creation either implicitly (by JVM) or explicitly(by Programmer),
constructor is calling is mandatory.
class JDK6
{
JDK6()
{
System.out.println("Installing JDK6 features......");
}
}
class JDK7 extends JDK6
{
JDK7()
{
System.out.println("Installing JDK7 features......");
}
}
class JDK8 extends JDK7
{
JDK8()
{
System.out.println("Installing JDK8 features......");
}
}
class MultiLevel
{
public static void main(String[] args)
{
new JDK8();
}
}
class Vehicle
{
By Srinivas (C/DS/Java trainer) Page 129
String fuel()
{
return "Petrol";
}
}
class Car extends Vehicle
{
String fuel() //override
{
return "CNG";
}
}
class Bike extends Vehicle
{
// No updation...
}
class Bus extends Vehicle
{
String fuel()
{
return "Diesel";
}
}
class Hierarchal
{
public static void main(String args[ ])
{
Car c = new Car();
String cf = c.fuel();
System.out.println("Car fuel type : "+cf);
In the following program we are accessing the functionality of Parent from child by creating
object for Parent class.
Duplicate objects wasting the memory in heap area.
Solution to this problem is using “super” keyword to access Parent functionality.
class Parent
{
void fun()
{
System.out.println("Parent's functionality.....");
}
super:
It is a keyword
It is pre-defined non-static variable.
It is used to access the complete functionality of Parent class from Child class.
It must be used in non-static context.
this super
It is a keyword It is a keyword
Pre-defined non static variable Pre-defined non static variable
It is used to access current object(class) It is used to access Parent object(class)
functionality functionality from child
It must be used only in non-static context It must be used only in non-static context
It holds object address It doesn’t hold any object address
By Srinivas (C/DS/Java trainer) Page 131
class Parent
{
void fun()
{
System.out.println("Parent's functionality.....");
}
}
class Child extends Parent
{
Child() //non-static context
{
this.fun(); //points to Child class object
super.fun(); //points to Parent class object
}
void fun()
{
System.out.println("Child's functionality.....");
}
}
class MainClass
{
public static void main(String[] args)
{
Child obj = new Child();
}
}
Note :
“super” is a sub pointer to “this”.
“this” holds address where as “super” doesn’t.
Using “super”, we can access only one level object functionality in the hierarchy.
class Parent
{
Parent()
{
By Srinivas (C/DS/Java trainer) Page 132
System.out.println("Parent's Addr : "+this); // Allowed
}
}
class Child extends Parent
{
Child()
{
System.out.println("Child's Addr : "+this); // Allowed
// System.out.println("Parent's addr : "+super); // Error :
}
public static void main(String[] args)
{
Child obj = new Child();
}
}
super():
Used to access Parent class constructor from the child class.
We must use super() method inside the child class constructor
Call to super() method must be the first statement in the Child’s constructor
In the process of child class object construction, it is not possible to invoke parent’s
constructor explicitly.
Hence it is possible to provide initialization of Parent object only by using super() method.
this() super()
Used to invoke current class constructor. Used to invoke Parent class constructor from
Child
Must be used only inside another constructor of Must be used only inside Child’s constructor.
same class.
Call to this() must be the first statement. Call to super() must be the first statement.
To connect constructors in a single class. To connect constructors in Is-A relation.
Used to initialize an object via multiple Used to initialize parent class object in the
constructors. process of child object creation.
Note: In the process of child class object construction, JVM implicitly creates Parent’s object first.
For this construction, JVM uses super() method.
class Parent
{
Parent()
{
System.out.println("Parent's instantiation.....");
}
}
class Parent
{
int a ;
Parent(int a)
{
this.a = a ;
}
}
class Child extends Parent
{
Child(int a)
{
super(a);
}
void details()
{
System.out.println("Parent's a : "+super.a);
}
}
class MainClass
{
public static void main(String[] args)
{
Child obj = new Child(100);
class Parent
{
int a , b ;
Parent(int a , int b)
{
this.a = a ;
this.b = b ;
}
}
class Child extends Parent
{
int c, d ;
Child(int a, int b, int c , int d)
{
super(a , b);
this.c = c ;
this.d = d ;
}
void details()
{
System.out.println("Parent's a : "+super.a+"\nParent's b : "+super.b+"\nChild's c :
"+this.c+"\nChild's d : "+this.d);
}
}
class MainClass
{
public static void main(String[] args)
{
Child obj = new Child(10,20,30,40);
obj.details();
}
}
/*
Compiler will not add any default constructor if we define any constructor inside the class.
*/
class Test
{
Test(int x)
{
// empty....
}
public static void main(String[] args)
{
new Test(); // Error : no such constructor definition
}
}
Note : In case Parent-child relation also, default constructors will be supplied by the compile only if
we don’t define any constructor.
Hence we need to take care of all the constructor availability in constructor chaining process among
Parent-child object creation.
Note : In the process of constructor chaining in Parent-Child classes, we need to check all the
constructors available or not.
class Parent
{
// no default constructor
Parent(int x)
{
// empty....
}
}
class Child extends Parent
{
/*Child()
{
super(); // looking for default constructor in Parent class and results error as it was
not defined....
}*/
}
class MainClass
{
public static void main(String[] args)
{
Child obj = new Child();
}
}
In the following example, we defined 4 constructors both in Parent and Child class.
We can connect all the constructors in the instantiation of Child class in 4 ways.
Note that, call to either super() or this() must be the first statement in the constructor.
That means we can connect only one constructor from another constructor.
Note: If class is “final” that cannot be inherited (extended). Only leaf classes in the hierarchy must be
defined as “final”.
Method is final:
If method is final, that cannot be overridden.
Overriding is the concept of updating a specific functionality of Object.
But if we define any function/method as final, that cannot be updated.
By Srinivas (C/DS/Java trainer) Page 139
For example…
class Galaxy
{
final String camera()
{
return "12mp";
}
}
class Edge extends Galaxy
{
String camera() // Error : can't Override
{
return "20mp";
}
}
Variable is final:
If variable is “final” that cannot be modified.
Constants in java application must be defined as final.
Most of the final variables are static in java application.
For example….
o static final double PI = 3.142
class Test
{
static final double PI = 3.142 ;
public static void main(String[] args)
{
Test.PI = 3.1412 ; // Error : can't modify
}
}
Note: We cannot update the functionality of “final object”, but we can access the complete
functionality of Object.
package p1;
public class Parent
{
public void f1()
{
System.out.println("Parent's public f1");
}
protected void f2()
{
System.out.println("Parent's protected f2");
}
}
package p2;
import p1.Parent;
class Child extends Parent
{
public static void main(String[] args)
{
//Parent p = new Parent(); //if we create Object of Parent class, it is allowed to access
only public members of Parent class.
p.f1() ; //allowed
class Parent
{
Parent()
{
}
}
class Child extends Parent
{
Parent()
{
} ---> Not possible here
}
class Test
{
final Test()
{
System.out.println("final constructor..");
}
}
Abstract class:
If a class is not able to provide complete definition of Object referred as Abstract class.
The class which is not providing complete definition of Object.
"abstract" is a pre-defined keyword allowed to define abstract classes.
Abstract class also saved with .java extension only.
.class file will be generated when abstract class has compiled.
Abstract class cannot be instantiated directly using “new” keyword, because it was not fully
defined.
For example, we can release any Mobile into the market after 100% manufactured.
Note: When any Child class of abstract class is unable to implement all the specifications of abstract
class must be defined as abstract.
class Test
{
abstract final void f1(); // Error
abstract static void f2(); // Error
}
Interfaces
class: Complete representation of Object(100%)
(Only concrete methods)
interface Test
{
void method()
{
// Error : interface methods can't have body
}
}
interface Test
{
void f1() ; // by default public & abstract
void f2() ;
}
To check compiler added code to the class file we use javap command.
interface Test
{
void f1() ;
void f2() ;
}
class Main
{
public static void main(String args[])
{
new Test();// Error : can't instantiate
}
}
interface Test
{
public static void main(String args[ ])
{
System.out.println("interface main method.....");
}
}
We can define static methods and can access directly using interface identity.
Static members cannot be overridden because it is common functionality of Object.
By Srinivas (C/DS/Java trainer) Page 150
We cannot update static members in the hierarchy.
If we want to update, we should modify in the top class of hierarchy.
interface Test
{
static void m()
{
System.out.println("interface static method");
}
public static void main(String args[])
{
System.out.println("interface main method....");
Test.m();
}
}
interface Test
{
void f1() ; // public method
void f2() ;
}
class Main implements Test
{
// void f1(){ } // Error : pls don't decrease privileges
interface Test
{
void f1() ;
void f2() ;
}
abstract class One implements Test
{
public void f1(){ }
}
class Two extends One
{
public void f2(){ }
}
The following program describes all the above discussions are correct or not.
class A { /* logic */ }
class B { /* logic */ }
interface E { /* logic */ }
interface F { /* logic */ }
Question : After implementation of interface, why we need to maintain interface in java application?
Answer :
Interface is a standard set of specifications.
Every standard(interface) must be implemented with a Duplicate name(class)
After their implementation with duplicate name (class name), we need set Standard
(interface) name to that object.
One standard object always tries to communicate with another standard object only in
communication world.
interface Lenovo
{
void processor();
void motherBoard();
void display();
}
Note: If one object definition (AssembledComputer) based on multiple standards (Intel, AMD,LG),
we cannot provide one standard name to the entire object.
interface Intel
{
void processor();
}
interface AMD
{
void motherBoard();
}
interface LG
{
void display();
}
Question: Why it is allowed to store Child object address into Parent reference variable?
Lenovo obj = new Computer();
Answer : Object casting concept.
class Addition
{
void add(int x, int y)
{
System.out.println("sum of 2 int's : "+(x+y));
}
void add(int x, int y, int z)
{
System.out.println("sum of 3 int's : "+(x+y+z));
}
}
class StaticBinding
{
public static void main(String[] args)
{
Addition obj = new Addition();
By Srinivas (C/DS/Java trainer) Page 157
obj.add(10,20,30); // method call...
}
}
class MainOverLoad
{
void main()
{
System.out.println("zero args...");
}
static void main(int x)
{
System.out.println("One args main.....");
}
public static void main(String[] args)
{
System.out.println("JVM main method...");
MainOverLoad obj = new MainOverLoad();
obj.main();
obj.main(10);
}
}
Runtime polymorphism:
It is also called Dynamic binding.
It is method overriding technique.
Defining a method in Child class with the same name and same signature of its Parent class is
called Method overriding.
We can implement dynamic binding only in “Is-A” relation.
More than one objects combined together to show Runtime polymorphism behavior.
Allowed only in Super and Sub class.
Note: One advantage of Runtime Polymorphism is used to update Parent class functionality in Child
class if it is not sufficient.
class SamsungGalaxy
{
String camera(){
return "12mp";
}
By Srinivas (C/DS/Java trainer) Page 158
String memory(){
return "2gb"
}
}
class SamsungEdge extends SamsungGalaxy
{
String camera(){ //overriding (updating functionality)
return "16mp";
}
String memory(){
return "4gb"
}
}
The main advantage of Runtime polymorphism is “Accessing Child class object functionality
using Parent object reference”.
We know the importance of “C/O address” while addressing someone.
The best example of runtime polymorphism as follows.
class Owner{
void mail(){
System.out.println("Owner received mail...");
}
}
class Tenant1 extends Owner{
void mail(){
System.out.println("Tenant1 received mail...");
}
}
class Tenant2 extends Owner{
/*void mail()
{
By Srinivas (C/DS/Java trainer) Page 159
System.out.println("Tenant2 received mail...");
}*/
}
class RuntimeBinding {
public static void main(String[] args)
{
Owner obj1 = new Owner();
obj1.mail(); //Owner will receive as it was belongs Owner.
Question: why it is allowed to store sub class object into super class type variable directly?
Answer: Because of implicit object up casting.
interface Owner
{
void tenantFun() ; //public abstract
}
abstract class Tenant implements Owner
{
public abstract void tenantFriendFun() ;
public void tenantFun()
{
System.out.println("Accessing Tenant fun......");
}
}
class TenantFriend extends Tenant
{
public void tenantFriendFun()
{
System.out.println("Accessing Tenant Friend fun....");
}
}
class RuntimeBinding
{
public static void main(String[] args)
{
Examples:
1. Cannot find symbol
2. “this” cannot be used in static context
3. Invalid method declaration.
2) Logical errors:
Logical error is the compiler error and runtime error.
It produces unexpected results when we run the application.
3) Runtime errors:
Violation of JVM rules.
As a programmer some of the errors we can analyze at the time of application development
but we cannot handle.
As a programmer we can write the logic but that executes only when problem has risen while
application is running.
Exception Causes....
1. Abnormal termination of program
2. Informal information to End user
3. Improper shutdown of Resources.
1. Name of error
2. Type of error
3. State of error
Once object has been created, it passes to the runtime system (JVM) then JVM handles that
exception with the help of Default Exception Handler.
Hence mean while, we need to catch that exception and handle before the object reaches
JVM, to avoid abnormal termination and continue with remaining statements execution in
the application.
import java.util.Scanner ;
class ExceptionDemo
{
public static void main(String[] args)
{
int a,b,c;
System.out.println("Enter two integers :");
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
b = sc.nextInt();
c = a/b;
System.out.println("result : "+c);
System.out.println("continue.....");
}
}
By Srinivas (C/DS/Java trainer) Page 164
Chances to get exceptions:
User has entered invalid arithmetic input causes “ArithmeticException”
Accessing the data of array which is out of bounds causes
“ArrayIndexOutOfBoundsException”.
class Test
{
public static void main(String[] args)
{
int arr[ ] = new int[5];
arr[7] = 30 ; //Exception :
}
}
try:
It is a pre-defined keyword
Used to define a block of statements.
Doubtful code that raises exception must be placed inside the try-block.
if exception raised inside the block, it creates Exception Object and passes to "catch" block
instead of JVM.
catch:
It is a keyword
used to define block which contains Exception handling code that raises in the corresponding
try-block.
syntax:
try
{
//doubtful code...
// related info…..
}
catch(<Exception_type> <identifier>)
{
//Handling code....
}
Exception Hierarchy:
java.lang.Throwable is the super class of all the Exceptions.
It has 2 direct sub classes Exception & Error
Errors can't be handled in java application.
Sub classes of RuntimeException are called "Unchecked Exceptions" belongs to "java.lang"
package.
Examples....
1. ArithmeticException
2. NumberFormatException
Note: It is also possible to handle an Exception by collecting the reference into its Super Exception
type variable.
import java.util.Scanner ;
class ExceptionDemo
{
public static void main(String[] args)
{
try
{
int var = 10 / 0 ;
}
// catch (ArithmeticException ae){ }
//catch (RuntimeException ae){ }
//catch(Exception e){ }
// catch(Throwable t) { }
catch(java.io.IOException ie){ } // Error : try block never throws such type of
exception
}
}
syntax :
try
{
-------- //chance to get Exception1
……
-------- // chance to get Exception2
}
catch(Exception1 <var>)
{
//Exception1 handling logic...
}
catch(Exception2 <var>)
{
//Exception2 handling logic...
}
/*
Task :
1) Read one argument from command line.
2) Convert into byte.
*/
class MultiCatch
{
public static void main(String args[ ])
{
try
{
String input = args[0] ;
System.out.println("Input value : "+input);
While using any method or constructor in the application, we need to consider the complete
prototype of that method.
Following diagram describes an example with its prototype.
/*class FileInputStream
{
public FileInputStream(String name) throws FileNotFoundException
finally:
A block of instructions.
Used to release a resource in Exception handling
Only using in case Checked exceptions.
finally block executes whether or not an Exception has raised in the try-block.
finally block executes in case of abnormal termination of program also.
Tips :
Try-block : Handling Exception.
Catch block : Avoids abnormal termination.
Finally block : Resource releasing code.
Case2 :
method(){
try{
//placing doubtful code
}
catch(){
//Handling UnchekcedException
//No abnormal termination
}
}
Case3 :
method(){
try{
//doubt ful code
}
finally{
//closing statements, working with CheckedException, Abnormal termination.
}
}
Case 4 :
method(){
try{
//doubtful code.....
}
catch(){
//Handing Checked Exception, No abnormal termination
}
finally{
//Releasing resources
}
}
Following program explains how finally block executes in case of abnormal termination of
program.
class Exceptions
{
public static void main(String[] args)
{
try
{
String s = "150" ;
import java.io.FileInputStream ;
import java.io.FileNotFoundException;
import java.io.IOException ;
class CheckedException
{
public static void main(String[] args)
{
FileInputStream fis = null ;
try
{
fis = new FileInputStream("g:/input.txt");
System.out.println("File opened successfully...");
}
catch (FileNotFoundException fnfe)
{
System.out.println("file doesn't exist....");
}
finally
{
try
By Srinivas (C/DS/Java trainer) Page 176
{
fis.close();
System.out.println("File closed successfully....");
}
catch (IOException io)
{
System.out.println("IO error....");
}
}
}
}
/*class FileInputStream
{
public FileInputStream(String name) throws FileNotFoundException
{
opens a file in read mode....
}
public void close() throws IOException
{
Closes this file input stream
}
}*/
import java.io.FileInputStream ;
import java.io.FileNotFoundException;
import java.io.IOException ;
class CheckedException
{
public static void main(String[] args)
{
FileInputStream fis = null ;
try
{
fis = new FileInputStream("g:/input1.txt");
System.out.println("File opened successfully...");
By Srinivas (C/DS/Java trainer) Page 177
}
catch (FileNotFoundException fnfe)
{
System.out.println("file doesn't exist....");
}
finally
{
try
{
fis.close();
System.out.println("File closed successfully....");
}
catch (IOException io)
{
System.out.println("IO error....");
}
catch(NullPointerException npe)
{
System.out.println("Couldn't close file...");
}
}
}
}
throws:
If any method is unable to handle an exception object, it can pass to next level.
It is recommended to handle every exception in any level of java application.
If we don’t handle an exception in any level, finally JVM handles using Default Exception
handler.
import java.io.*;
class CheckedException
{
public static void main(String[] args) throws FileNotFoundException, IOException
{
FileInputStream fis = new FileInputStream("g:/input.txt");
System.out.println("File opened successfully...");
fis.close();
System.out.println("File closed successfully....");
}
}
fis.close();
System.out.println("File closed successfully....");
}
}
throw:
Exception is a class.
It is either pre-defined or user-defined.
It is allowed to create user exceptions by extending functionality from pre-defined
exception.
User exception can be either Checked or Unchecked.
Most of the User exceptions are “checked”.
In the above application, what is happening internally when exception rises, now we are doing
explicitly.
/*class ArithmeticException
{
public ArithmeticException(String s)
{
Constructs an ArithmeticException with the specified detail message.
}
}*/
class Test
{
public static void main(String[] args)
{
ArithmeticException obj = new ArithmeticException("User_msg");
throw obj ;
}
}
Another example:
class Test
{
public static void main(String[] args)
{
NumberFormatException nfe = new NumberFormatException("Invalid data
conversion....");
throw nfe ;
}
}
import java.io.IOException ;
class Test
{
public static void main(String[] args)
{
try
{
IOException obj = new IOException("IO error");
throw obj ;
}
catch (IOException io)
{
System.out.println("Exception : "+io.getMessage());
}
}
}
String getErrorMessage()
{
return this.name ;
}
}
class Test
{
static void method() throws MyException
{
MyException obj = new MyException("Message....");
throw obj ;
}
}
class Main
{
public static void main(String[] args)
{
try
{
Test.method();
}
catch (MyException me)
{
System.out.println("Exception : "+me.getErrorMessage());
}
}
}
String getErrorMessage()
{
return this.name ;
}
}
class Account
{
private int balance ;
Account(int balance)
{
this.balance = balance ;
}
public int getBalance()
{
return this.balance ;
}
public void withdraw(int amount) throws InsufficientFundsException
{
System.out.println("Trying to withdraw : "+amount);
System.out.println("Avail balance : "+this.balance);
if(amount <= this.balance)
{
this.balance = this.balance - amount ;
System.out.println("Collect cash : "+amount);
}
else
{
InsufficientFundsException ife = new InsufficientFundsException("Low
balance");
throw ife ;
}
}
}
class Bank
{
public static void main(String args[ ])
By Srinivas (C/DS/Java trainer) Page 183
{
Scanner sc = new Scanner(System.in);
int amount ;
If the processor is not capable of performing Multi tasking results abnormal termination
(hang).
Multi threading:
The only difference between Multi tasking and Multi threading is,
o In Multi tasking, "n" process spaces required to perform "n" tasks.
o In Multi threading, "n" threads execute in a single process space.
Multi tasking takes care by Operating System. No programming effort is required.
To implement Multi threading, we need to write program.
Multi threading results, less stress on the Processor, because no need to switch between the
contexts to perform Multi tasking.
Instantiation: Thread Object will be created to participate in the communication only when it is
instantiated by the programmer.
Runnable state: The started thread by the programmer need to wait in the Queue until Scheduler
allocates Thread space in the processor to be executed.
Waiting state: Another Queue state into which thread enters from running state for different
reasons....
Dead state: The last stage of Thread into which Thread enters either by completing all the thread
instruction or in case of abnormal termination.
class SingleThreaded
{
public static void main(String[] args)
{
SingleThreaded obj = new SingleThreaded();
obj.printNumbers();
sleep() method:
/*class Thread
{
public static void sleep(long millis) throws InterruptedException
{
Causes the currently executing thread to sleep (temporarily cease execution) for the
specified number of milliseconds.
}
}*/
The following application describes the use of sleep method and practically proves that main
thread can completes before execution of any Child thread:
/*class Thread{
public Thread()
{
create thread and set default identity to that thread.
}
}*/
class Identities extends Thread
{
/*Identities()
Using constructor:
public Thread(String name)
It sets the name to the current user thread.
join() method:
A pre defined method used to implement inter thread communication.
We can join the threads using this method.
We use join() method in case of one thread execution should resume only when another
thread moved to dead state.
/*class Thread
{
public void join() throws InterruptedException
{
Waits for "this" thread to die
}
}*/
//Thread.sleep(2000);
child.join(); //main thread wait until child moved to dead state.
System.out.println("sum of first "+JoinDemo.n+ " numbers is : "+JoinDemo.sum);
}
public void run()
{
System.out.println("Calculation starts...");
for(int i=1 ; i<=JoinDemo.n ; i++)
{
JoinDemo.sum = JoinDemo.sum + i ;
try
{
Thread.sleep(100);
}
catch (InterruptedException ie){ }
}
System.out.println("Calculation end");
}
}
class PrintNumbers
{
void print1to50() throws InterruptedException
{
for(int i=1 ; i<=50 ; i++)
{
System.out.print(i+"\t");
Thread.sleep(100);
}
}
void print50to1() throws InterruptedException
{
for(int i=50 ; i>=1 ; i--)
{
System.out.print(i+"\t");
Thread.sleep(100);
}
}
}
class TimeCheck
{
public static void main(String[] args) throws InterruptedException
{
PrintNumbers pn = new PrintNumbers();
long start = System.currentTimeMillis();
pn.print1to50();
pn.print50to1();
long end = System.currentTimeMillis();
System.out.println("Time consumed : "+(end-start)/1000+" seconds");
}
}
Question: Can we call start() method more than one time on the same thread Object at the same
time?
Answer: not allowed, results IllegalThreadStateException. Violation rule of Synchronization.
Priority of a Thread:
Every thread can have the priority by which Operating System schedules the thread when it is
in waiting (queue) state.
Threads having higher priority will be processed first.
Every thread is having default priority.
+66java.lang.Thread class contains Fields(pre-defined variables) to describe priorities of
Thread.
/*class Thread{
public static final int MAX_PRIORITY
The maximum priority that a thread can have.
public static final int NORM_PRIORITY
public static final int MIN_PRIORITY
}
*/
class ThreadPriorities
{
public static void main(String[] args)
{
System.out.println("min priority : "+Thread.MIN_PRIORITY);
System.out.println("default priority : "+Thread.NORM_PRIORITY);
System.out.println("max priority : "+Thread.MAX_PRIORITY);
}
}
Thread m = Thread.currentThread();
Types of Threads:
Java application is allowed to define 2 types of Threads.
1) Non-Daemon threads
2) Daemon threads.
Non-Daemon threads:
Non-daemon threads execute front end logic of application.
Every thread is having Non-Daemon behavior as soon as it has created.
Daemon-threads:
Thread executes behind the application.
It is called service thread.
It executes back ground logic of application.
It is possible to change the behavior of Non-Daemon to Daemon.
public final void setDaemon(boolean on)
The JVM implicitly stops all the daemon threads execution if all the Non-Daemon threads
moved to dead state.
It is possible to change the behavior of Thread into Daemon either in the process of Thread
construction or before start.
It is not possible to change the behavior of Thread once it has been started(in running state).
By Srinivas (C/DS/Java trainer) Page 199
Hence main-thread always behaves like Non-Daemon, because it starts by the JVM implicitly.
Thread synchronization:
The concept of synchronization is, when multiple threads are trying to access a single
resource, only one thread is allowed and all the remaining threads moved to queue (waiting)
state.
Complete class is not possible to synchronize in the java application.
A method or block can be synchronized.
Block synchronization :
Synchronized block is used to lock an object for any shared resource.
Scope of synchronized block is smaller than the method.
Generally we synchronize methods as shown in the above discussion.
Block synchronization is used to synchronize a set of lines of code in a method.
If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
class PrintNumers
{
void print(int n)
{
for(int i=1 ; i<=5 ; i++)
{
System.out.println("Parallel : "+i);
try
{
Thread.sleep(500);
}
catch (Exception e){ }
}
synchronized(this)
{
for(int i=1;i<=5;i++)
{
System.out.println("Sequential of "+n+" multiples : "+n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
class SynchronizedBlock
{
public static void main(String args[])
{
PrintNumers obj = new PrintNumers();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Program to set the Identity of Thread that has created using Runnable.....
public Thread(Runnable target , String name)
Has-A relation:
One Object holding the reference of another Object.
We can implement Has-A relation using Non-static variables because only non-static variables
get memory allocation inside the object.
As we shown in the diagram…. Human(Object) is holding the Reference(Controller) of
another Object(Helicopter) , hence Human can access the complete functionality of
Helicopter.
class Helicopter
{
void accelerate()
{
System.out.println("Speed increasing");
}
void moveLeft()
{
System.out.println("Left turn....");
}
void moveRight()
{
System.out.println("Right turn....");
}
void moveForward()
{
System.out.println("Moving forward...");
}
void moverBackward(){}
}
class Human
{
By Srinivas (C/DS/Java trainer) Page 205
Helicopter heli ; //Human "Has-a" Helicoptor
Human(Helicopter heli)
{
this.heli = heli ;
}
void controlHelicopter()
{
this.heli.accelerate();
this.heli.moveLeft();
this.heli.moveRight();
}
}
class MainClass
{
public static void main(String args[ ])
{
Helicopter heli = new Helicopter();
Human h = new Human(heli);
h.controlHelicopter();
}
}
Garbage Collector:
It is a Daemon thread.
Daemon threads always run behind the application and provide service to the Non-Daemon
thread.
Every child thread is by default Non-Daemon when it has created including main thread.
It is possible to change the behavior of Non-Daemon thread to Daemon thread at the time of
thread creation only.
Once the thread has been start, it is impossible to change its behavior.
Types of Threads:
Java application is allowed to define 2 types of Threads.
By Srinivas (C/DS/Java trainer) Page 207
1) Non-Daemon threads
2) Daemon threads.
Non-Daemon threads:
Non-daemon threads execute front-end logic of application.
For example
o Reading input
o Displaying output
Every thread is having Non-Daemon behavior as soon as it has created.
Daemon-threads:
Thread executes behind the application.
It is called service thread.
It executes back ground logic of application.
It is possible to change the behavior of Non-Daemon to Daemon.
public final void setDaemon(boolean on)
The JVM implicitly stops all the daemon threads execution if all the Non-Daemon threads
moved to dead state.
This program explains JVM stops Daemon thread when Non-daemon threads moved to
dead state:
It is possible to change the behavior of Thread into Daemon either in the process of Thread
construction or before start.
If we try to convert while thread is running, results IllegalThreadStateException
The following program describes how objects are garbage collected using finalize() method.
Remember this program is used to understand the concept. It doesn’t compile and execute.
class GC1
{
File file ; //non-static variable must be initialized using constructor.
GC1(File file)
{
this.file = file ;
}
public static void main(String[] args)
{
GC1 obj = new GC1(new File("test1.txt"));
new GC1(new File("test2.txt")); // eligible for GC
}
protected void finalize()
{
this.file.close();
}
}
/*class Object
{
protected void finalize()
{
empty......
}
}*/
By Srinivas (C/DS/Java trainer) Page 210
class GCDemo // extends Object
{
GCDemo()
{
System.out.println(this+" has been created...");
}
protected void finalize()
{
System.out.println(this+" has been deleted...");
}
public static void main(String[] args)
{
new GCDemo();
new GCDemo();//un referenced objects, eligible for GC
}
}
Question: Why Objects are not garbage collected in the above application?
JVM starts the GC thread only when heap memory is running low.
Multi tasking applies stress on the processor.
If JVM runs GC thread continuously in the application that decreases application
performance.
Hence JVM starts GC thread only when required.
class GCDemo
{
int obj_no ;
GCDemo(int obj_no)
{
this.obj_no = obj_no ;
System.out.println("Created : "+this.obj_no);
}
public static void main(String[] args)
By Srinivas (C/DS/Java trainer) Page 211
{
for(int i=1 ; i<=16000 ; i++)
{
new GCDemo(i);
}
}
protected void finalize()
{
System.out.println("Deleted : "+this.obj_no);
}
}
Note: It is possible to request the JVM to start the GC thread using pre-defined method System.gc().
But it is not guarantee that JVM will start the Thread.
/*class System
{
public static void gc()
{
Runs GC thread.
}
}*/
class GCDemo
{
GCDemo()
{
System.out.println(this + " Created");
By Srinivas (C/DS/Java trainer) Page 212
}
public static void main(String[] args)
{
new GCDemo();
new GCDemo();
Note : Generally in Real time application, we request to start GC-thread continuously using a thread
with infinite loop as follows.
class GCDemo extends Thread
{
int obj_no ;
GCDemo()
{
//empty...
}
GCDemo(int obj_no)
{
this.obj_no = obj_no ;
System.out.println("Created : "+this.obj_no);
}
thread.stop();
}
Note : The only difference between Factory class and Singleton class is, “Factory class” can be
instantiated many times where as “Singleton” class only once.
class Access
{
public static void main(String[] args)
{
// FactoryClass fc = new FactoryClass(); // Error :
FactoryClass fc1 = FactoryClass.factoryMethod();
FactoryClass fc2 = FactoryClass.factoryMethod();
System.out.println("fc1 : "+fc1);
System.out.println("fc2 : "+fc2);
System.out.println("s1 : "+s1);
System.out.println("s2 : "+s2);
}
}
Runtime class:
Available in java.lang package.
since jdk 1.0
Runtime class represents JVM.
The current runtime (virtual environment - JVM) can be obtained from the getRuntime()
method.
It is a Singleton class.
System.out.println("jvm1 : "+jvm1);
System.out.println("jvm2 : "+jvm2);
}
}
Increasing Heap size and JVM size dependant to Main memory (RAM).
Commands to increase the size:
-Xms --> to set Heap size
-Xmx --> to set JVM size
class-files : Outer.class
Outer$Inner.class
class Outer
{
static void f1()
{
System.out.println("Outer class static method");
}
static class Inner
{
static void f2()
{
System.out.println("Inner class static method");
}
}
public static void main(String args[])
{
Outer.f1();
// Outer.f2(); //Error : Not defined in Outer class
Outer.Inner.f2();
}
}
class Outer
{
void f1()
{
System.out.println("Outer class non-static method");
}
class Inner
{
void f2()
{
class Outer
{
static class Inner
{
void fun()
{
System.out.println("Inner class non-static method");
}
}
public static void main(String args[ ])
{
Outer.Inner obj = new Outer.Inner();
obj.fun();
}
}
Accessing static members of non-static inner class: It is not allowed to define static members(free
accessible) inside the non-static context(restricted access). Hence non-static inner class doesn’t have
static declarations.
class Outer
{
class Inner
{
static void fun() //Error :
{
System.out.println("Inner class static method");
}
}
}
Note : private members of one class cannot be accessed from another class even in Parent-
Child relation also
class First
{
private static int a=100;
}
class Second extends First
{
public static void main(String[] args)
{
System.out.println("a value : "+First.a);
}
}
But an Outer class can access even private members of inner class:
class Outer
{
class Inner
{
private void method()
{
System.out.println("Inner class private method");
}
}
public static void main(String args[ ])
{
Outer obj1 = new Outer();
Outer.Inner obj2 = obj1.new Inner();
obj2.method();
}
}
In the above program we can instantiate Inner class using Outer object as follows…
class Outer
Static Members of Outer class are directly visible to inner class including private:
class Outer
{
private static int x = 100 ;
class Inner
{
private void method()
{
System.out.println("Outer's x val : "+Outer.x);
}
}
public static void main(String args[ ])
{
new Outer().new Inner().method();
}
}
Note : non-static members of outer class including private can be accessed from the inner class as
follows.....
<outer_class_name>.this.<outer_class_non-static-member>
class Outer
{
private int x ;
Outer(int x)
{
this.x = x ;
}
class Inner
{
int x ;
Inner(int x)
class Outer
{
static
{
class LocalInner
{
//Outer$1LocalInner.class
}
}
Outer
{
class LocalInner
{
//Outer$2LocalInner.class
}
}
}
Scope of local inner class is always restricted to that block where it has defined
class Outer
{
static
More than one level of local inner classes(as shown below) creates complex user defined data
types.
class Outer
{
Outer()
{
class LocalInner
{
void check()
{
System.out.println("Class inside constructor...");
class InnerInner
{
void check()
{
System.out.println("Class inside method....");
}
}
new InnerInner().check();
}
}
By Srinivas (C/DS/Java trainer) Page 224
new LocalInner().check();
}
public static void main(String args[ ])
{
new Outer();
}
}
interface Connection
{
void check();
}
class DriverManager
{
public static Connection getConnection()
{
Connection con = new Connection()
{
public void check()
{
System.out.println("anonymous.....");
}
};
return con;
}
}
class DatabaseConnection
{
public static void main(String args[])
By Srinivas (C/DS/Java trainer) Page 225
{
Connection con = DriverManager.getConnection();
con.check();
}
}
interface Connection
{
void check();
}
class DriverManager
{
public static void setConnection(Connection con)
{
con.check();
}
}
class DatabaseConnection
{
public static void main(String args[])
{
DriverManager.setConnection(new Connection()
{
public void check()
{
System.out.println("anonymous.....");
}
});
}
}
class RunnableAnonymous
{
public static void main(String[] args)
{
Thread t = new Thread(new Runnable()
{
public void run()
{
System.out.println("anonymous....");
}
}
);
t.start();
}
}
Byte Streams
Byte streams are those in which the data will be transferred one byte at a time between
primary memory to secondary memory and secondary memory to primary memory either
locally or globally.
java.io.* package contains some set of classes and interfaces to perform byte stream
operations.
Programs use byte streams to perform input and output operations of 8-bit data.
All byte stream classes are descended from InputStream and OutputStream classes
The two main classes used to perform Byte stream operations are InputStream &
OutputStream.
These classes are abstract classes.
FileInputStream class:
This is the concrete (which we can create an object or it contains all defined methods) sub-
class of all InputStream class.
public class FileInputStream extends InputStream
This class is always used to open the file in read mode.
Opening the file in read mode is nothing but creating an object of FileInputStream class.
FileInputStream (String fname) throws FileNotFoundException
FileInputStream fis=new FileInputStream (“abc.txt”);
If the file name abc.txt does not exist then an object of FileInputStream fis is null and hence
we get FileNotFoundException.
FileOutputStream class:
This is the concrete sub-class of all OutputStream classes.
public class FileOutputStream extends OutputStream
This class is always used for opening the file in write mode is nothing but creating an object
of FileOutputStream class.
FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)
If the flag is true the data will be appended to the existing file else if flag is false the data will
be overlapped with the existing file data.
If the file is opened in write mode then the object of FileOutputStream will point to that file
which is opened in write mode.
If the file is unable to open in write mode an object of FileOutputStream contains null.
/*class FileInputStream
{
public FileInputStream(String name) throws FileNotFoundException
{
opens a file in read mode.....
}
public void close() throws IOException
By Srinivas (C/DS/Java trainer) Page 229
{
closes the file
}
public int read()
{
on success, returns ASCII value of character
on failure, returns -1 .
}
}
*/
import java.io.*;
class ByteStreams
{
public static void main(String[] args) throws Exception
{
FileInputStream fis = null ;
try
{
fis = new FileInputStream("d:/ByteStreams.java");
System.out.println("File opened....");
int ch ;
while((ch=fis.read()) != -1)
{
System.out.print((char)ch);
}
}
finally
{
if(fis != null)
{
fis.close();
System.out.println("File closed...");
}
}
}
}
Append mode :
Used to append the data.
If file is present, it opens and place the cursor at the end of the file to add new contents.
If file is not present, it creates new file.
import java.io.*;
class ByteStreams
{
public static void main(String[] args) throws Exception
{
FileInputStream fis = null ;
FileOutputStream fos = null ;
try
{
fis = new FileInputStream("d:/ByteStreams.java");
fos = new FileOutputStream("d:/Output.txt");
int ch ;
while((ch=fis.read()) != -1)
{
fos.write(ch);
}
System.out.println("File copied....");
}
finally
{
if(fis != null)
{
fis.close();
}
if(fos != null)
{
fos.close();
}
}
}
}
int ch ;
while((ch=fis.read()) != -1)
{
fos.write(ch);
}
System.out.println("Content appended.....");
}
finally
{
if(fis != null)
{
fis.close();
}
if(fos != null)
{
fos.close();
}
}
}
}
Note : Byte streams are mainly used to work with binary files such as images, audio files….
import java.io.*;
class CopyImage
{
public static void main(String[] args) throws Exception
{
FileInputStream fis = null ;
FileOutputStream fos = null ;
try
{
fis = new FileInputStream("g:/input.jpg");
fos = new FileOutputStream("g:/output.jpg");
Character Streams
Prior to JDK 1.1, the input and output classes (mostly found in the java.io package) supported
only 8-bit "byte" streams.
In JDK 1.1 the concept of 16-bit Unicode "character" streams was introduced.
While the byte streams were supported via the java.io.InputStream and
java.io.OutputStream classes and their subclasses, character streams are implemented by the
java.io.Reader and java.io.Writer classes and their subclasses.
For example, to read files using character streams, you'd use the java.io.FileReader class; to
read using byte streams you'd use java.io.FileInputStream.
Unless you're working with binary data such as image and sound files, you should use readers
and writers to read and write information for the following reason:
Programs that use character streams are easier to internationalize because they're not
dependent upon a specific character encoding.
To bridge the gap between the byte and character-stream classes, Java provides the
java.io.InputStreamReader and java.io.OutputStreamWriter classes.
The only purpose of these classes is to convert byte data into character-based data according
to a specified (or the platform default) encoding.
FileReader:
Inherited from InputStreamReader.
Used to read character by character from any underlying stream.
We can’t read like images, videos, sound files as these are not come under byte streams.
FileWriter:
Inherited from OutputStreamReader.
Used to Write character by character to any kind of file or output device.
By Srinivas (C/DS/Java trainer) Page 233
import java.io.* ;
class CharacterStreams
{
public static void main(String[] args) throws IOException
{
FileReader fr = null ;
FileWriter fw = null ;
try
{
fr = new FileReader("g:/input.jpg");
fw = new FileWriter("g:/output.jpg");
int ch ;
while((ch = fr.read()) != -1)
{
fw.write(ch);
}
System.out.println("copied....");
}
finally
{
if(fr != null)
{
fr.close();
}
if(fw != null)
{
fw.close();
}
}
}
}
Note :
class must implements Serializable interface to serialize that object.
In the process of serialization, transient variables will not participate.
The following example code shows how to serialize and de-serialize of an object, it includes three
programs,
1. Defining a class that includes some properties of an employee.
2. Serializing Employee object.
3. De-serializing Employee object.
Serialization:
import java.io.*;
class Serialization
{
public static void main(String[] args) throws Exception
By Srinivas (C/DS/Java trainer) Page 235
{
Employee e = new Employee(101,"Syam",50000,12345);
FileOutputStream fos = null ;
ObjectOutputStream oos = null ;
try
{
fos = new FileOutputStream("d:/Emp.ser");
oos = new ObjectOutputStream(fos);
oos.writeObject((Object)e);
System.out.println("Serialized.....");
}
finally
{
if(oos != null)
{
oos.close();
}
if(fos != null)
{
fos.close();
}
}
}
}
De Serialization:
import java.io.*;
class DeSerialization
{
public static void main(String[] args) throws Exception
{
FileInputStream fis = null ;
ObjectInputStream ois = null ;
try
{
fis = new FileInputStream("d:/Emp.ser");
ois = new ObjectInputStream(fis);
Employee e1 = (Employee)ois.readObject();
System.out.println("De-Serialized.....");
transient keyword:
The keyword transient in Java used to indicate that the variable should not be serialized.
By default all the variables in the object is converted to persistent state.
In some cases, you may want to avoid some variables (confidential data) because you don’t
have the necessity to transfer across the network.
So, you can declare those variables as transient. If the variable is declared as transient, then it
will not be persisted means will not be participated in Serialization process.
How many methods Serializable has? If not, then what is the purpose of Serializable interface?
Serializable interface doesn't have any method.
It is empty interface.
It is also called Marker Interface or Tagged interface in Java.
Marker interface is used as a information tag about an object.
It adds special behavior to Object of class which is implementing it.
Examples
o java.io.Serializable interface
o java.lang.Cloneable interface
If a class is Serializable but its super class in not, what will be the state of the instance variables
inherited from super class after de serialization?
Java serialization process only continues in object hierarchy till the class is Serializable i.e.
implements Serializable interface in Java and values of the instance variables inherited from
class NotSerializable{
int a;
}
public class Employee extends NotSerializable implements java.io.Serializable{
public String name;
public String address;
public transient int SSN;
public static int number;
}
Buffered Streams :
Buffer is a temporary storage area while processing the information.
In some of the applications we use Buffers to process the data instead of fetching
information from the secondary memory every time.
Processed information will be stored in Buffer temporarily.
Once we close(save) the Buffer, the info saved permanently in Secondary memory.
BufferedReader:
import java.io.*;
class BufferedStreams
{
public static void main(String[] args) throws Exception
{
FileReader fr = null ;
FileWriter fw = null ;
BufferedWriter bw = null ;
try{
fr = new FileReader("d:/BufferedStreams.java");
fw = new FileWriter("g:/buffer.txt");
bw = new BufferedWriter(fw);
int ch;
while( (ch=fr.read()) != -1 ){
bw.write(ch);
}
}
finally{
if(bw != null){
bw.close();
}
if(fr != null){
fr.close();
}
if(fw != null){
fw.close();
}
By Srinivas (C/DS/Java trainer) Page 240
}
}
}
StringTokenizer class :
Available in util package.
Since jdk 1.0.
Used to split a string into Tokens(words).
import java.util.StringTokenizer;
class Tokenizer
{
public static void main(String[] args)
{
String line = "this is a test" ;
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
String line ;
while( (line = br.readLine()) != null)
{
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
count++ ;
}
BufferedInputStream
BufferedInputStream adds extra functionalities to another InputStream.
BufferedInputStream creates internal array with buffer size on the machine to read and write
group of bytes.
We can skip the data while reading from the internal buffer array using pre-defined skip()
method.
We can also reset the position to be read using two pre-defined functions mark() and reset().
PrintStream class :
The PrintStream class is obtained from the FilterOutputstream class that implements a
number of methods for displaying textual representations of Java primitive data types.
Unlike other output streams, a PrintStream never throws an IOException and the data is
flushed to a file automatically i.e. the flush() method is automatically invoked after a byte
array is written.
The constructor of the PrintStream class is written as:
PrintStream (java.io.OutputStream out); //create a new print stream
The print( ) and println( ) methods of this class give the same functionality as the method of
standard output stream.
Example:
import java.io.*;
public class PrintStreamDemo
{
public static void main(String[] args)
{
try
{
FileOutputStream out = new FileOutputStream("out.txt");
PrintStream p = new PrintStream(out);
p.println("this text will be written into out.txt after run");
System.out.println("text has been written, go and check out.txt in the
current directory");
p.close();
} catch (Exception e) {}
}
}
ByteArrayInputStream
It is an implementation of an input stream that uses a byte array as the source.
This class has two constructors, each of which requires a byte array to provide the data
source:
By Srinivas (C/DS/Java trainer) Page 244
ByteArrayInputStream(byte array[ ])
ByteArrayInputStream(byte array[ ], int start, int numBytes)
Here, array is the input source.
The second constructor creates an InputStream from a subset of your byte array that begins
with the character at the index specified by start and is numBytes long.
import java.io.*;
class ByteArrayInputStreamDemo
{
public static void main(String args[]) throws IOException
{
String tmp = "abcdefghijklmnopqrstuvwxyz";
byte b[] = tmp.getBytes();
ByteArrayInputStream bais1 = new ByteArrayInputStream(b);
ByteArrayInputStream bais2= new ByteArrayInputStream(b,3,3);
DataInputStream
Is used to read java primitive data types from an underlying input stream.
It is inherited from FilterInputStream class.
It has only one constructor, and it takes byte stream object as an argument.
String readLine() :
Deprecated. This method does not properly convert bytes to characters.
Method Description
f.exists() Returns true if file exists.
f.isFile() Returns true if this is a normal file.
f.isDirectory() true if "f" is a directory.
f.getName() Returns name of the file or directory.
f.isHidden() Returns true if file is hidden.
f.lastModified() Returns time of last modification.
f.length() Returns number of bytes in file.
f.getPath() path name.
f.delete() Deletes the file.
f.renameTo(f2) Renames f to File f2. Returns true if successful.
f.createNewFile() Creates a file and may throw IOException.
Creating a File:
/*class File
{
public boolean exists()
{
Tests whether the file or directory is present
}
public boolean createNewFile() throws IOException{
creates a file in specified path...
}
}*/
Creating directories:
import java.io.*;
class CreateDirectory
{
public static void main(String[] args)
{
String s1 = "d:/test" ;
String s2 = "d:/test1/test2/test3";
File d1 = new File(s1);
File d2 = new File(s2);
if(d1.mkdir())
System.out.println(s1+" created...");
if(d2.mkdirs())
System.out.println(s2+" created...");
}
}
File copy:
import java.io.*;
public class Copy
{
public static void main(String[] args) throws IOException
{
File inputFile = new File("Copy.java");
File outputFile = new File("OutCopy.java");
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
int c;
while ((c = in.read()) != -1)
out.write(c);
By Srinivas (C/DS/Java trainer) Page 249
in.close();
out.close();
}
}
import java.io.File;
public class Main
{
public static void main(String[] args)
{
String filePath = File.separator + "Java" + File.separator + "IO";
File file = new File(filePath);
System.out.println(file.getPath());
}
}
import java.io.File;
public class Main {
public static void main(String[] args)
{
String str="f:/Dir1/dir2/dir3";
boolean isDirectoryCreated = (new File(str).mkdirs());
if (isDirectoryCreated)
{
System.out.println("successfully created");
}
else
{
System.out.println("creation failed");
}
}
}
import java.io.File;
public class SetWritableTest
{
public static void main(String[] args)throws SecurityException
{
File file = new File("ddd.txt");
if (file.exists())
{
boolean bval = file.setWritable(false);
System.out.println("set the owner's write permission: "+ bval);
}
else
{
System.out.println("File cannot exists: ");
}
}
}
Hidden file: a file is considered to be hidden, if it’s marked as hidden in the file properties.
import java.io.File;
import java.io.IOException;
public class FileHidden
{
public static void main(String[] args) throws IOException
{
File file = new File("FileHidden.java");
if(file.isHidden())
{
System.out.println("This file is hidden");
}
else
{
System.out.println("This file is not hidden");
}
}
}
Need of reflection:
Reflection is a feature in the Java programming language.
It allows an executing Java program to examine or "introspect" upon itself, and
manipulates internal properties of the program.
For example, it's possible for a Java class to obtain the names of all its members and
display them.
For example, there is no way in a Pascal, C, or C++ program to obtain information
about the functions defined within that program.
The reflection API represents, or reflects, the classes, interfaces, and objects in the
current Java Virtual Machine.
With the reflection API you can:
Determine the class of an object.
Get information about a class's modifiers, fields, methods, constructors, and
super classes.
Find out what constants and method declarations belong to an interface.
Create an instance of a class whose name is not known until runtime.
Get and set the value of an object's field, even if the field name is unknown to
your program until runtime.
Invoke a method on an object, even if the method is not known until runtime.
Create a new array, whose size and component types is not known until runtime,
and then modify the array's components.
Interface info : One class can extends only one class, but can implements more than one
interface.
import java.util.ArrayList;
class InterfacesInfo
{
public static void main(String[] args)
{
ArrayList al = new ArrayList();
Class c = al.getClass();
Class in[ ] = c.getInterfaces();
System.out.println(c.getName()+" implementing.........");
for(int i=0 ; i<in.length ; i++)
{
System.out.println(in[i].getName());
}
}
}
Finding Fields Info : Properties of an Object (either static or non-static) referred as fields.
import java.lang.reflect.Field;
class FieldsInfo
{
public static void main(String[] args)
{
Thread t = new Thread();
Class c = t.getClass();
Field f[ ] = c.getFields();
System.out.println(c.getName()+" variables set..");
for(int i=0 ; i<f.length ; i++)
{
System.out.println(f[i]);
}
}
}
import java.lang.reflect.Field;
class FieldsInfo
{
public static void main(String[] args)
{
//System s = new System(); //CE : can't be instantiated.
Class s = java.lang.System.class;
System.out.println("fields of System class are......");
Field f[] = s.getFields();
for(int i=0 ; i<f.length ; i++)
System.out.println(f[i]);
}
}
import java.lang.reflect.Method;
class MethodsInfo
{
public static void main(String[] args)
{
Example e = new Example();
Class c = e.getClass();
Method m[] = c.getMethods();
System.out.println(c.getClass()+" containing follwing methods.....");
for(int i=0 ; i<m.length ; i++)
{
System.out.println("method "+(i+1)+" : "+m[i].getName());
}
}
}
class DynamicLoading
{
public static void main(String[] args)
{
java.util.Scanner sc = new java.util.Scanner(System.in);
System.out.print("Enter one class name : ");
String name = sc.next();
try{
Class.forName(name);
System.out.println("class is loading successfully.....");
}
catch (ClassNotFoundException cn){
System.out.println("class doesn't exist.....");
}
}
}
class Test
{
public static void main(String[] args)
{
String s1 = "one";
String s2 = new String("two");
char c[ ] = {'t','h','r','e','e'};
String s3 = new String(c);
byte b[ ] = {65,66,67,68};
String s4 = new String(b);
String length:
Finding length of a string is possible in two ways.
Using length() in string class we can find length of the String
Using Array class “length” property we can find out number of strings inside the array.
class StringDemo
{
public static void main(String args[])
{
String palindrome = "Dot saw I was Tod";
String set[] = {"one" , "two" , "three"};
int len1 = palindrome.length();
int len2 = set.length;
System.out.println( "Palindrome Length is : " + len1);
System.out.println( "Number of strings in set : " + len2);
}
}
String concatenation:
By Srinivas (C/DS/Java trainer) Page 257
Merging of two strings is nothing but string concatenation.
We can concatenate two strings in two ways.
As “+” operator exhibits polymorphism in java, we can concatenate two string using “+”
operator.
By using concat() method also we can perform concatenation operation.
/*class String{
String concat(String str)
{
Concatenates the specified string to the end of this string.
}
}*/
class StringDemo
{
public static void main(String[] args)
{
String s1 = "Hello" ;
String s2 = "World" ;
System.out.println("Before Merge : \nS1 : "+s1+"\nS2 : "+s2+"\n");
// s1.concat(s2);
s2 = s1.concat(s2);
System.out.println("After Merge : \nS1 : "+s1+"\nS2 : "+s2+"\n");
}
}
class Test{
String s ;
Test(String s){
this.s = s ;
}
}
class StringDemo{
public static void main(String[] args) {
Test t1 = new Test("Hello");
Test t2 = new Test("Hello");
System.out.println("t1 : "+t1.hashCode());
System.out.println("t2 : "+t2.hashCode());
System.out.println("s1 : "+s1.hashCode());
System.out.println("s2 : "+s2.hashCode());
}
}
System.out.println("s1 : "+s1.hashCode());
System.out.println("s2 : "+s2.hashCode());
System.out.println("t1.s : "+t1.s.hashCode());
}
}
Char at position:
public class StringDemo {
public static void main(String args[]) {
String s = "Naresh technologies";
char result = s.charAt(8);
System.out.println(result);
System.out.printf("%c",s.charAt(7)); //using format specifiers
}
}
String comparison:
public class StringDemo{
public static void main(String args[]) {
String str1 = "Strings are immutable";
String str2 = "Strings are immutable";
String str3 = "Integers are not immutable";
int i=100;
String s2=Integer.toString(i); //converts primitive to string
By Srinivas (C/DS/Java trainer) Page 262
System.out.println(s2);
If String is immutable then how can I able to change the contents of the object?
If you made any changes that will not directly reflect on old string. Internally a new String
object is created to do the changes.
So suppose you declare a String object:
String myString = “Hello”;
Next, you want to append “Guest” to the same String. What do you do?
myString = myString +“world”;
When you print the contents of myString the output will be “Hello world”.
Although we made use of the same object (myString), internally a new object was created in
the process.
So, if you were to does some string operation involving append or trim or some other
method call to modify your string object, you would really be creating those many new
objects of class String.
Code1:
class Example {
public static void main(String[] args) {
String s1="naresh";
s1=s1+"tech";
System.out.println(s1);
Code2:
class Example {
public static void main(String[] args) {
String s1="naresh";
s1=s1+"tech";
System.out.println(s1);
class Example {
public static void main(String[] args) {
StringBuilder sb1=new StringBuilder("naresh tech");
System.out.println(sb1);
sb1.deleteCharAt(2);
sb1.insert(2,'gm');
System.out.println(sb1);
}
}
By Srinivas (C/DS/Java trainer) Page 264
Collection Framework
For every computer application maintaining and managing the data is mandatory.
While storing the data into secondary storage device like database, if we arrange the data in
a particular structure, we can access effectively at later time.
To structure the data number of algorithms were proposed.
Some of the examples are :
1. stack (Last In First Out)
2. queue (First In First Out)
3. arrays (Stores info in sequential order)
4. linked lists(Stores info in the form of nodes)
5. trees
6. graphs.
In other languages like C and C++, we need to implement proposed algorithms to structure
the data in any computer application.
But Java API provides interfaces and classes to structure the data which are implementations
of those algorithms.
Mainly used interfaces as given below.
Collection is the super interface of all.
No direct implementation of collection interface.
Array:
They are fixed in size.
With respect to memory arrays are not preferable.
Arrays shows very good Performance(index based)
Can hold only homogeneous data elements.
Arrays can hold both primitive data types and objects
They do not have any underlying data structures algorithms.
Arrays can hold duplicate elements.
int arr[ ] = new int[5]; //memory will be allocated using "new" operator at runtime
arr[0] = 10 ; //primitive value
arr[1] = new Integer(20) ; //using wrapper classes, we are storing Integer object
arr[2] = 10 ;
Collections :
Grow able in nature.
With respect to memory, collections are recommended.
It shows poor Performance(All the collections are not index based, for example Linked List).
Can hold both homogenous and Heterogeneous.
They have underlying data structure.
Collections hold only Objects.
List interface :
ArrayList :
1) available in java.util package.
2) since jdk 1.2
3) ordered
4) allows duplicates.
5) initial capacity (n=10)
5) incrementing capacity (3n/2) that means it increases half of its previous capacity.
6) ArrayList is not synchronized by default but can be synchronized explicitly as follows.....
Collections.synchronizedList(new ArrayList(....));
import java.util.ArrayList;
class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList al = new ArrayList();
al.add(new Integer(10)); //boxing
al.add(20); //auto boxing (since jdk 1.5)
al.add(10); //duplicates allowed
al.add("amar");//heterogenous data allowed.
System.out.println(al);
}
}
import java.util.ArrayList;
class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(new Integer(10));
al.add(new Float(34.56)); //CE : not allowed
}
}
ArrayList elements we can print directly by printing Object reference of that List, because
internal iterator will access the elements.
Using internal elements only we can print the elements but we can't process those elements.
To process elements number of explicit Iterators are available in the Collection API.
1. For-each loop
2. Enumeration
3. Iterator
syntax :
for(<data_type> <var> : <array>or<collection>)
{
Processing logic…
}
Example:
class ForEachExample
{
public static void main(String[] args)
{
int arr[ ] = {10,20,30,40,50};
System.out.println("Array elements are : ");
for(int ele : arr)
{
System.out.println(ele);
}
}
}
Program:
class ForEachLoop
{
public static void main(String[] args)
{
int arr[ ] = {10,20,30,40,50};
int i=0 ;
for( int ele : arr )
{
arr[i] = ele + 100 ;
i++;
}
System.out.println("Array elements are : ");
for( int ele : arr ){
System.out.println(ele);
}
}
}
import java.util.ArrayList;
class ArrayListDemo extends ArrayList
{
public static void main(String[] args)
{
ArrayListDemo al = new ArrayListDemo();
for(int i=10 ; i<=100 ; i+=10)
{
al.add(new Integer(i));
}
System.out.println(al);
al.removeRange(4,8); //removes the elements from index 4 to 7
System.out.println(al);
}
}
/*
public E remove(int index)
Removes the element at the specified position in this list.
*/
import java.util.ArrayList;
class ArrayListDemo
{
By Srinivas (C/DS/Java trainer) Page 270
public static void main(String[] args)
{
ArrayList al = new ArrayList();
for(int i=10 ; i<=30 ; i+=10)
{
al.add(new Integer(i));
al.add(new Integer(2));
}
System.out.println(al);
al.remove(2); //deletes element @ index 2
System.out.println(al);
}
}
/*
public boolean remove(Object o)
Removes the first occurrence of the specified element from this list, if it is present
*/
import java.util.ArrayList;
class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList al = new ArrayList();
for(int i=10 ; i<=30 ; i+=10)
{
al.add(new Integer(i));
al.add(new Integer(2));
}
System.out.println(al);
al.remove(new Integer(2)); //deletes first occurance of 2
System.out.println(al);
}
}
if(al1.isEmpty())
System.out.println("al1 list is empty");
else
System.out.println("al1 contains elements");
}
}
Note: In ArrayList it is not possible to check the internal capacity(no such method). But in Vector we
can check internal capacity and incrementing capacity using pre-defined method.
Tip : Only the collection classes which are from jdk 1.0 are synchronized by default. Most of the
Collection classes are introduced from jdk 1.2 which are not synchronized by default but can be
syncrhronized explicitly user pre-defined static functions available in Collections class
for example.....
Collections.synchronizedList();
Collections.synchronizedSet();
Collections.synchronizedMap();
Collections.synchronizedSortedSet();
Collections.synchronizedSortedMap();
boolean hasMoreElements()
Tests if this enumeration contains more elements.
Object nextElement()
Returns the next element of this enumeration if this enumeration object */
import java.util.Vector;
import java.util.Enumeration;
class VectorDemo
{
public static void main(String[] args)
{
Vector v = new Vector();
System.out.println("intial size : "+v.size());//returns number of elements
System.out.println("intial capacity : "+v.capacity());
for(int i=10 ; i<=100 ; i+=10)
{
v.add(new Integer(i));
}
System.out.println("after 10 insertions size : "+v.size());
By Srinivas (C/DS/Java trainer) Page 273
System.out.println("after 10 insertions capacity : "+v.capacity());
v.add(110);
System.out.println("after 11 insertions size : "+v.size());
System.out.println("after 11 insertions capacity : "+v.capacity());
Enumeration e = v.elements();
while(e.hasMoreElements())
{
System.out.println(e.nextElement());
}
}
}
import java.util.Vector;
import java.util.Enumeration; //interface
class VectorDemo
{
public static void main(String[] args)
{
Vector v = new Vector(3,2);
System.out.println("initial capacity : "+v.capacity());
v.add(10);
v.add(20);
v.add(30);
v.add(40);
System.out.println("after 4 insertions, capacity : "+v.capacity());
Enumeration e = v.elements();
System.out.println("Vector elements are : ");
while(e.hasMoreElements())
{
System.out.println(e.nextElement());
}
}
}
LinkedList :
1) Available in util package.
2) since jdk 1.2
3) ordered
4) allows duplicates
5) initial capacity n=0
6) incrementing capacity ++n
7) not synchronized by default.
import java.util.ArrayList ;
import java.util.LinkedList ;
class ConstructionTime
{
private static Object arr[ ] ;
static
{
arr = new Object[1000000] ;
for(int i=0 ; i<arr.length ; i++)
{
arr[i] = new Object();
}
}
public static void main(String[] args)
{
long start, end ;
Note : HashSet & LinkedHashSet stores the data into collection Object according to HashTable
algorithm.
structure format :
Every element in the Hashtable stores according to key element and size of Hashtable only.
But in Set interface, elements uses only Hashtable size to be stored but not key elements.
HashSet :
available in util package.
since from jdk 1.2
not ordered
not allowed duplicates.
initial capacity is 16
default load factor is 0.75
HashSet is not Synchronized by default, can be synchronized explicitly as follows...
Collections.synchronizedSet(new HashSet(....));
import java.util.*;
class HashSetDemo
{
public static void main(String[] args)
{
ArrayList list = new ArrayList();
Random r = new Random();
for(int i=1 ; i<=10 ; i++)
{
int ele = r.nextInt(5);
list.add(new Integer(ele));
}
System.out.println("List : "+list); // allow duplicates
Note : Some of the implementations rejects the element when it is duplicated in the Collection.
for example... Set interface rejects the duplicate elements.
Map interface replaces the duplicate elements.
import java.util.*;
class HashSetDemo
{
public static void main(String[] args)
{
HashSet set = new HashSet();
set.add("amar");
if(set.add("amar"))
System.out.println("duplicates are replaced");
else
System.out.println("duplicates are rejected");
}
}
load factor:
The amount of load(no of elements can add from each location of hash table).
Once load is reached, the size of hash table will be increased implicitly(probably doubled)
and all the elements are re-arranged automatically.
Load factor = number of elements / size of hash table
LinkedHashSet :
Iterator :
It is an interface having pre-defined functions used to iterate Collection Object to process the
elements.
Much working like Enumeration.
Iterator introduced in jdk 1.2 along with new implementations of Collection interface.
To get Iterator object, we need to call iterator() method on any Collection instance.
Iterator <identifier> = Collection_Object.iterator();
import java.util.*;
class SetDemo
{
public static void main(String[] args)
{
// HashSet set = new HashSet(); // No insertion order
LinkedHashSet set = new LinkedHashSet(); // Maintain insertion order
TreeSet:
TreeSet maintains sorted order of inserted elements.
It will arrange the elements in ascending order using balanced binary search tree algorithm.
since from jdk 1.2
import java.util.*;
class SetDemo
{
public static void main(String[] args)
{
Random r = new Random();
By Srinivas (C/DS/Java trainer) Page 279
// HashSet hs = new HashSet();
// LinkedHashSet hs = new LinkedHashSet();
TreeSet hs = new TreeSet();
Note : HashMap and LinkedHashMap stores the elements according to Hashtable algorithm only.
HashMap :
available in util package
since from jdk 1.2
not ordered
duplicates allowed with unique keys
default capacity is 16
default load factor is 0.75
HashMap is not synchronized by default. but can be synchronized explicitly as follows.
Collections.synchronizedMap(new HashMap(...));
import java.util.*;
class SetDemo
By Srinivas (C/DS/Java trainer) Page 280
{
public static void main(String[] args)
{
HashSet hs = new HashSet();
hs.add("one");
if(hs.add("one"))
System.out.println("Duplicate element is replaced in Set");
else
System.out.println("Duplicate element is rejected in Set");
}
}
import java.util.HashMap ;
class MapDemo
{
public static void main(String[] args)
{
HashMap map = new HashMap();
map.put(10 , "One");
System.out.println("Map : "+map);
import java.util.HashMap ;
class MapDemo
{
public static void main(String[] args)
{
HashMap map = new HashMap();
map.put(10 , "One");
map.put(20 , "One");
map.put(null , "Two");
map.put("key" , "Three");
map.put(34.56 , "Four");
System.out.println("Map : "+map);
}
}
Note : we can apply generics on map collection object. Once we set restrictions on data, all the
methods logic will be converted according to generics type.
import java.util.HashMap ;
class MapDemo
By Srinivas (C/DS/Java trainer) Page 281
{
public static void main(String[] args)
{
HashMap<Integer , String> map = new HashMap<Integer, String>();
map.put(10 , "One");
map.put(34.56 , "Four"); // Error : Only Integer keys allowed
System.out.println("Map : "+map);
}
}
Note : The only difference between LinkedHashMap and HashMap is, HashMap doesn't maintain
insertion order of elements where as LinkedHashMap does it. LinkedHashMap since jdk 1.4
import java.util.*;
class MapDemo
{
public static void main(String[] args)
{
HashMap hm = new HashMap();
hm.put(26, "one");
hm.put(26, "two"); //"one" is replaced with "two"
hm.put(16, "two"); //duplicate elements allowed
hm.put(null,"three"); //null key allowed
hm.put(56,null); //null element allowed
hm.put("56","four"); //heterogenous keys allowed
System.out.println(hm);
}
}
TreeMap :
TreeMap maintains ascending order of keys.
TreeMap does it through Balanced binary trees.
import java.util.*;
class MapDemo
{
public static void main(String[] args)
{
TreeMap tm = new TreeMap();
tm.put(26, "one");
tm.put(16, "two");
//tm.put(null,"three"); //not allowed
//tm.put("str","four"); //not allowed
System.out.println(tm);
}
}
list.add(100);
list.add(200);
System.out.println("List : "+list);
list.addFirst(111);
list.addLast(222);
System.out.println("List : "+list);
Note : If we collect LinkedList object address into a particular implemented interface type, we cannot
access all the interfaces functionality.
import java.util.*;
class LinkedListDemo
{
public static void main(String[] args)
{
Queue q = new LinkedList();
q.add(100);
q.add(200);
System.out.println("Queue : "+q);
System.out.println("Peek : "+q.peek());
PriorityQueue :
Maintains insertion order but returns the elements in the ascending order(smallest element
first).
PriorityQueue top element is always the smallest element in the queue.
import java.util.*;
class PriorityQueueDemo
{
public static void main(String[] args)
{
Random r = new Random();
PriorityQueue q = new PriorityQueue();
for(int i=1 ; i<=6 ; i++)
{
q.add(new Integer(r.nextInt(100)));
}
System.out.println("Elements : "+q);
}
}
/*
public Object peek()
Retrieves but does not remove
on success it returns head element
on failure it returns "null" element
import java.util.*;
class PriorityQueueDemo
{
public static void main(String[] args)
{
Random r = new Random();
PriorityQueue q = new PriorityQueue();
for(int i=1 ; i<=6 ; i++)
{
q.add(new Integer(r.nextInt(100)));
}
System.out.println("Queue : "+q);
for(int i=1 ; i<=6 ; i++)
{
import java.util.*;
class QueueDemo{
public static void main(String[] args) {
LinkedList q = new LinkedList();
Random r = new Random();
for(int i=1 ; i<=5 ; i++){
q.add(new Integer(r.nextInt(50)));
}
q.addFirst(100);
q.addLast(200);
System.out.println(q);
import java.util.*;
class LinkedListDemo{
public static void main(String[] args) {
LinkedList l = new LinkedList();
for(int i=10 ; i<=100 ; i+=10){
l.add(new Integer(i));
}
System.out.println("List : "+l);
for(int i=0 ; i<l.size() ; i++){
System.out.println("Poll : "+l.poll());
}
}
}
import java.applet.Applet;
import java.awt.*;
public class FirstApplet extends Applet
{
By Srinivas (C/DS/Java trainer) Page 287
public void paint(Graphics g)
{
g.drawString("Hello world", 200,200);
}
}
/*
<applet code = "FirstApplet.class" width="600" height = "600">
</applet>
*/
<BODY>
<applet code = "FirstApplet.class" width="600" height = "600">
</applet>
</BODY>
</HTML>
import java.applet.Applet;
import java.awt.*;
public class FirstApplet extends Applet
{
public FirstApplet()
{
System.out.println("Applet is instantiated....");
}
public void paint(Graphics g)
{
g.drawString("Hello world", 200,200);
}
public void init()
{
System.out.println("Applet is initialized....");
}
public void start()
{
System.out.println("Control enter into Applet....");
}
public void stop()
{
System.out.println("Control goes off the Applet...");
}
public void destroy()
{
System.out.println("Resource released.....");
}
}
/*
<applet code = "FirstApplet.class" width="600" height = "600">
</applet>
*/
Component:
The Object which is displayed on the Applet window is called component.examples....
Buttons, Textbox, CheckBox, RadioButton....
Layout :
Arrangement of Components by setting Bounds on the window.
Java API has many pre-defined layout classes to arrange the components.
1) Flow Layout
import java.applet.Applet;
import java.awt.*;
public class Buttons extends Applet
{
Button b1,b2;
public void init(){
this.setLayout(null);
this.b1 = new Button("BUTTON#1");
this.b2 = new Button("BUTTON#2");
b1.setBounds(150,200,150,50);
b2.setBounds(300,200,150,50);
this.add(b1);
this.add(b2);
}
}
/*
<applet code = "Buttons.class" width="600" height = "600">
</applet>
*/
Event Listeners:
An Event is an operation(action) performed on a component of Applet.
When action performed, Component fires one event.
When we create Buttons, these cannot be reacted to Events which are performed.
ActionListener interface must be implemented to write EventListener logic for Buttons.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class ButtonListener extends Applet implements ActionListener
{
Button b1,b2;
public void init()
{
this.setLayout(null);
this.b1 = new Button("BUTTON#1");
this.b2 = new Button("BUTTON#2");
b1.setBounds(150,200,150,50);
b2.setBounds(300,200,150,50);
this.add(b1);
this.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == b1)
System.out.println("you clicked button1");
else
System.out.println("you clicked button2");
}
}
/*
<applet code = "ButtonListener.class" width="600" height = "600">
</applet>
*/
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class RadioButtons extends Applet implements ActionListener
Frames :
Applets are designed to embed with HTML pages and these can be run by Browser
Interpreter.
Frames are designed to implements Standalong GUI java applications run by JVM directly.
main() is allowed while implementing Frames.
import java.applet.Applet;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends Frame implements ActionListener
{
Label l1,l2,l3,l4;
Button b1,b2,b3,b4,b5;
TextField t1,t2,t3;
public Calculator(){
setLayout(null);
setSize(600,600);
l1 = new Label("Enter no1 : ");
l2 = new Label("Enter no2 : ");
l3 = new Label("Result : ");
l4 = new Label("");
b1 = new Button("ADD");
By Srinivas (C/DS/Java trainer) Page 293
b2 = new Button("SUB");
b3 = new Button("MUL");
b4 = new Button("DIV");
b5 = new Button("EXIT");
l1.setBounds(100,100,150,50);
t1.setBounds(350,100,150,50);
l2.setBounds(100,200,150,50);
t2.setBounds(350,200,150,50);
l3.setBounds(100,300,150,50);
t3.setBounds(350,300,150,50);
l4.setBounds(150,50,200,50);
b1.setBounds(100,400,100,50);
b2.setBounds(220,400,100,50);
b3.setBounds(340,400,100,50);
b4.setBounds(460,400,100,50);
b5.setBounds(250,475,150,50);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(l4);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource() == b5){
System.exit(1);
By Srinivas (C/DS/Java trainer) Page 294
}
try{
int a,b,c;
String s1 = t1.getText();
String s2 = t2.getText();
a= Integer.parseInt(s1.trim());
b= Integer.parseInt(s2.trim());
if(ae.getSource() == b1){
c = a+b ;
String res = Integer.toString(c);
t3.setText(res);
}
else if(ae.getSource() == b2){
c = a-b ;
String res = Integer.toString(c);
t3.setText(res);
}
else if(ae.getSource() == b3){
c = a*b ;
String res = Integer.toString(c);
t3.setText(res);
}
else if(ae.getSource() == b4){
c = a/b ;
String res = Integer.toString(c);
t3.setText(res);
}
}
catch (Exception e){
l4.setText("Error Info : "+e.getMessage());
}
}
Swing components are platform independant, because the complete logic developed using
java language only.
Swing components are called Light weight(pure java) components.
package online;
import javax.swing.JFrame;
public class FirstFrame extends JFrame
{
public static void main(String[] args)
{
new FirstFrame();
}
}
By Srinivas (C/DS/Java trainer) Page 296
package online;
import javax.swing.JFrame;
public class FirstFrame extends JFrame
{
FirstFrame()
{
this.setSize(600, 400);
this.setTitle("First Frame");
this.setVisible(true);
}
public static void main(String[] args)
{
new FirstFrame();
}
}
package online;
import javax.swing.JButton;
import javax.swing.JFrame;
public class FirstFrame extends JFrame
{
JButton b ; //instance variable
FirstFrame()
{
this.setSize(600, 400);
this.setTitle("First Frame");
package online;
By Srinivas (C/DS/Java trainer) Page 297
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class FirstFrame extends JFrame
{
JButton b ; //instance variable
FirstFrame()
{
this.setSize(600, 400);
this.setTitle("First Frame");
this.setLayout(new FlowLayout());
package online;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class FirstFrame extends JFrame
{
JButton b1, b2 ;
FirstFrame()
{
this.setSize(600, 400);
this.setTitle("First Frame");
this.setLayout(null);
b1.setBounds(150,150,150,50);
b2.setBounds(300,150,150,50);
this.add(b1);
this.add(b2);
this.setVisible(true);
}
public static void main(String[] args)
{
new FirstFrame();
}
}
import javax.swing.JButton;
import javax.swing.JFrame;
public class FirstFrame extends JFrame implements ActionListener
{
JButton b1, b2 ;
FirstFrame()
{
this.setSize(600, 400);
this.setTitle("First Frame");
this.setLayout(null);
b1.setBounds(150,150,150,50);
b2.setBounds(300,150,150,50);
b1.addActionListener(this);
b2.addActionListener(this);
this.add(b1);
this.add(b2);
this.setVisible(true);
}
public static void main(String[] args)
{
new FirstFrame();
}
import javax.swing.JButton;
import javax.swing.JFrame;
public class FirstFrame extends JFrame
{
JButton b1, b2 ;
FirstFrame()
{
this.setSize(600, 400);
this.setTitle("First Frame");
this.setLayout(null);
b1.setBounds(150,150,150,50);
b2.setBounds(300,150,150,50);
b1.addActionListener(new Button1Inner());
b2.addActionListener(new Button2Inner());
this.add(b1);
this.add(b2);
this.setVisible(true);
}
public static void main(String[] args)
{
new FirstFrame();
}
import javax.swing.JButton;
import javax.swing.JFrame;
public class FirstFrame extends JFrame
{
JButton b1, b2 ;
FirstFrame()
{
this.setSize(600, 400);
this.setTitle("First Frame");
this.setLayout(null);
this.setVisible(true);
}
public static void main(String[] args)
{
By Srinivas (C/DS/Java trainer) Page 302
new FirstFrame();
}
}
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class FirstFrame extends JFrame
{
JComboBox jc ;
FirstFrame()
{
this.setSize(600, 400);
this.setTitle("First Frame");
this.setLayout(null);
jc = new JComboBox();
jc.setFont(new Font("Arial", Font.BOLD , 30));
String s[] = {"One", "Two", "Three", "Four"};
for(int i=0 ; i<s.length ; i++)
{
jc.addItem(s[i]);
}
jc.setBounds(200,150,200,50);
this.add(jc);
jc.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String item = (String) jc.getSelectedItem();
System.out.println("Selected item : "+item);
}
}
);
this.setVisible(true);
}
public static void main(String[] args)
{
new FirstFrame();
}
package online;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class FirstFrame extends JFrame
{
JLabel l1 , l2;
JTextField t1 ;
JButton b1 ;
FirstFrame()
{
this.setSize(1000, 500);
this.setTitle("First Frame");
this.setLayout(null);
t1 = new JTextField();
t1.setFont(new Font("Arial", Font.BOLD , 35));
t1.setForeground(Color.BLUE);
t1.setBounds(350,70,400,50);
this.add(t1);
b1 = new JButton("Print");
b1.setFont(new Font("Arial", Font.BOLD , 25));
b1.setBounds(800,75,100,40);
this.add(b1);
l2 = new JLabel();
l2.setFont(new Font("Arial", Font.BOLD , 40));
l2.setBounds(100,250,700,50);
l2.setForeground(Color.RED);
this.add(l2);
this.setVisible(true);
}
public static void main(String[] args)
{
new FirstFrame();
}
}
setLayout(null);
b1=new JButton("PREVIOUS");
this.add(b1);
b1.setBounds(220,250,150,50);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
By Srinivas (C/DS/Java trainer) Page 305
this.dispose();
new First("FIRST FRAME");
}
imp.add(newsf);
imp.add(bookm);
imp.add(mail);
fileExit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
file.add(fileNew);
file.add(fileOpen);
file.add(fileSave);
file.addSeparator();
file.add(imp);
file.addSeparator();
file.add(fileExit);
menubar.add(file);
setJMenuBar(menubar);
setTitle("Submenu");
setSize(600,600);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
Port :
Every computer which is connected in the network has a single physical connection.
All data destined for a particular computer will be collected through that connection call
Socket.
Question: How does the computer knows, to which application it has to forward the data that is
collected through Socket?
In one computer, we can run number of applications simultaneously.
Each application should run at a specific port number.
Hence OS can identify the application by its port number to send the collected through single
physical connection (Socket).
A 16-bit computer is having 2^16 (65536) ports to run applications.
Port numbers ranging from 0-1023 are restricted, these ports always used by well known
system applications.
IP address
An Internet Protocol address (IP address) is a numerical label assigned to each device which
is connected in the network.
Using IP address only, it is possible to send the information to a specific system connected
in Network.
IP address having 2 versions
Internet Protocol Version 4 (IPv4)
Internet Protocol Version6 (IPv6)
URL:
Stands for Uniform Resource Locator.
It is a reference (an address) to a resource(application) on the Internet.
A URL has two main components:
For example :
http://www.google.com
Protocol identifier: http://
Resource name: www.google.com
import java.net.*;
import java.io.*;
public class ParseURL
{
public static void main(String[] args) throws Exception
{
URL aURL = new
URL("http://localhost:8086/RequestApp/go?userName=naresh&userPass=srinivas");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
System.out.println("filename = " + aURL.getFile());
}
}
Find IP address: Every system it is connected in the network can be recognized by a unique address
and can send the information using Socket connection.
import java.net.*;
import java.io.*;
public class IP
{
public static void main (String[] args) throws IOException
{
if(args.length == 0)
{
System.out.println("Input host name");
}
else
{
String host = args[0];
try
{
InetAddress ip = InetAddress.getByName(host);
System.out.println("IP address: " + ip.getHostAddress());
}
catch ( UnknownHostException e )
{
System.out.println("Could not find IP address for: " + host);
}
}
}
}
Socket Overview
A socket forms the interface between the protocol and client for communication.
A Java socket forms the base for data transmission between two computers using TCP/IP.
The socket specifies the site address and the connection port.
When packets reach a client or server, they are routed to the destination port specified in
packet header.
java.net Package
The java.net package contains the classes and interfaces required for networking.
Some important classes are
1. MulticastSocket,
import java.io.*;
import java.net.*;
public class ExSocket
{
public static void main(String args[]) throws UnknownHostException
{
try
{
Socket mySocket = new Socket("www.google.com",80);
System.out.println("Connection to: " + mySocket.getInetAddress());
System.out.println("Port Number: " + mySocket.getPort());
System.out.println("Local Address: " + mySocket.getLocalAddress());
System.out.println("Local Port: " + mySocket.getLocalPort());
}
catch (UnknownHostException e)
{
System.out.println("Site not found!");
}
catch (SocketException e)
{
System.out.println("Socket error");
}
catch ( IOException e)
{
System.out.println("An I/O Exception Occurred!");
}
}
}
import java.io.*;
import java.net.*;
public class SerSocket
{
public static void main(String args[])
{
int port=1080;
try
{
ServerSocket mySocket = new ServerSocket(port);
System.out.println("Server initialized on port " + port);
mySocket.getLocalPort();
{
while(true)
{
mySocket.accept();
}
}
}
catch (Exception e)
{
System.out.println("Exception : "+e.getMessage());
}
}
}
A CHAT PROGRAM
CLIENT SIDE CODE:
import java.net.*;
import java.io.*;
class ClientChild implements Runnable
{
Thread t;
Socket client;
ClientChild(Socket client)
{
this.client=client;
t=new Thread(this);
t.start();
}
public void run()
{
try