Anda di halaman 1dari 43

Java Important Concept

Author(s):

Dayanithi J

Date written: 06/03/2009


Declaration
I hereby declare that this document is based on my personal experiences. To the
best of my knowledge, this document does not contain any material that infringes
the copyrights of any other individual or organization including the customers of
Infosys.
Target readers -

Java Learner

Keywords
Java, Basic, Static, Final, Exception, Interface, Inheritance, Class, Overloading,
Overriding, Dynamic Binding
Pre-requisites Elementary Java Knowledge
Introduction
This document helps you to understand the basic concept in java.
The coding snippet gives you the brief introduction about the topic.
Appropriate Error messages are description in the right side of the each code
snippet.
The Blue color indicates the keywords In Java. The Green color on the right
side indicates the Valid program. The Red color on the right side indicates the
Invalid or Error.
Index
1.
Typecasting
2.
Array
3.
Class
4.
This Keyword
5.
Constructor
6.
Method Overloading
7.
Memory Allocation
8.
Null
9.
Array of Objects
10. Static
i. Static Variable
ii. Static Method
iii. Static Block
11. String in Java
12. Relationship

13. Inheritance
14. Method Overriding
15. Dynamic Binding
16. Runtime Polymorphism
17. Abstract Class
18. Final
i. Final variable
ii. Final method
iii. Final Class
19. Interface
20. Package
21. Autobox / unbox
22. Exception
i. Try & catch block
ii. Finally block
iii. Throw
iv. Throws
23. Generic
24. == Vs .equal()
25. File Handling
Typecasting
float j,l=9;
j = (float)l;

Valid

float j,l=9;
j = float(l);

Invalid

Array
All arrays are created dynamically
new int[5] - It creates an array of 5 integers and returns a reference to the newly
created array
1) By default Array instance will be set to 0.
2) Local variable can not be used without initialized
3) While declaring Array types, The Value won't come in the left side.
int i[9];

Invalid

4) The number of elements in each row (dimension) need not be equal


int[][] irregular = { { 1 },

{ 2, 3, 4 },
{ 5 },
{ 6, 7 } };

Valid

System.out.println(irregular[2]);

Valid(It print Address)

int i[] = { 4, 5, 2, 7 };

Valid

int []i = new int[10];

Valid

int i[][] = { { 5, 4 }, { 3,5 } };

Valid

int i[][] = { { 5, 4 }, { 3 } };

Valid

int d[][] = new int[4][];

Valid

int d[][] = new int[][7];

InValid(column is must)

int i[][4] = { { 5, 4 }, { 3,5 } }; -

Invalid(Left side
number should not

come)
int i[] = new int[];

InValid(Unknown size of
object)

int a[][] = new int[3][];


System.out.println(a[0]);

Output: null

Class
1. All the data members, members are set to default access specifiers.
2. By Default, The data memebers of classes are assigned as shown below
i. numeric data types are set to 0
ii. char data types are set to null character(\0)
iii. boolean data types are set to false
iv. reference variables are set to null
3. The variable, methods, class with default access specifierss can be used in all
the classes of the same package
4. Classes and Interfaces can have either the public access or the default access
Example 1:
class Parent
{
int i;
}
public class Program
{
public static void main(String args[])
{
Parent p = new Parent();

System.out .println(p.i);

//Variable i can be accessed here

}
}
Output:
0
This Keyword
class Parent
{
int i;
int geti()
{
System.out.println(i);
return i;
}
void seti(int i)
{
i = i;
System.out.println(i);
}
}

//If this keyword not use here then,


//the value not set properly.
//So, this.i=i; is correct to change i

public class Program


{
public static void main(String[] args)
{
Parent p = new Parent();
p.seti(99);
System.out.println(p.geti());
}
}
Output:
99
0
0
Constructor
1. It is optional to define constructor
2. If a user defined constructor is available, it is called just after the memory is
allocated for the object
3. Constructor will have same name as that of class name
4. Constructor will not have any return type (void, int etc...)
5. In Inheritance, The Parent constructor is executed first
6. Parent constructor is executed before child constructor execution

7. The Super keyword is used to override the Parent constructor. Super


Keyword should be used at first line
8. Constructor can not be a static, abstract or final

Example 1:
/*to describe: The Super keyword is used to override the Parent constructor. Super
Keyword should be used at first line*/
class Parent
{
Parent()
{
System.out.println("Parent's Default constructor");
}
Parent(int i)
{
System.out.println("Parameterized constructor");
}
}
class Child extends Parent
{
Child()
{
super(9);
//Should be used at first line
System.out.println("Child's Default constructor");
}
}
public class Program extends Parent
{
public static void main(String[] args)
{
Child p = new Child();
}
}
Output:
Parameterized constructor
Child's Default constructor
Method Overloading

Two or more methods in a Java class can have the same name, if their
argument lists are different

Argument list could differ in


No of parameters
Data type of parameters
Sequence of parameters

Example 1:
public class Program
{
int Add(int i, int j)
{
return i+j;
}
float Add(int i, int j, int k)
{
return i + j + k;
}

Valid

public static void main(String[] args)


{
Program p = new Program();
System.out.println(p.Add(6, 7));
System.out.println(p.Add(5,6,7));
}

The Method overloading considers only the arguments.


Example 2:
public class Program
{
int Add(int i, int j)
{
return i+j;
}
void Add(int i, int j, int k)
{
System.out.println (i + j + k);
}

Valid

public static void main(String[] args)


{
Program p = new Program();
System.out.println(p.Add(6, 7));
p.Add(5,6,7);
}
}

when
when
when
when
when

passing
passing
passing
passing
passing

int
->
char
->
float ->
String ->
double ->

if
if
if
if
if

no
no
no
no
no

int available
->
char available ->
float available ->
String available ->
double available ->

then float will take


then float will take
then double will take
Error
Error

Hierachy of automatic conversion


char(1)->

int(2)->

float(3)->

double(4)->

X(nothing)

String -> X(nothing)


Memory Allocation
Stack
Heap

Local variable
All dynamically allocated arrays
Dynamically allocated objects
Data members of the class

If null is assigned to any reference, then the Garbage collector can dereference the
object if memory allocation is needed more.
If a reference variable is Declared Within a function, the reference is invalidated as
soon as the function call ends
Example 1:
public class Program
{
private int i;
void editObj()
{
Program p = new Program();
p.i = 100;
}
void seti()
{
i = i + 5;
}
void displayi()
{
System.out.println(i);
}
public static void main(String[] args)
{
Program p = new Program();
p.i = 5;
p.editObj();
p.seti();
p.displayi();
}

}
Output:
10

//Object p destroyed when


//this function is over

Null
String str = null;
int h = null;

Valid
-

Invalid
Because, Primitive types are
not objects and they cannot
be assigned null

Array of Objects
PolicyHolder [] policyHolder = new PolicyHolder[3];
/*3 PolicyHolder references policyHolder[0], policyHolder[1] and policyHolder[2]
are created and all 3 references are null*/
public class Child
{
int i;
public static void main(String args[]) throws Exception
{
try
{
Child d[] = new Child[5];
System.out.print(d[0].i);
//Exception Arise
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Output:
Java.lang.NullPointerException
Example 2:
To avoid NullPointerException, we need to create object for each reference by using
new Keyword.
public class Child
{
int i;
public static void main(String args[]) throws Exception
{
try
{
Child d[] = new Child[5];
for (int i = 0; i < d.length; i++)
d[i] = new Child();
//Allocate memory
for (int i = 0; i < d.length; i++)

System.out.print(d[i].i+ " ");


}
catch (Exception e)
{
System.out.println(e);
}
}
}
Output:
00000
Static
The static

keyword can be used in 3 scenarios:


For class variables
For methods
For a block of code

Static Data Member in class

1. Static data is initialized to zero


2. Static variable instantiated only once
3. Static data is a data that is common to the entire class

Static data is a data that is common to the entire class


public class Program
{
static int count;
Program()
{
count++;
}
public static void main(String args[]) throws Exception
{
Program p[] = new Program[10];
for(int i=0; i<p.length ;i++)
p[i]=new Program();

}
}

for (int i = 0; i < p.length; i++)


System.out.print(p[i].count + " "); //For all object the
// the static variables
//data remain same

Output:
10 10 10 10 10 10 10 10 10 10

The count variables value for all the objects to particular class is 10. Because static
variable instantiated only once.
Static Method

1. static method is a method that is common to the entire class. So we can call it
without creating object.
2. static method can access only static method and static data member. But as
many as normal local variable can be declared inside the static method.
3. Constructor method can not be a static
4. static method can not use super or this keyword
5. static method can have private, public access specifiers
6. static method can not have static variable declartion.

Explanation 1:
static method is a method that is common to the entire class. So we can call it
without creating object
public class Program
{
static int count;
int i;
Program()
{
count++;
}
private static void display() //private access specifier can also work
{
System.out.println(count);
}
public static void main(String args[]) throws Exception
{
//Invoking the Static method without object
Program.display();
//Even Constructor also not working here
}
}
Output:

0
Explanation 2:
static method can access only static method and static data member. But as many
as normal local variable can be declared inside the static method.
public class Program
{
static int count;
int i;
Program()
{
count++;
}
public void showi()
{
System.out.println(i);
}
static void showcount()
{
System.out.println(count);
}
static void display()
{
showcount();
showi();
//Error
System.out.println(i);
//Error
}
public static void main(String args[]) throws Exception
{
//Invoking the Static method without object
Program.display();
}
}
Output:
Program.java:20:non-static method showi() cannot be referenced from a static
context
showi();
^
Program.java:21: non-static variable i cannot be referenced from a static context
System.out.println(i);
^
Explanation 3:
Constructor method can not be a static
public class Program

static Program()
{

//Error

}
public static void main(String args[]) throws Exception
{
}

Program.java:3: modifier static not allowed here


static Program()
^
1 error
Explanation: 4
static method can not use super or this keyword
class Parent
{
Parent()
{
System.out.println("Parent's Constructor");
}
}
public class Program
{
int count;
static
{
super();
//Error
this.count =9;
//Error
System.out.println("Static block invoked");
}
Program()
{
System.out.println("Constructor is invoked");
}
public static void main(String args[]) throws Exception
{
Program p = new Program();
}

Program.java:15: call to super must be first statement in constructor


super();
^

Program.java:16: non-static variable this cannot be referenced from a static con


text
this.count =9;
^
2 errors
Explanation 6:
6. static method can not have static variable declartion.
public class Child extends Parent
{
public static void main(String args[]) throws Exception
{
static int i=9;
//Error
}
}
Static Block

1. The static block is a block of statement inside a Java class that will be executed
when a class is first loaded
2. The static block have more priority than constructor. Because, constructor
invoked when object is created. But static is invoked when class is loaded.
3. The static block always executed only once.

Explanation 1:
The static block is a block of statement inside a Java class that will be executed
when a class is first loaded
public class Program
{
static
{
System.out.println("Static block invoked");
}
Program()
{
System.out.println("Constructor is invoked");
}
public static void main(String args[]) throws Exception
{
}
}

Output:
Static block invoked
Explanation 2:
The static block have more priority than constructor. Because, constructor invoked
when object is created. But static is invoked when class is loaded
public class Program
{
static
{
System.out.println("Static block invoked");
}
Program()
{
System.out.println("Constructor is invoked");
}
public static void main(String args[]) throws Exception
{
Program p = new Program();
}
}
Output:
Static block invoked
Constructor is invoked
Strings in java

String is a system defined class in Java


Declaring Hello World in code will create an object of type string with data Hello
World and returns a reference to it.
String rules
1.
2.
3.
4.
5.
6.

Prevents buffer overruns


null terminator not used in strings
String is not a simple array of characters
String is immutable(value cant be changed)
String object can be created without new object
String is not primitive

Relationship

There are 3 types of relationships

Has-A (or Part-Of)


Car has an Engine
Uses-A
Driver uses a Car
Is-A (or Kind-Of)
Trainee is an Employee

Has A
Has-A relationship occurs when a class contains another class as one of its member
Has-A relationship is represented with a diamond headed line in UML

class Engine
{
String Horsepower;
String model;
}
public class Car
{
Engine eng;
String color;
double price;

//Car class have Engines reference

public static void main(String args[])


{
}
}
Uses A
Uses-A relationship occurs when one class interacts with another
Loosely coupled relationship

A method of a class creates an object of the other class


A method of a class invokes the method on an object of the other class
class Car
{
String Horsepower;
String model;
}
public class Driver
{
public static void main(String args[])
{
Car santro = new Car();
Car maruthi = new Car(); //Driver class using Car Object

}
}
Is A ( also known as inheritance)
Is-A Relationship or Inheritance occurs when a class is similar to another class
A class is a different type of another class
Inheritance is represented by a triangle head arrow in UML Class diagrams
Inheritance
1. It is used to acquire the property of another class (i.e. super class)
2. extends keywords is used to inherit the other class
3. Inheritance leads to code re-usability
4. Parent class is also known as super class
5. Child class is also known as sub class, derived class
6. Doesnt support multiple inheritance of class
7. The parent constructor is executed before child constructor executed.

Method Overriding
1. Redefining a base class method in a sub class is called method overriding
2. An overriding method can call an overridden method using the syntax
super.methodName()
3. Always the child class method will be invokded

//Example for Method Overriding


class Parent
{
void display()
{
System.out.println("Parent's Display method");
}
}

public class Program extends Parent


{
void display(int i)
{
System.out.println("Child's Display method");
}
public static void main(String args[]) throws Exception
{
Program c = new Program();
c.display();
//Parent class display method is
}
//overridden here
}

Dynamic Binding

1. A reference to a super class can refer to a sub class object


Example: Parent parentreference = new ChildClass ()
2. Dynamic binding is the practice of figuring out which method to invoke at
Runtime
3. Methods that are newly declared in the sub classes cannot be accessed
Using this reference
4. Static method can be hidden. And it cant be overridden

class Parent
{
void display()
{
System.out.println("Parent's Display method");
}
}
public class Child extends Parent
{
void display()
{
System.out.println("Child's Display method");
}
public static void main(String args[]) throws Exception
{

Parent p = new Child();


p.display();
}
method
}
reference

//Parents reference is pointed to


//child object
//Now JVM will invoke the
//based on object not by
//This is called dynamic binding

Output:
Childs Display Method
Explanation 3:
3. Methods that are newly declared in the sub classes cannot be accessed
Using this reference

class Parent
{
void display()
{
System.out.println("Parent's Display method");
}
}
public class Child extends Parent
{
void display()
{
System.out.println("Child's Display method");
}
void show()
{
System.out.println("Child's show method");
}
public static void main(String args[])
{
Parent p = new Child();
p.show();
//Error. Since parent class does not
}
//have show() method. We can not overide it
}
Output:
Child.java:23: cannot find symbol
Symbol: method show ()
Location: class Parent
p.show();
^

1 error
Runtime Polymorphism

1. sub class's reference can be assigned to super class address but not vice versa.
2. To do that we have to type cast the reference of the sub class in reference of the
super
3. If arugment vary in the same function name, it wont work. But if we use Object
Argument, it works. Because Object class is a super class of all datatype.

Example 1:
class A
{
void add()
{
System.out.println("A's Add Method");
}
}
class B extends A
{
void add()
{
System.out.println("B's Add Method");
}
}
class AB
{
public static void main(String s[])
{
A ob1;
ob1 = new A();
ob1.add();//will call the method of super class.
ob1 = new B();// sub class's reference can be assigned to super
class address but not vice versa.to do that we
have to type cast the reference of the sub class
in reference of the super class.
ob1.add();//will call the method of sub class
}

Example 2:

3. If arugment vary in the same function name, It will always call the parents
method.

class A
{
void add(String s)
{
System.out.println("A's Add Method");
}
}
class B extends A
{
void add(Object obj)
{
System.out.println("B's Add Method");
}
}
class AB
{
public static void main(String s[])
{
A ob1;
ob1 = new A();
ob1.add("Hello");//will call the method of super class.
ob1 = new B();
ob1.add("Hello");//will call the method of super class not sub class
}

Output:
As Add method
As Add method

Static
Function Overloading - More than one
method having same name but
differing in argument list
Resolved during compilation time

Dynamic

Function Overriding - keeping


signature and return type sam
method in the base class is red
in the derived class
Resolved during run time
Which method to be invoked is
decided by the object that the
reference points to and not by
type of the reference

Abstract Class

1. Abstract classes cannot be instantiated


They are used as base classes for other classes
2. Subclasses that extend an abstract class need to provide implementation
of all the abstract methods of the base class or declare the subclass
also as abstract
3. Abstract method cannot be defined in the abstract class. Only declaration should
be made
4. The following cannot be abstract
Constructors
static methods
private methods
final

Example 1:
1. Abstract classes cannot be instantiated
They are used as base classes for other classes

abstract class Parent


{
void display() //Concrete Method
{
}
}
public class Child
{
public static void main(String args[]) throws Exception
{
Parent p = new Parent();
//Error
}
}
Output:
Child.java:14: Parent is abstract; cannot be instantiated
Parent p = new Parent ();
//Error
^
1 error
Example 2:

Subclasses that extend an abstract class need to provide implementation of all the
abstract methods of the base class or declare the subclass also as abstract

abstract class Parent


{
abstract void display();
}
public class Child extends Parent
{
void display() //Abstract method need to be implemented, else error
{
System.out.println("Abstract class method display()'s definiton");
}
public static void main(String args[]) throws Exception
{
Child c = new Child();
c.display();
}
}
Output:
Abstract class method display ()s definition

Example 3:
3. Abstract method cannot be defined in the abstract class. Only declaration should
be made
abstract class Parent
{
abstract void display()
{
System.out.println("Abstract class method display()'s definiton");
//Error
}
}
public class Child extends Parent
{
void display()
{
System.out.println("Abstract class method display()'s definiton");
}
public static void main(String args[]) throws Exception
{
}

Output:
Child.java:14: Parent is abstract; cannot be instantiated
Parent p = new Parent();
//Error
^
1 error

Final

1. To declare constant variable


Final keyword need not be initialized.
2. To prevent overriding (cannot be overridden by the sub classes)
3. To prevent inheritance (cant be extended)
4. final keyword can declared as static
5. reference variable can be final

Explanation 1:
To declare constant variable
When Final keyword need not be initialized
public class Child
{
public static void main(String args[]) throws Exception
{
final int i;
//Need not be initialised

i = 10;

//If not initialised, first time can be


modified

i = 11;

//Error, Can't be changed second time

}
Child.java:9: variable i might already have been assigned
i = 11;
^
1 error
Explanation: 2
2. To prevent overriding
class Parent

final void display()


//final member function
{
System.out.println("Parent's Display Method");
}

public class Child extends Parent


{
void display()
//Error . Since, it cannt be override
{
System.out.println("Child's Display Method");
}
public static void main(String args[]) throws Exception
{
Child c = new Child();
c.display();
}
}
Output:
Child.java:12: display () in Child cannot override display () in Parent;
overridden method is final
void display ()
//Error
^
1 error
Explanation 3:
3. To prevent inheritance
final class Parent
{
void display()
{
System.out.println("Parent's Display Method");
}
}
public class Child extends Parent
//Error. Final class cannt be inherit
{
void display()
{
System.out.println("Child's Display Method");
}
public static void main(String args[]) throws Exception
{
Child c = new Child();

c.display();

}
Output:
Child.java:10: cannot inherit from final Parent
public class Child extends Parent
^
1 error
Interface

1. Interface is implements to class using implements keyword


2. Using interface we can specify what the class must do, but not how it does it
3. All members of an interface are public.
4. All methods of an interface are abstract and the keyword abstract need not (and
should not) be used. And not static
5. It is mandatory for the concrete classes that implement an interface to
implement all the methods declared in the interface
6. Interface can be extended
7. Partial Implementation if a class includes an interface but does not fully
implement the methods defined by that interface, then the class must be declared
as abstract
8. protected , private not allowed here
9. Classes and Interfaces can have either the public access or the default access

Explanation 1:
1. Interface is implements to class using implements keyword
interface A
{
void display();
}

//By default it is public and abstract

public class Child implements A


//Interface implements here
{
public void display()
//It should be defined public here
{
System.out.println("Child's Display Method");

}
public static void main(String args[]) throws Exception
{
Child c = new Child();
c.display();
}

}
Output:
Childs Display Method
Explanation 2:

Possible error in interface


interface A
{
private void display();
void show();
void get()
defined
{
}

//Error. Private cannt be used


//Error. Body definition cannot be

public class Child implements A


{
void display()
//Error. It should be declared as public
{
System.out.println("Child's Display Method");
}
//Error. show () has to be defined.
Since not defined. It is error
public static void main(String args[]) throws Exception
{
Child c = new Child();
c.display();
A a = new A();
//Error. Object cant be instantiated
//for interface
}
}
Output:
Child.java:3: modifier private not allowed here
private void display();
//By default it is public and abstract
^
Child.java:8: Child is not abstract and does not override abstract method show()
in A
public class Child implements A
^
Child.java:10: display() in Child cannot implement display() in A; attempting to
assign weaker access privileges; was public

void display()
^
Child.java:20: A is abstract; cannot be instantiated
A a= new A();
^
4 errors
Explanation 3:
7. Partial Implementation if a class includes an interface but does not fully
implement the methods defined by that interface, then the class must be declared
as abstract
abstract interface A
{
void display();
void show();
}
abstract class B implements A
{
public void display()
//Partial implementation
{
System.out.println("Interface A's method");
}
//show method is not defined in this
}
//class
public class Child extends B
{
public void show()
//show method has to defined here
{
//since this class is not abstract
System.out.println("Interface A's method");
}
public static void main(String args[]) throws Exception
{
}

Variable in Interface

1. By default it is public, final and static


2. Need to be assigned

Explanation 1:

interface A
{
int a=10;
int b=5;
}

//By default it is public, final and static


//Need to be assigned

public class Child implements A


{
public static void main(String args[]) throws Exception
{
System.out.println(a);
}
}
Output:
10
Explanation 2:
Possible error in Interface variable
interface A
{
int a=10;
//By default it is public, final and static
int b;
//Error. Need to be assigned
}
public class Child implements A
{
public static void main(String args[]) throws Exception
{
a = 10;
//Error. cant be changed since it is final
System.out.println(a);
}
}
Output:
Child.java:4: = expected
int b;
^
Child.java:12: cannot assign a value to final variable a
a = 10;
^
2 error

Explanation : 4
6. Interface can be extended
interface A
{

int a=10;
int b=5;

//By default it is public, final and static


//Need to be assigned

}
interface B extends A
//Interface can inherit another interface
{
int c = 1;
}
public class Child implements B
{
public static void main(String args[]) throws Exception
{
System.out.println(a);
//variable a can be called with
}
//intialization since it is static
}
Output:
10

Abstract Classes
Can have concrete methods
Can have variables
Can have private and protected
members
Can be extended from one class
A class can extend only one abstract
class

Interfaces
Can have only abstract methods
Can have only static final (constant)
data members
All members are public by default
Can be extended from any number of
interfaces
A class can implement any number of
interfaces

Packages
A package is a collection of related classes and interfaces in Java
The package statement, if existing, should be the very first statement of the file
Packages prevent the clash of class/interface names by putting in different
subclasses

Step 1: //Create a Package file


package world;
public class Infy
{
void display()
{
System.out.println("Package example");
}
}
Step 2: //to create a package folder
Go to command prompt
Navigate to the where package file is saved.
javac d .\ Infy.java
Verify whether folder is created or not.
Step 3:
import world.*;
public class HelloWorld extends Infy
{
public static void main(String[] args)
{
System.out.println("Hello World");
world.Infy f = new world.Infy();
f.display();
}
}
Step 4:
Save and execute it.
Autoboxing / Unboxing

class AutoBox
{
public static void main(String args[])
{
Integer iOb = 100; // autobox an int
int i = iOb; // auto-unbox
}

System.out.println(i + " " + iOb); // displays 100 100

}
Autoboxing
Unboxing

Primitive to Wrapper
Wrapper to Primitive

Wrapper classes for the primitive types

Wrapped Class: boolean, int, long


public class WrappedClassApp
{
public static void main(String args[])
{
Boolean b1 = new Boolean("TRUE");
Boolean b2 = new Boolean("FALSE");
System.out.println(b1.toString() + " or " + b2.toString());
for (int j = 0; j < 16; ++j)
System.out.print(Character.forDigit(j, 16));
System.out.println();
Integer i = new Integer(Integer.parseInt("ef", 16));
Long l = new Long(Long.parseLong("abcd", 16));
long m = l.longValue() * i.longValue();
System.out.println(Long.toString(m, 8));
Basic Type
byte
short
int
long
float
double
boolean
char

Wrapper Class
Byte
Short
Integer
Long
Float
Double
Boolean
Character

System.out.println(Float.MIN_VALUE);
System.out.println(Double.MAX_VALUE
);

Output:
true or false
0123456789abcdef
50062143
1.4E-45
1.7976931348623157E308
StringBuffer ()
public class StringBufferDemo
{
public static void main(String[] args)
{
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer= " + sb);
System.out.println("length= " + sb.length());
System.out.println("capacity= " + sb.capacity());

//appending and inserting into StringBuffer.


String s;
int a = 42;
StringBuffer sb1 = new StringBuffer(40);
s = sb1.append("a=").append(a).append("!").toString();
System.out.println(s);
StringBuffer sb2 = new StringBuffer("I JAVA!");
sb2.insert(2, "LIKE");
System.out.println(sb2);

}
Output:
buffer= Hi Rohit
length= 8
capacity= 24
a=42!
I LIKEJAVA!
Difference between StringBuilder and StringBuffer
First tell me what is the best way to concatenate large number of String objects? Is
it a + b?
Most Java developers know not to use a + b (+ operator) because of huge
performance problems, they use StringBuffer instead. In fact I did some tests in
the past which confirms this folklore. However some of you may not know there is
new kid on the block - StringBuilder.

java.lang.StringBuilder is java.lang.StringBuffers cousin (like java.util.HashMap is


to java.util.Hashtable or java.util.HashSet is to java.util.Vector) but without the
synchronization overhead. Unless you need to concatenate a String from multiple
Threads, you are likely to get better performance with StringBuilder.
Exception

An Exception occurs during the execution of a program and disrupts the normal
flow of instructions
When an exception is to be thrown in a Java program, Java cannot throw any
object, it can throw only Throwable objects
Hierarchy of Exception class

Try, catch & Finally Block


1. try block should be followed be either finally or catch block. After the
declaration of finally block catch block should not come.
2. finally block will always executed once even if exception is not caught
3. There should be only one finally
4. There may be more than one catch Block
5. Checked Exception is an exception which is identified by the compile and return

error if try-catch block is not included.


Example: opening file
6. Nested try block is possible
7. When using multiple catch block statements, it is important to remember that
exception subclasses must come before any of their superclasses.

Explanation 1:
Possible error in try catch block
public class HelloWorld
{
public static void main(String[] args)
{
try
{
System.out.println(6 / 6);
}
finally
{
System.out.println("Finally block");
}
catch(Excetpion e)
//Error: The catch block should be
//immedietly followed by try
block
{
System.out.println ("Exception occur");
}
}
}
Error #2:
public class HelloWorld
{
public static void main(String[] args)
{
try
{
System.out.println(6 / 6);
}
finally
{
System.out.println("Finally block");
}
finally //Error: There should be only one finally block
{
System.out.println("Second finally block);
}

}
}
Error #3:
public class HelloWorld
{
public static void main(String[] args)
{
try
{
System.out.println(6 / 6);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
catch (ArithmeticException e)
//Error: This is subclass it
{
//should come first
System.out.println(e.getMessage());
}
}
}
Output:
HelloWorld.java:14: exception java.lang.ArithmeticException has already been
caught
catch (ArithmeticException e)
^
1 error

Explanation 2:
2. Finally block will always executed even if exception is not caught
public class HelloWorld
{
public static void main(String[] args)
{
try
{
System.out.println(6 / 6);
}
finally

System.out.println("Finally block");

}
}

}
Throw

1. throw keyword used to throw an exception explicitly by a programmer


Example:
public class HelloWorld
{
public static void main(String[] args)
{
try
{
throw new NullPointerException("");
}
catch (NullPointerException e)
{
System.out.println(e.getMessage());
}
catch (ArithmeticException e)
{
System.out.println(e.getMessage());
}
}
}
Throws

1. throws keyword is used to send the exception signal to the calling method.
2. It is must to include the method inside the try catch block, if the methods
declaration has throws exception declaration
Difference between try-catch and throws keyword

try-catch

throws

try-catch block handle the exception


at same level (i.e. when the
exception caught, it handle over
there.)

throws keyword does not handle the


exception, it catch and retrieve the
exception detail and pass it to the
upper level (i.e. calling method.)

Explanation 1:
public class Program
{
void display()
{
System.out.println("Child's Display method");
}
public static void main(String args[]) throws Exception
{
try
{
generateException(); //Exception is handled here
}
catch (Exception e)
{
System.out.println("Hi");
}
}
static void generateException() throws ArithmeticException
{
int i = 9 / 0;
//throws catch the exception here
System.out.println(i);
//and pass the exception to the calling
}
//method(i.e. main())
}
OutPut:
Hi
Explanation 2:
2. It is must to include the method inside the try catch block, if the methods
declaration has throws exception declaration
public class Program
{
void display()
{
System.out.println("Child's Display method");

}
public static void main(String args[]) throws Exception
{
generateException(); //Error Since try-catch block is not there
}
static void generateException() throws ArithmeticException
{
int i = 9 / 0;
System.out.println(i);
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Program.generateException(Program.java:14)
at Program.main(Program.java:9)
Explanation 3:
2. It is not a mandatory to include try catch block in this example, because here we
didnt can the method which throws exception

public class Program


{
public static void main(String args[])
{
Program t = new Program();
System.out.println("Print");
}
public void method() throws Exception
{
throw new Exception();
}
}
Output:
Print
Generic
A class, interface or a method that works on a parameterized type is called
a generic
Generic enable us to create single class that automatically works with
different types of data using parameterized type.
Generic work only with Objects

Generic Types differ based on their type Arguments

Explanation:
class GenericClass <T>
{
T ob;
GenericClass(T ob)
{
System.out.println(ob.getClass().getName());
this.ob=ob;
}
void display()
{
System.out.println(ob);
}
}
public class AB
{
public static void main(String args[])
{
Display<String> d= new Display<String>("Hi");
Display<Integer> d1=new Display<Integer>(9);
}

}
Output:

java.lang.String
Hi
java.lang.Integer
9
== Vs .equal ()
==

equals ()

True

if both References are same, and


Both contents are same.

False

if both References is not same, and


Both contents are same.

It Compare the object first, then the value


If the object is not same then it is error

String is class not primitive

==
Related Primitive and
wrapper object can be
used together
Example:
int i = 9;
Integer j = new
Integer(9);
System.out.println(i ==
j);
Output: true
Different & related
Primitive and wrapper
object can be used
together
float f = 9;
Integer j = new
Integer(9);
System.out.println(f==j);

equals()
Related Primitive and wrapper
Object cant be used together
Example:
int i = 9;
Integer j = new Integer(9);
System.out.println(i.equals(j));
Output: Error

Different & related Primitive


and wrapper Object cannt be
used together
float f = 9;
Integer j = new Integer(9);
System.out.println(f.equals(j));
Output: Error

Output: true
Different wrapper object
cant be used together

Different wrapper object can be


used together

String s = "9";
Integer j = new
Integer(9);
System.out.println(s==j);

String s = "9";
Integer j = new Integer(9);
System.out.println(s.equals
(j));

Output: Error

Output: false

File Handling
FileOutputStream
import java.io.FileOutputStream;
public class FileOutputStreamDemo
{
public static void main(String args[]) throws Exception
{
FileOutputStream fos = new FileOutputStream("Data.txt");
int b1 = -1, b2 = 66, b3 = 67;
fos.write(b1);
fos.write(b2);
fos.write(b3);
fos.close();
}

}
FileInputStream
import java.io.FileInputStream;
public class FileInputStreamDemo
{
public static void main(String args[]) throws Exception
{
FileInputStream fis = new FileInputStream("Data.txt");
//byte b[]=new byte [45];

//System.out.println(fis.read(new byte[890]));
int i = fis.read();
while (i != (-1))
{
System.out.println((byte)i);
i = fis.read();
}
fis.close();
}

BufferOutputStream
The bufferOutputStream uses the buffer first and if the buffer size is full the
content is write into that file.
Lets us see the same content with Three different case
Here Buffer Size : 200
so if the buffer size is fill the data to file
Case 1:
import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
public class BufferedOutputStreamDemo
{
public static void main(String args[]) throws Exception
{
FileOutputStream fos = new FileOutputStream("Buffer.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos, 200);
for (int i = 0; i < 700; i++)
{

bos.write((byte)i);
}

}
Output:
Buffer.txt is created and itss File Size:

600

100 byte is lost because the buffer is not properly committed (i.e. it doesnt use
flush() or close() method)
Case 2:
import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
public class BufferedOutputStreamDemo
{
public static void main(String args[]) throws Exception
{
FileOutputStream fos = new FileOutputStream("Buffer.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos, 200);

for (int i = 0; i < 700; i++)


{
bos.write((byte)i);
bos.flush(); //the buffer is flush. So the
}
//remaining content is written

}
Output:
Buffer.txt is created and itss File Size:

700

100 byte is saved because the buffer is properly committed (i.e. it uses the flush()
method)
Reference:
1.

Java Complete Reference Book