0% found this document useful (0 votes)
21 views

Core Java Part 2

Uploaded by

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

Core Java Part 2

Uploaded by

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

Core Java Part - II

Chapters:
1. Object Oriented Programming
  
Encapsulation (Data hiding & Method abstraction)
  
Inheritance (IS-A Relationship)
  
Polymorphism
  
Method Signature
  
Overloading
  
Overriding
  
Constructors
  
this or super
  
Final & static
  
Abstract class and Interface

2. Exceptions
  
Introduction
  
Exception Hierarchy
  
Exception handling using : try-catch-finally
  
Methods to display error information.
  
Checked and Unchecked exceptions
  
Multiple catch blocks.
  
Nested try blocks
  
User defined exceptions (Customized Exceptions)
  
Throw and Throws

3. Java.lang Package
  
Hierarchy
  
Object class
  
String
  
StringBuffer & StringBuider (Jdk1.5)
  
Wrapper classes
 
Autoboxing and Unboxing (Jdk1.5)

E-Mail: [email protected] Phone: (+91) 9865358359 1


R.ARAVIND

OBJECT ORIENTED PROGRAMMING


  Encapsulation (Data hiding & Method abstraction)
  
Inheritance (IS-A Relationship)
 
 Polymorphism
 Method Signature
 Overloading
 Overriding
  Constructors

  
this or super
  
Final & static
  
Abstract
 
Interface

Encapsulation
Data hiding
One of the sound object-oriented programming techniques is hiding the data within the class by declaring
them with private accessibility modifier. Making such variables available outside the class through public setter
and getter methods. Data hiding says “restrict access and modification of internal data items through the use
of getter and setter methods”.
Example:
public class Authentication{
//Data hiding
private String username;
private String password;

public void setUsername(String name){


if((name != null) && name!=””){
username = name;
}else{
Sop(“Username cannot be null or empty”);
}
}
public String getUsername(){
return username;
}
….
….
}
Authentication obj = new Authentication();
//obj.username=”aspire”;//Compilation error.
obj.setUsername(“aspire”);//Ok
obj.setUsername(“”);//validation error saying “Username cannot be null or empty.”
Method Abstraction
E-Mail: [email protected] Phone: (+91) 9865358359 2
R.ARAVIND
One of the sound object-oriented programming techniques is “Hiding method implementation complexity from
outside users” is called as method abstraction.
//Method abstraction public
boolean isValidUser(){
//Use JDBC API for obtaining connection.
Connection con = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:XE”, “scott”,
“tiger”);
Check with database whether user is already registered or
not. If valid user then
return true;
else
return false;
}

Encapsulation = Data hiding + Method Abstraction

Encapsulation combines (or bundles) data members with method members together (or the facility that bundles
data with the operations that perform on that data is called as encapsulation).
Example:
public class Authentication{
//Data hiding
private String username;
private String password;

public void setUsername(String name){


if((name != null) && name!=”” ){
username = name;
}
}
public void setPassword(String pwd){
if((pwd != null) && pwd!=”” ){
Password = pwd;
}
}

//Method abstraction
public boolean isValidUser(){
//Use JDBC API for obtaining connection.
Connection con = DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:XE”,
“scott”, “tiger”);
Check with database whether user is already registered or not.
If valid user then
return true;
else
return false;
E-Mail: [email protected]
Phone: (+91) 9865358359 3
R.ARAVIND
}
}

//Client program
Public class AccessSite{
public static void main(String[] args){
Authentication auth = new
Authentication(); //set website username
and password auth.setUsername(“aspire”);
auth.setPassword(“aspire123”);

boolean success= auth.isValidUser();


if(success){
System.out.println(“Logged into INBOX…”);
}else{
System.out.println(“Invalid username / password…”);
}
}
}

Inheritance
Define common methods in parent class and specific methods in child class.
Example:
class Figure{ //Parent class
private int width;
private int height;
public Figure(int w, int h )
{
width = w; height = h;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public void move(int x, int y){
System.out.println("Move method...");
}
public void resize(int width, int height){
System.out.println("Resize method....");
}
public void hide(){
System.out.println("Hide method...");
}
public void show(){

E-Mail: [email protected] Phone: (+91) 9865358359 4


R.ARAVIND
System.out.println("show method...");
}
}
class Rectangle extends Figure{ //child class
public Rectangle(int w, int h)
{
super(w,h);//Invokes immediate parent class matching constructor
}
//subclass specific method.
double area(){
return getHeight()* getWidth();
}
}

class Triangle extends Figure{


public Triangle(int w, int h){
super(w,h);
}
//subclass specific method.
double area(){
Return 0.5 * getHeight()* getWidth();
}
}

~ Triangle
~ Figure ~ Rectangle
-width
-height
+Figure(int, int) +Rectangle() +Triangle()
+getWidth() +getWidth() +getWidth()
+getHeight() +getHeight() +getHeight()
+move() +move() +move()
+resize() +resize() +resize()
+hide() +hide() +hide()
+show() +show() +show()
+area() +area()

Note:
Accessibility modifier UML symbol
Private -
Default ~
Protected #
Public +

In the above example, Rectangle IS-A Figure. Similarly, Triangle IS-A Figure. So, inheritance is also called as IS-A
relationship.
E-Mail: [email protected] Phone: (+91) 9865358359 5
R.ARAVIND
The base class common methods move(), resize(), hide(), and show() are reused in the subclasses Rectangle
and Triangle. Hence the main advantage with inheritance is Code REUSABILITY.
The base class is also called as superclass, supertype, or parent class. The derived class is also called as subclass,
subtype, or child class.
In java, the extends keyword is used to inherit a superclass.
Example:
class Rectangle extends Figure{}

In java, a class can inherit at most one superclass. This is called single level inheritance.
Example:
class C extends A, B{} //Compilation error.
Conclusion: Java does not support multiple inheritance with classes but supports with interfaces.

The inheritance relationship is represented as Hierarchical classification.

Figure

Rectangle Triangle
Figure 1: Inheritance hierarchy

The classes higher up in the hierarchy are more generalized and the classes lower down in the hierarchy
are more specialized.

Case 1: Subclass specific methods cannot be invoked using superclass reference variable.
Example:
Figure fRef = new Figure(10,20);
fRef.move();
//Compilation error. Undefined method.
//fRef.area();

Case 2: As expected, subtype object is assigned to subtype reference variable:


Example:
Rectangle rRef = new Rectangle(10,20);
rRef.move(); //Compiles and runs without errors.
rRef.area();

Case 3: The subclass object can be assigned to a superclass reference variable. But, the subclass specific
methods cannot be invoked using superclass reference variable, because the compiler only knows
reference type methods but not actual runtime object methods.
This assignment involves a widening reference conversion (upcasting).
Example:
Figure fRef = new Rectangle(10,30); //Reference type widening. Subtype object is assigned to supertype ref var.
fRef.move();//Ok
E-Mail: [email protected] Phone: (+91) 9865358359 6
R.ARAVIND
fRef.area(); // Compilation error. Undefined method.

Polymorphism
Polymorphism translates from Greek as many forms (poly - many & morph - forms). Overloading and
overriding are the two different types of polymorphisms.
Overloading – Static polymorphism
Overriding – Dynamic polymorphism

Method Signature
It is the combination of the method name and its parameters list. Method signature does not consider
return type and method modifiers.
Example:
public int add(int, int){}
public float add(float, float){}

Method overloading
Two or more methods are said to be overloaded if and only if methods with same name but differs in
parameters list (Differs in Number of parameters, Parameter type, or Parameter order), and without considering
return type, method modifiers i.e. Overloaded methods must have different method signature irrespective of
their return type, modifiers.
Example: class
Addition{
public int add(int x, int y){}
public int add(int x, int y, int z){}

public float add(float x, float y){} public


double add(double x, double y){}

public float add(int x, float y){}


public float add(float x, int y){}
}
All above methods are overloaded with each other.
Addition obj = new Addition();
obj.add(10,20);//compiler maps with add(int, int)
obj.add(10,20,30); //compiler maps with add(int, int, int)

The overloaded methods are resolved by the java compiler at compilation time. Hence overloading is
also known as ‘Static Polymorphism’ or ‘Early Binding’.

Method overriding
A subclass can re-implement superclass methods to provide subclass specific implementation. The method
in superclass is called as overridden method, whereas method in subclass is called as overriding method.
Method overriding rules:
a) The accessibility modifier of subclass method must be same or less restrictive. AND
b) The superclass and subclass methods must have same return type. AND
E-Mail: [email protected] Phone: (+91) 9865358359 7
R.ARAVIND
c) The superclass and subclass method signature must be same (i.e., method name, the number of
parameters, parameter types, parameter order). AND
d) The throws clause in overriding method can throw all, none or a subset of the checked exceptions which
are specified in the throws clause of the overridden method, but not more checked exceptions.

Example:
class Figure {
int width;
int height;
Figure(int w, int h) {
width = w;
height = h;
}
//overridden method
public double area(){
return 0.0; //unknow
}
}
class Rectangle extends Figure {
Rectangle(int w, int h) {
super(w, h);
}
//overriding method
public double area() {
return width * height;
}
}
public class OverridingDemo {
public static void main(String[] args) {
//superclass object assigned to superclass reference variable
Figure fRef = new Figure();
Sop(fRef.area()); //0.0 //area() from Figure class

//subclass object assigned to subclass reference


variable
Figure fRef1 = new Rectangle(10,20);
Sop(fRef1.area()); //200.0 //area() from Rectangle class.
}
}

The method overriding is resolved at runtime based on actual object type but not Reference type.
Hence method overriding is also known as Late Binding or dynamic polymorphism.

Dynamic Method Dispatch (DMD):


Method overriding is also known as Dynamic Method Dispatching.
Example:
class Figure{
E-Mail: [email protected] Phone: (+91) 9865358359 8
R.ARAVIND
void area(){}
}
class Rectangle extends
Figure{ void area(){}
}
class Triangle extends
Figure{ void area(){}
}

Figure fRef = new Rectangle(10,20);


fRef.area(); //area() method from Rectangle object is invoked.

fRef = new Triangle(10,20);


fRef.area(); //area() method from Triangle object is invoked.

The method overriding is also called as Dynamin Method Dispatching, Dynamic Polymorphism, or
Late Binding.

Difference between overloading and overriding:


Criteria Overriding Overloading
Method signature Must be same Must be different.
Return type Must be same. Never considered.
Accessibility modifier Must be same or Less restrictive. Never considered.
Throws clause Must not throw new checked Never considered.
exceptions.
Declaration context A method must only be overridden A method can be overloaded in the
in a subclass. same or in a sub class.
Method call resolution Method overriding resolved at Method overloading resolved at
runtime based on actual object compile time based on Reference
type. It is also called as dynamic type. It is also called as static
polymorphism or late binding. polymorphism or early binding.

Constructor
The purpose of the constructor is initialization followed by instantiation.

Constructor Rules:
a) The name of constructor must be same as class name.
b) The only applicable modifiers for the constructors are:
i) Public ii) protected iii) default modifier iv) private
c) The constructor must not have any return type not even void.
Example:
public class Box{
Int width;
Int height;
Int depth;
public Box(int w, int h, int d){ //Initialization
E-Mail: [email protected] Phone: (+91) 9865358359 9
R.ARAVIND
width = w;
height = h;
depth = d;
}
}

Box b = new Box(1,2,3); //Instantiation


Constructors are either Default constructors or Parameterized constructors:

Constructors

Default constructors Parameterized construcotrs

Implicit default constructor Explicit default constructors Primitive type Reference type

Default constructor
Constructor without parameters is called as Default constructor. It is also called as no-arg constructor.
There are two types of default constructors:
a) Implicit Default Constructor
If no constructor is declared explicitly inside class, the Java Compiler automatically includes constructor
without parameters called as Implicit Default Constructor.
Example:
public class Box{}

//After compilation
public class Box{
public Box(){} //implicit default constructor
}

b) Explicit Default Constructor


We can declare constructor without parameters list explicitly is called as explicit default constructor.
Example:
Class Box{
Box(){ //explicit default
constrctor Width = 1;
Height = 2;
Depth = 3;
}
}

Parameterized Constructor
E-Mail: [email protected] Phone: (+91) 9865358359 10
R.ARAVIND
Constructor can take either Primitive or Reference type as its parameters is called as
parameterized constructor.
Example:
class Box{
int width;
int height;
int depth;
Box(){ //no-arg constructor
Width =1;
Height = 2;
Depth = 3;
}
Box(int width){
this.width = width;
height = 2;
depth = 3;
}
Box(int width, int height){
this.width = width;
this.height =
height; depth = 3;
}
/*Box(int width, int height, int depth){
this.width = width;
this.height = height;
this.depth = depth;
}*/
//short cut approach
Box(int width, int height, int depth){
this(width, height); //calls matching constructor from the same class
this.depth = depth;
}
Box(Box b){
this.width = b.width;
this.height = b.height;
this.depth = b.depth;
}
}
public class ConstructorDemo {
public static void main(String[] args) {
Box b1 = new Box(1,2,3); Box
b2 = new Box(b1);
}
}
Constructors are overloaded with each other. Also, Constructors cannot be inherited to subclass.

E-Mail: [email protected] Phone: (+91) 9865358359 11


R.ARAVIND

Constructor Chaining
Super class constructors are always executed before subclass constructors is called as constructor chaining.
Example:
class One{
One(){
System.out.println("1");
}
}
class Two extends One{
Two(){
System.out.println("2");
}
}
class Three extends
Two{ Three(){
System.out.println("3");
}
}
public class ConstructorChainingDemo {
public static void main(String[] args) {
Three obj = new Three();
}
}
O/P:
1
2
3

super or this
There are two forms of ‘super’ or ‘this’: i) without parantheses ii) with parantheses
‘this’ without parentheses are used to invoke fields and methods from the same class.
‘super’ without parantheses is used to invoke its immediate superclass fields and methods.
‘this()’ is used to call matching constructor from the same class.
‘super()’ is used to call matching constructor from immediate superclass.
Example:
class One{
Int age = 20;
}
class Two extends One{
Int age = 30;
Void disp(){
SOP(age); // 30
SOP(this.age);//30
SOP(super.age); // 20
}
E-Mail: [email protected] Phone: (+91) 9865358359 12
R.ARAVIND
}

final
The ‘final’ is a modifier used with:
a) Variables b) Methods c) Classes

final w.r.t variables


The value of the final variable is always fixed i.e., once it is initialized, it never re-initialized.
Example:
final int SIZE = 10;
//SIZE = 20; //C.E. Final variable cannot be re-initialized. It is
always recommended to use Upper case for final variables names.

Final w.r.t methods


Final methods are always fully (completely) implemented.
Example:
class Figure{
final void move(){}
final void resize(){}
final void show(){}
final void hide(){}
public double area(){
return 0.0; //Unknow
}
}
Final methods cannot be overridden i.e., final keyword prevents method overriding.

final w.r.t classes


If all methods in class are completely implemented, then instead of declaring every method as final, better
declare class itself as final.
By default, all methods in a final class are final.
Example:
public final class One{ public
void meth1(){} public
void meth2(){}
}

Final classes cannot be extended.


Example:
class Two extends One{}//C.E

Note:
1) Final with variables prevents re-initialization.
2) Final with methods prevents method overriding.
3) Final with classes prevents inheritance.

E-Mail: [email protected] Phone: (+91) 9865358359 13


R.ARAVIND

static
The ‘static’ modifier is used with:
a) Variables b) methods c) Blocks d) Inner class

Static members are Independent of any object creation i.e., static members are Common across all objects.
Static members never associated with any object but directly associated with class. Hence, static variables
are also called as Class variables or Global variables.
Example:
class Box{
Private int width;
Private int height;
Private int depth;
public static int count; //static variable
Box(int w, int h, int d){width = w; height = h; depth = d; count++;}
}
Box b1 = new Box(1,2,3);
Box b2 = new Box(4,5,6);
sop(Box.count); //2

Static members are executed when class is loaded into JVM. Hence, static members are accessed without (or
before) creating an object itself.
Note:
1) Instance variables are associated with Heap area.
2) Static variables are associated with Method area.
3) Local variables are associated with Stack area.
4) Final variables are associated with Constant Pool area.

Static methods
Rules:
1) A static method cannot access instance variables.
2) A static method cannot access instance methods.
3) Cannot use this or super from static context.

We can use static members from non-static context, but not vice versa.
It is always recommended to use class name to access static members rather than object name.

abstract
The ‘abstract’ modifier is used
with: a) methods b)classes.

Declare method as abstract if the method implementation is unknown. Always, abstract methods must ends
with semi-colon.
Example:
public abstract double area();

E-Mail: [email protected] Phone: (+91) 9865358359 14


R.ARAVIND
Abstract class Rules:
Declare class as abstract if:
a) Atleast one abstract method, but all other methods are concrete.
b) All methods are abstract methods, i.e., none of the method is a concrete method.
c) All methods are concrete, i.e., none of the method is an abstract method.

If a class inherits abstract class using extends keyword, the subclass must either implement all abstract
methods or declare subclass also as abstract class.
Abstract classes must not be instantiated, but abstract classes are used as reference variables to
achieve dynamic polymorphism.
Example:
public abstract class
Figure{ Int width;
Int height;
Figure(int width, int height){this.width = width; this.height = height;}
Public final void move(){}
Public final void resize(){}
Public final void hide(){}
Public final void show(){}

public abstract double area();


}
class Rectangle extends Figure{
Rectangle(int w, int h){super(w,
h);} @Override
public double area(){
Return width * height;
}
}
Class Triangle extends Figure{ Triangle(int
w, int h){super(w, h);} @Override

Public double area(){


Return 0.5 * width * height;
}
}

Public class AbstractDemo{


Public static void main(String[] args){
//Figure fRef = new Figure(1,2); //C.E since abstract classes cannot be instantiated.
Figure fRef = new Rectangle(10,20);//Subclass object is assigned to superclass ref variable
SOP(fRef.area()); // The area() method from rectangle is invoked.
fRef = new Triangle(10,20);
SOP(fRef.area()); // The area() method from triangle is invoked.
}
}

E-Mail: [email protected] Phone: (+91) 9865358359 15


R.ARAVIND
Advantages with Abstract classes:
1) Forces the subclass to provide method implementation
2) Achieves Dynamic Polymorphism.

Interfaces
Interface provides service details but not its implementation details.
For example, the stack interface says its operations push() and pop() but not its actual implementation details
such as array or linked list. We (service provider) can change stack implementation from array to linked list
without affecting to client applications (service consumer).

Service Consumer

Service Details (interface)

Service Provider

Syntax:
<modifier> interface <interface name> [extends interface1,… interfacen]{
[field declarations]
[method declarations]
}

Fields w.r.t Interface


By default, all interface fields are public static final.
Hence, All of the following field declarations are equal:
a) public static final int SIZE = 10; //Declaring public static final explicitly is redundant but not error.
b) static final int SIZE = 10;
c) final int SIZE = 10;
d) int SIZE = 10;

All interface variables must be initialized in the declaration section.


Example:
Public static final int SIZE = 10; //declaration cum initialization
Public static final int SIZE; //C.E saying Missing Initialization

Methods w.r.t Interface


By default, all interface methods are public abstract i.e., interface is a pure abstract
class. Hence, All of the following methods declarations are equal:
a) public abstract void meth(); //Declaring public abstract explicitly is redundant but not error.
b) public void meth();
c) abstract void meth();
d) void meth();
E-Mail: [email protected] Phone: (+91) 9865358359 16
R.ARAVIND
All methods in an interface are abstract, hence, interfaces cannot be instantiated. However, interfaces can be
used as reference variables.
Example:
public interface Stack{
public void push(int x);
public int pop();
}

public class StackImpl implements


Stack{ private final int SIZE = 10;
public void push(int x){
//impl using arrays
}
public int pop(){
//impl using arrays
}
}

Stack sRef = new StackImpl(); //Ok


sRef.push(10);
sRef.pop();

Constructors w.r.t interface


All variables in an interface are final constants, which must be initialized in the declaration section itself.
Also, all methods in an interface are abstract, such an interfaces cannot be instantiated.
Hence, Interface does not need constructors at all i.e., interfaces never have constructors at all.

Inheritance w.r.t Interface


A class inherits another class using extends keyword.
A class inherits interface(s) using implements keyword.
An interface inherits interface(s) using extends keyword.
Either class or an interface can inherit any number of interfaces.
Example:
Public interface One{} Public interface One{} Public interface One{} Public interface One{}
Public class Two Public interface Two Public interface Two{} Public interface Two{}
implements One{} extends One{} Public class Three Public interface Three
implements One, Two{} extends One, Two{}
Java supports multiple inheritance by inheriting multiple interfaces.

The subclass of an interface either implement all abstract methods or declare subclass as an abstract class.
The accessibility modifier of the subclass method must be always public.
Example:
Public Interface One{
public void meth1();

E-Mail: [email protected] Phone: (+91) 9865358359 17


R.ARAVIND
Public void meth2();
}

class Two implements One{ abstract class Two implements One{


public void meth1(){} public void meth1(){}
public void meth2(){} }
}

Marker Interface
If our class gets special privilege by inheriting an interface, such an interface is called as marker interface.
Example:
Java.io.Serializable
Java.lang.Runnable

If an interface does not have any methods, it is always called as Marker interface.
Example:
Java.io.Serializable

Even though an interface contains methods which gives special privilege to our class, then such an interface is
also called as Marker Interface.
Example:
- run() method.
Java.lang.Runnable

Question: Though interface is a pure abstract class, why do we need an interface?


To support multiple inheritance and if a subclass already implements another class, then subclass cannot
inherit our abstract class. This restriction is not applicable for an interface, since a class can inherit any number
of interfaces.

Difference between abstract class and Interface:


Abstract class Interface
Can contain concrete methods. All methods are abstract.
Can contains non final & non static variables. All variables must be static and final.
Can contains any number of constructors. Never contains constructors at all.
Does not support multiple inheritance. Supports multiple inheritance.
E-Mail: [email protected] Phone: (+91) 9865358359 18
R.ARAVIND

EXCEPTIONS
  Introduction
  
Exception Hierarchy
  
Difference between Exception & Error
  
Methods to display error information
  
Exception handling using : try-catch-finally
  
Checked and Unchecked exceptions
  
Multiple catch blocks
  
Nested try blocks
  
User defined exceptions (Customized Exceptions)
 
Throw and Throws

Introduction
Definition: An unexpected problem occurs while running our application at runtime is called as an exception.
For example: ArithmeticExcetion, ArrayIndexOutOfBoundsException, FileNotFoundException, etc.
Example:
public class ExceptionDemo {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = a/b;
System.out.println("The result="+c);
System.out.println("End of main method");
}
}
o/p:v java 10 0
Exception in thread "main" java.lang.ArithmeticException: / by
zero at ExceptionDemo.main(ExceptionDemo.java:5)
[Abnormal Termination]

Exception Hierarchy
The root class for all exceptions is java.lang.Throwable.
The two main subclasses of Throwable are Exception and Error.
Difference between Exception and Error:
Exception Error
Exceptions are caused by our program and Errors are not caused by our application and rather
hence recovarable. After recovering they are caused due to lack of system resources such
(handling) exception, the program will as memory, etc. Hence, errors are not recoverable. The
continue as if there is no exception. program will be terminated abnormally.
E-Mail: [email protected] Phone: (+91) 9865358359 19
R.ARAVIND

Throwable

Exception Error

InterruptedExceupted RunException IOException AssertionError VirtualMachineError

FileNotFoundException EOFException OutOfMemoryError StackOverFlowError

ArithmeticExcepton IndexOutOfBoudsException ClassCastException NullPointerException

ArrayIndexOutOfBoundsException StringIndexOutOfBoudsException
E-Mail: [email protected] Phone: (+91) 9865358359 20
R.ARAVIND

E-Mail: [email protected] Phone: (+91) 9865358359 21


R.ARAVIND

Methods to display error Information:


The Java.lang.Throwable root class contains the following 3 methods to print exception information:
1) Public void printStackTrace()
This method is used to print following error information:
a) Exception name
b) Exception Message
c) Line number which causes the exception
d) Method belongs to the above line number
e) Class belongs to the above method.
f) File name belongs to the above class.
Example:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionDemo.main(ExceptionDemo.java:5)

2) Public String toString()


This method is used to print following error information:
a) Exception name
b) Exception Message
Example:
java.lang.ArithmeticException: / by zero

3) Public String getMessage()


This method is used to print following error
information. a) Exception Description.
Example:
/ by zero

Exception handling using try-catch-finally


It is always a good programming practice to handle an exception for graceful termination (Normal termination)
of the program i.e., the purpose of handling an exception is to continue program execution as if there is no
exception.

Try block
It contains the statements which likely to throw an exception.
If an exception is raised, the remaining statements in the try block are skipped.
Try block must be followed by either catch or finally or both.

Catch block
Catch block is used to handle an exception.
The catch block is executed only if try block throws an exception.
Catch block cannot be written without try block. For each try block there can be zero or more catch blocks.

Finally block
It is not recommended to write clean up code inside try block, because there is no guaranty for the execution
of all statements inside try.
E-Mail: [email protected] Phone: (+91) 9865358359 22
R.ARAVIND
It is not recommended to write clean up code inside catch block because it won't executed if there is
no Exception.
We required one place to maintain cleanup code which should be executed always irrespective of whether
exception is raised or not and exception is handle or not. Such type of block is called as finally block. Hence
the main objective of finally block is to maintain cleanup code.
Only one finally block can be associated with try block.

Example:
public class ExceptionHandlingDemo {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
try{
int c = a/b;
}catch(Exception ae){
System.out.println("Denominator should not be 0");
ae.printStackTrace();
}finally{
System.out.println(“finally block”);
}
System.out.println("End of main method.");
}
}
Java ExceptionHandlingDemo 10 0
O/P:
Denominator should not be 0
java.lang.ArithmeticException: / by zero
at ExceptionHandlingDemo.main(ExceptionHandlingDemo.java:6)
finally block
End of main method.
[Normal Termination]

Checked and Unchecked exceptions


If an exception(or error) is directly or indirectly inherited from RuntimeException(or Error) is called as
Unchecked exception i.e., in the exception hierarchy, if RuntimeException (or Error) presents then it is a
Unchecked exception, otherwise, it is a checked exception.
Example:
Unchecked exception Checked exception
java.lang.Object java.lang.Object
java.lang.Throwable java.lang.Throwable
java.lang.Exception java.lang.Exception
java.lang.RuntimeException java.lang.ClassNotFoundException
java.lang.ArithmeticException

Checked exception must be handled, otherwise the program will not be compiled.
Example:

E-Mail: [email protected] Phone: (+91) 9865358359 23


R.ARAVIND
Try{
Thread.sleep(1000);
}catch(InterruptedException ie){}

Unchecked exception may or may not be handled. The compiler will ignore unchecked exceptions.
Example:
Void meth(){
SOP(10/0);
}

The unchecked exceptions are caused due to invalid input data entered by end user at runtime, whose
information never known by compiler in advance. Hence, unchecked exceptions are ignored by java compiler.
The checked exceptions must be handled by the developer otherwise the compiler will not let the code to be
compiled.

Try with Multiple Catch Blocks


The way of handling an exception is varied from exception to exception, hence it is recommended to
place separate catch block for every exception.
If the statements in try block throws multiple exceptions, it is recommended to handle them individually.
In case of try with multiple catch blocks, the order of catch blocks present is very important and it should
be from subclass exception type to superclass exception type.
The catch block for a super class exception should not shadow the catch block for the sub class exception i.e. the
order of the catch blocks is from sub class to the super class exception, otherwise the program will not be
compiled.
Example:
Try{ Try{ Try{
Int[] arr = new int[5]; Int[] arr = new int[5]; Int[] arr = new int[5];
SOP(arr[10]); SOP(arr[10]); SOP(arr[10]);
String str = “hello”; String str = “hello”; String str = “hello”;
SOP(str.charAt(10)); SOP(str.charAt(10)); SOP(str.charAt(10));
}catch(ArrayIndexOutOfBoundsExc }catch(ArrayIndexOutOfBoundsExc }catch(IndexOutOfBoundsExceptio
eption e){ e.printStackTrace(); eption ae){ n ae){
}catch(StringIndexOutOfBoundsExc }catch(IndexOutOfBoundsExceptio }catch(ArrayIndexOutOfBoundsExc
eption e){ n e){} eption e){ }
Sop(e.toString()); //OK //C.E.
}
//OK

Nested try blocks


Try block with in another try block is called as nested try block.
Example:
try{
try{
}catch(){}
}catch(){}

E-Mail: [email protected] Phone: (+91) 9865358359 24


R.ARAVIND
If an exception is raised inside inner try block, initially it will look for inner catch block, if it is not matched, then
it will look for outer catch block.
If an exception is raised in outer try block, then directly it will look for outer catch block.

User defined (or Customized) exceptions


Like built-in exceptions, user can define application (project ) specific exceptions is called as user
defined exceptions.
Like built-in exceptions, there are two types of user defined exceptions as well:
  
Un-checked Exceptions
 
Checked Exceptions.
Un-checked Exceptions Checked Exceptions
package edu.aspire; Public class DivByOneException extends
public class DivByOneException extends Exception{
RuntimeException{ Public DivByOneException ( ){}
Public DivByOneException( ){super();} Public DivByOneException (String message){
Public DivByOneException (String message){ Super(message);
super(message); }
} }
}

throw
The ‘throw’ keyword is used to propagate (or delegate) an exception to its caller inorder to let the
calling method to handle an exception rather than implementation method.
Syntax:
throw <throwable object>;
Example:
throw new ArithmeticException(“/ by zero”);

The ‘throw’keyword is always used at block level but not at method signature level.
All built-in exceptions are automatically thrown by the JVM. But, built-in exceptions can be
programmatically thrown by the developer using throw keyword.
All user defined exceptions must be programmatically thrown using ‘throw’ keyword.

Example:
public class Division{
public static void main(String[]
args){ try{
div(10,0); //method calling
}catch(ArithmeticException ae) {
ae.printStackTrace();
}
}
public static void div(int x, int y){ //method implementation If(y==0){

throw new ArithmeticException(“/ by zero”);


}
E-Mail: [email protected] Phone: (+91) 9865358359 25
R.ARAVIND
System.out.println(x/y);
}
}

Built-in exceptions w.r.t throw keyword


Using throw keword with built-in exceptions is optional. Hence the result of the following two programs is
exactly same. class Test{
public static void main(String[] args){ Class Test{
System.out.println(10/0); public static void main(String[] args){
} throw new ArithmeticException(“/ by Zero”);
} }
//R.E : A.E }
//R.E : A.E

User defined exceptions w.r.t throw Class Test{


keyword public static void main(String[] args){
User defined exceptions must be thrown throw new DivByOneException(“/ by one”);
explicitly using throw keyword. Hence the result
}
of the the following
}
two programs is not same. class Test{
// R.E :
public static void main(String[] args){
System.out.println(10/1);
}
}
Compiles and Runs without exception. edu.aspire.DivByOneException: / by one
O/P: 10

throws
Throws keyword is used at method signature level to specify the type of exception a method throws.
Syntax:
<method modifiers> <return type> method_name(<formal parameter list>)
<throws> <ExceptionType1> … <,ExceptionTypeⁿ>{
<statement>
}

Checked exceptions w.r.t throws keyword:


If the throw propagates checked exceptions inside method block, then such checked exceptions must be
specified at method signature using ‘throws’ keyword.
Example:
class Test{ class Test{
p.s.v main(String[] args)throws I.E{ p.s.v main(String[] args){
doStuff(); doStuff();
} }
Public static void doStuff() throws IE{ public static void doStuff(){
throw new InterruptedException(); throw new InterruptedException();
} }
//R.E: InterruptedException //C.E: Unhandled exception type :

E-Mail: [email protected] Phone: (+91) 9865358359 26


R.ARAVIND
InterruptedException.

If an exception is propagated to JVM, it prints the stack trace followed by terminates the thread which
causes the exception. This is called as Default Handler.

Unchecked exceptions w.r.t throws keyword:


The compiler does not verify the unchecked exceptions in throws clause i.e., if the throw propagates unchecked
exceptions inside method block, then throws may or may not specify unchecked exceptions at method
signature.
Example:
class Test{ class Test{
p.s.v.main(String[] args)throws ArithmeticException{ p.s.v.main(String[] args){
throw new ArithmeticException(); throw new ArithmeticException();
} }
} }
//R.E: A.E //R.E: A.E

Throws w.r.t method overriding


The subclass method must not throws more checked exceptions than superclass method, i.e., the overriding
method in subclass may throw none, all, or sub-set of checked exceptions from overridden method from
superclass, but not more checked exceptions. This rule is not applicable for unchecked exceptions.
Example:
class One{ class One{ class One{
public void meth()throws public void meth()throws public void meth()throws
IOException{ IOException{ IOException{
} } }
} } }
class Two extends One{ class Two extends One{ class Two extends One{
public void meth()throws public void meth()throws public void meth()throws
Exception{ InterruptedException{ FileNotFoundException{
} } }
} } }
//C.E: Sub class method must not //C.E: Sub class method must not //R.E: IOException
throw supertype exception. throw different checked exceptions.

The overriding method in subclass may throw different unchecked exceptions than overridden method in
superclass i.e., the overriding method in subclass may or may not specify unchecked exceptions in overridden
method unchecked exceptions in superclass.
class One{ class One{ class One{
public void meth()throws public void meth()throws public void meth()throws
IndexOutOfBoundsException{ IndexOutOfBoundsExceptions{ IndexOutOfBoundsExceptions{
} } }
} } }
class Two extends One{ class Two extends One{ class Two extends One{
public void meth() public void meth()throws public void meth()throws
} RuntimeException ArrayIndexOutOfBoundsException
E-Mail: [email protected] Phone: (+91) 9865358359 27
R.ARAVIND
} } }
//No compilation error. } }
//No compilation error. //No compilation error.

Difference between Checked and Unchecked exceptions :


CheckedException UnCheckedException
Except for RuntimeException, Error, and their Exceptions inherited from Error or
subclasses, all other exceptions are called RuntimeException class and their subclasses are
checked exceptions. known as unchecked exceptions.
All checked exceptions must be handled, The compiler will not force unchecked exceptions
otherwise the program will not be compiled. to be handled i.e., unchecked exceptions may or
may not be handled.
If a method throw checked exceptions, they must Specifying unchecked exceptions in throws clause
be specified in the throws clause. But, more is optional.
checked exceptions must not be specified in the
throws clause.

E-Mail: [email protected] Phone: (+91) 9865358359 28


R.ARAVIND

JAVA.LANG PACKAGE
  Hierarchy
  
Object class
  
String
  
StringBuffer & StringBuider (Jdk1.5)
  
Wrapper classes
 
Autoboxing and Unboxing (Jdk1.5)

This package contains most common classes in java. Hence, this package is automatically imported into every
source file at compile time.
E-Mail: [email protected] Phone: (+91) 9865358359 29
R.ARAVIND

Object

String StringBuffer StringBuilder Math Number Character Boolean Void

BigDecimal BigInteger Byte Short Integer Long Float Double

Figure: Partial Hierarchy Of java.lang Package classes

Note:
1) The six numeric wrapper classes are Byte, Short, Integer, Long, Float, Double.
2) The three non numeric wrapper classes are Character, Boolean, and Void.
3) All wrapper classes, String, StringBuffer, StringBuilder classes are final.
4) All wrapper classes and String classes are immutable.
5) All wrapper classes and String classes are Comparable and Serializable.

E-Mail: [email protected] Phone: (+91) 9865358359 30


R.ARAVIND

E-Mail: [email protected] Phone: (+91) 9865358359 31


R.ARAVIND

Object class
Every class in java, whether it is built-in or user defined, is implicitly inherited from Object class, i.e., the Object
is a root class for all classes in java.

Object class defines following methods:


1. public String toString()
2. public boolean equals(Object)
3. public int hashCode()
4. protected Object clone()
5. public Class getClass()
6. public void wait()
7. public void notify()
8. public void notifyAll()
9. protected void finalize()

public String toString()


It is always recommended to override toString() method to provide object state information.
Example:
class Box{
int width;
int height;
int depth;
Box(int w, int h, int
d){ Width = w;
Height = h;
Depth = d;
}

Int volume(){
return width * height * depth;
}
@Override
public String toString(){
return “Width=”+width +” Height=”+height +” Depth=”+depth;
}
}
Box b1 = new Box(1, 2,3);
Box b2 = new Box(4,5,6);
System.out.println(b1.toString());
System.out.println(b2);//The toString() method will be automatically invoked.
O/P:
Width=1 Height = 2 Depth = 3
Width=4 Height = 5 Depth = 6

E-Mail: [email protected] Phone: (+91) 9865358359 32


R.ARAVIND
Public boolean equals()
Actually, equals() method is used to compare two object states (content comparision).
The == operator is used to compare reference values but not object states (Reference comparision).
Example:
Box b1 = new Box(1,2,3);
Box b2 = new Box(1,2,3);
Box b3 = b1;

SOP(b1.equals(b2));//true
SOP (b1 == b2); //false
SOP(b1.equals(b3));//true
SOP (b1 == b3); //true
SOP (b2 == b3); //false

It is always recommended to override equals() method to compare two object


states. @Override
public boolean equals(Object o) {
//Comparing with null reference always returns false.
if (o == null)
return false;
//Comparing incompatible types always throws
ClassCastException. if (!(o instanceof Box))
throw new ClassCastException();
//alias comparision.
if (this == o) return
true;

Box b = (Box)o;
//content comparison
if ((this.width == b.width) && (this.height == b.height) && (this.depth == b.depth)) {
return true;
} else {
return false;
}
}

Box b1 = new Box(1,2,3);


Box b2 = new Box(1,2,3);
Box b3 = new Box(4,5,6);
Box b4 = b1;
Box b5 = null;
System.out.println(b1 == b2);//false
System.out.println(b1.equals(b2));//true
System.out.println(b1 == b3);//false
System.out.println(b1.equals(b3)); //false
System.out.println(b1==b4); //true
System.out.println(b1.equals(b4));//true
E-Mail: [email protected] Phone: (+91) 9865358359 33
R.ARAVIND

Difference between == operator and equals() method


== operator equals() method
Used to compare reference values but not actual Used to compare actual object states (Content
object states i.e., used for Reference comparision. comparision).

public int hashCode()


The hashcode is associated with object. More than one object may have same hashcode value. The hashcode is
different from reference value. The reference value is returned to reference variable, but hashcode is
associated with object.
The hashing mechanism is used to achieve better search results.
The hashcode take us to the appropriate bucket. The equals() method is used to choose one of the object among
many objects within the bucket.
@Override
public int hashCode() {
final int prime =
31; int result = 1;
result = prime * result + depth;
result = prime * result +
height; result = prime * result
+ width; return result;
}

Box b1 = new Box(1,2,3);


Box b2 = new Box(4,5,6);

Box b3 = new Box(10,20,30);


Box b4 = new Box(40,50,60);

Contract between equals() and hashCode() methods:


1) If two objects are equal by equals() method, then their hashcodes must be same.
2) If two objects are not equal by equals() method, then their hashcodes may or may not be same.
3) If two objects hashcodes are equal by hashCode() method, then their equals() method may or may not
return true.
4) If two objects hashcodes are not equal by hashCode() method, then their equals() method must return
false.

Java.lang.String
In java, String is a sequence of characters but not array of characters. Once string object is created, we are not
allowed to change existing object. If we are trying to perform any change, with those changes a new object is
created. This behavior is called as Immutability.
Strings are created in 4 ways:
1) String Literals
Example:
String str = “aspire”;
E-Mail: [email protected] Phone: (+91) 9865358359 34
R.ARAVIND
2) String objects
Example:
String str = new String(“aspire”);
3) String constant expressions.
Example:
String str = “aspire ” + “ technologies”’;
4) String concatenation operation.
Example:
String str1 = “aspire”’;
String str2 =” technologies”;
String str = str1 + str2;

Example:
String str = new String(“aspire”);
str.concat(“technology”); //new string object is created.
Heap Memory

aspire
str

aspire technology

StringBuffer sb = new StringBuffer(“Aspire”);


Sb.append(“technology”);
Heap Memory

Aspire technology
sb
String class does not support append() method. Once we create StringBuffer object, we can perform
changes. Hence it is a mutable object.

String Constructors
1) Public String()
Creates an empty string whose length is zero.
2) Public String(String str)
Example:
String str = new String(“hello”); //string object
3) Public String(char[] value)
Example:
char[] values = {‘a’,’b’,’c’};
String str = new String(values); //”abc”
4) Public String(StringBuffer sb)
Example:
StringBuffer sb = new StringBuffer(“hello”);
String str = new String(sb);

E-Mail: [email protected] Phone: (+91) 9865358359 35


R.ARAVIND
5) Public String(StringBuilder sb)
Example:
StringBuilder builder = new StringBuilder(“hello”);
String str = new String(sb);

Methods
1. Public char charAt(int index)
Returns the char value at the specified index.
Example:
String str = “aspire”;
SOP(str.charAt(2)); // p
2. Public String concat(String str)
Appends at the end of the invoking string. Always returns new object.
Example:
String str1 = ‘’aspire ”; //string literal
String str2 = str1.concat(“technologies”); //string
object Sop(str1); // “aspire ”
Sop(str2);// “aspire technologies”

3. Public String substring(int beginIndex, int endIndex)


Returns a new string that is a substring of this string. beginIndex is inclusive, but, endIndex is exclusive.
Example:
String str1 = “aspire technologies”
String str2 = str1.substring(0, 6); //”aspire”

4. public String substring(int beginIndex)


If the endIndex is not specified, it returns till end of the string.
Example:
String str1 = “aspire technologies”;
String str2 = str1.substring(7);//”technologies”

5. The following lastIndexOf() methods are overloaded.


Public int lastIndexOf(char ch)
Public int lastIndexOf(String str)
Example:
String name = “java.lang.Integer”;
String cName = name.substring(name.lastIndexOf(‘.’)+1); //”Integer”
String pName = name.substring(0,name.lastIndexOf(‘.’)); // “java.lang”

6. The following indexOf() methods are overloaded.


Public int indexOf(int ch)
Public int indexOf(String str)
Example:
String pack = “java.lang.String”;
pack.substring(0,pack.indexOf(‘.’)); //java

E-Mail: [email protected] Phone: (+91) 9865358359 36


R.ARAVIND
7 . public int length()
Returns the number of characters in the string object.
Example:
String str = “hello”;
SOP(str.length()); //5

8. public String toLowerCase()


Returns string in lowercase format.
Example:
String name=”RAMESH”;
String after = name.toLowerCase(); //ramesh

9. public String toUpperCase()


Returns string in uppercase format.
Example:
String name=”ramesh”;
String after = name.toUpperCase(); //RAMESH

10. public String trim()


Removes leading and trailing spaces, if any.
Example:
String str = “ ramesh ”
Sop(str.trim());//”ramesh”

11. Public String replace(char oldChar, char newChar)


Replaces all occurrences of old characters with new character.
Example:
String str = “ababab”;
String result =str.replace(‘b’,’a’); //aaaaaa

12. Public int compareTo(Object obj)


Returns –ve, if o1 < o2
Returns +ve, then o1 > o2;
Returns 0, then o1 == o2 are equal.
Example:
Sop(“A”.compareTo(“B”));//-1
Sop(“B”.compareTo(“A”));//+1
Sop(“A”.compareTo(“A”));//0

Java.lang.StringBuffer
For every change in string object, a new string object is created, because string is immutable object, which
causes memory overhead. To avoid this, use StringBuffer, the changes are applied on the existing object rather
than creating new object every time. Hence StringBuffer is muttable object.
Constructors
1) Public StringBuffer()
Constructs an empty string buffer with default initial capacity is 16.

E-Mail: [email protected] Phone: (+91) 9865358359 37


R.ARAVIND

2) Public StringBuffer(String str)


Constructs a string buffer initialized to the contents of the specified string.
The initial capacity of the string buffer is : 16 + str.length()
Example:
StringBuffer sb = new StringBuffer(“hello”);
SOP(sb.capacity()); //21
SOP(sb.length()); //5
3) Public StringBuffer(int initialCapacity)
Creates an empty string buffer with specified initial capacity.

Methods
1. Public int capacity() //Not available in String class
Returns the current capacity of the StringBuffer. It means, the maximum number of characters in
can hold. Once it reaches it capacity, it automatically increases.
2. Public int length()
Returns the actual number of characters contained in the StringBuffer.
3. Public char charAt(int index)
4. The following are append() overloaded methods in StringBuffer class
Public StringBuffer append(String s)
Public StringBuffer append(Boolean
b) Public StringBuffer append(char s)
Public StringBuffer append(int s)
Public StringBuffer append(long s)
Public StringBuffer append(double
s) Public StringBuffer append(float s)
Public StringBuffer append(Object s)
Note: Such methods are not available in String class.
5. The following are overloaded insert() methods in StringBuffer class
Public StringBuffer insert(int pos, String s)
Public StringBuffer insert (int pos, Boolean b)
Public StringBuffer insert (int pos, char c)
Public StringBuffer insert(int pos, int i) Public
StringBuffer insert (int pos, long l) Public
StringBuffer insert (int pos, float f) Public
StringBuffer insert(int pos, double f)
Note: String does not have this method.
Example:
StringBuffer sb = new StringBuffer(“1221”);
sb.insert(2,”33”); //123321
6. Public StringBuffer delete(int start, int end) //Not in string class
Start is inclusive, but end is exclusive.
Example:
StringBuffer sb = new StringBuffer(“123321”);
Sb.delete(2,4); //1221
7. Public StringBuffer deleteCharAt(int index)
8. Public StringBuffer reverse() //not in string class
E-Mail: [email protected] Phone: (+91) 9865358359 38
R.ARAVIND
Example:
StringBuffer sb = new StringBuffer("satyam");
System.out.println(sb.reverse()); // O/P: maytas
9. Public void trimToSize()
If the capacity is larger than length, then extra space will be removed.
Example:
StringBuffer sb = new
StringBuffer(“hello”); SOP(sb.capacity());
//21 SOP(sb.length()); //5
Sb.trimToSize();
SOP(sb.capacity()); //5
SOP(sb.length()); //5

Java.lang.StringBuilder (jdk1.5)
StringBuffer is a synchronized class. It cannot be accessed by more than one thread at a time. Hence
performance is not good.
StringBuilder is non-synchronized version of StringBuffer class. Hence, it can be accessed by more than one
thread at a time. So, Performance is good with StringBuilder.
Differences between StringBuffer and StringBuilder:
StringBuffer StringBuilder
Synchronized class (i.e., thread-safe) Non-Synchronized class (i.e., non thread-safe)
Performance is low Performance is high
Legacy class Introduced in Jdk1.5

E-Mail: [email protected] Phone: (+91) 9865358359 39


R.ARAVIND

Wrapper classes
Object

Number Boolean Character Void

Byte Short Integer Long Float Double


Fig: Wrapper classes
Wrapper classes are used to wrap (store) primitive data into an object.
Hence, primitive types can also be handled just like an object.
By default, all wrapper classes are final, hence cannot be inherited.
Also, the instance of all wrapper classes are immutable i.e., the value in the wrapper object cannot be
changed. Public final class Integer extends Number{
private final int value;
public Integer(int value){
this.value = value;
}
Public Integer(String value){
value = parseInt(value)
} public byte byteValue()
{
return (byte)value;
}
public short shortValue() {
return (short)value;
}
public int intValue() {
return (int)value;
}
public long longValue() {
return (long)value;
}
public float floatValue() {
return (float)value;
}
public double doubleValue() {
return (double)value;
}
}

Constructors
E-Mail: [email protected] Phone: (+91) 9865358359 40
R.ARAVIND
All wrapper classes except Character have two overloaded constructors: Primitive type and String type
constructors.

Java.lang.Integer
Public Integer(int value){}
Public Integer(String value){}
Example:
Integer iRef = new Integer(4);
Integer iRef = new Integer(“4”);
Java.lang.Long
Public Long(long value){}
Public Long(String value){}
Example:
Long lRef = new Long(10);
Long lRef = new Long(10L);
Long lRef = new Long(“10”);

Java.lang.Float
Public Float(float value){}
Public Float(double value){}
Public Float(String value){}
Example:
Float fRef = new Float(3.5F);
Float fRef = new Float(3.5);
Float fRef = new Float(“3.5F”);

Java.lang.Character (Contains only one constructor)


Public Character(char value)
Example:
Character cRef = new Character(‘a’);
Character cRef = new Character(“a”); //C.E

Java.lang.Boolean
Public Boolean(boolean value)
Public Boolean(String value)
Allocates a Boolean object representing the value true if the string argument is not null and
is equal, ignoring case, to the string "true".
Example:
Boolean bRef = new Boolean(“true”);
Boolean bRef = new Boolean(“True”); //true
Boolean bRef = new Boolean(“TRUE”);

Boolean bRef = new Boolean(null);


Boolean bRef = new Boolean(“yes”); //false
Boolean bRef = new Boolean(“no”);
E-Mail: [email protected] Phone: (+91) 9865358359 41
R.ARAVIND
Boolean bRef = new Boolean(“aspire”);

Java.lang.Void
Although the Void class is considered as a wrapper class, it does not wrap any primitive value and is not
instantiable i.e has no public constructors. It just denotes the Class object representing the keyword
void.

Fields
The following constants are declared for each wrapper class except Boolean:
Public static final primitive type MIN_VALUE
Public static final primitive type MAX_VALUE
Public static final int SIZE
Public static final Class TYPE

The following constants are declared only for Boolean class:


Public static final Boolean FALSE;
Public static final Boolean TRUE;
Public static final Class TYPE;

Methods
typeValue() Primitive
data static
toString(primitive
valueOf()
parseType()

Wrapper valueOf() String


object value
toString()

The methods are:



1. typeValue() methods Retrieves primitive value from wrapper object.

2. parseType() methods Converts numeric string into numeric value.

3. overloaded valueOf() Alternative to constructors.

4. overloaded toString() Returns string representation of primitive data.
1. typeValue() methods
Retrieving Primitive value from wrapper object.
a) Six Methods:
The following methods are applicable for all numeric wrapper classes:
public byte byteValue() All numeric wrapper classes [Byte, Short, Integer, Long,
public short shortValue() Float, Double] contains six methods.
public int intValue()

E-Mail: [email protected] Phone: (+91) 9865358359 42


R.ARAVIND
public long longValue()
public float floatValue()
public double doubleValue()

b) booleanValue()
This method is applicable only for Boolean wrapper class.
Example:
Boolean bRef =new Boolean(“yes”);
SOP(bRef.booleanValue()); // false

c) charValue()
This method is applicable only for Character wrapper class.
Example:
Character cRef = new Character(‘a’);
SOP(cRef.charValue()); // ‘a’

2. parseType(String) Methods
Every wrapper class except Character class contains following static parseType() method to convert
String value to Primitive data.
Wrapper class parseType(String) Example
Java.lang.Byte parseByte(String) byte b = Byte.parseByte(“1”);
byte b = Byte.parseByte(“one”); //NFE
Java.lang.Short parseShort(String) short s = Short.parseShort(“1”);
Java.lang.Integer parseInt(String) Int I = Integer.parseInt(“1”);
Java.lang.Long parseLong(String) Long l = Long.parseLong(“1”);
Java.lang.Float parseFloat(String) float f = Float.parseFloat(“1.0F”);
Java.lang.Double parseDouble(String) double d = Double.parseDouble(“1.0”);
Java.lang.Boolean parseBoolean(String) Boolean b = Boolean.parseBoolean(“no”);

3. valueOf() method
The overloaded static valueOf() methods are alternative to constructors to create wrapper object.
Public static Wrapper type valueOf(primitive type)
Public static Wrapper type valueOf(String)
Example:
Integer iRef = Integer.valueOf(10);
Integer iRef = Integer.valueOf(“10”);
Integer iRef = Integer.valueOf(“ten”);//throws NFE

4. toString()
All wrapper classes overrides toString() method to return wrapper object value in string format. Also, all
wrapper classes have overloaded static toString(primitive type) method to convert primitive value into string
format.
Example:
String str = Integer.toString(10); // “10”
E-Mail: [email protected] Phone: (+91) 9865358359 43
R.ARAVIND
Integer iRef = new Integer(10);
String str = iRef.toString(); // “10”

Also, the Integer, Float, Double classes contains the following xxxString() methods for converting primitive
to Binary, Octal, and Hexa format.

toBinaryString(int) toOctalString(int) toHexString(int / float/ double)


  
Integer
  
Float or Double
Example:
String s = Integer.toBinaryString(10); //1010
String s = Integer.toHexString(10); //a

Autoboxing and Unboxing


The Auto & Un boxing first time introduced in JDK1.5.
Autoboxing (jdk1.5)
The java compiler automatically converts Primitive data to Wrapper object is called as autoboxing.
Example:
Before compilation:
Integer iRef = 10.
After compilation:
Integer iRef = new Integer(10); // Autoboxing

Unboxing
The java compiler automatically converts Wrapper object to primitive data is called as unboxing.
Example:
Before compilation:
Int I = new Integer(10);
After compilation:
Int I = new Integer(10).intValue(); //unboxing.

E-Mail: [email protected] Phone: (+91) 9865358359 44


Realtime Professional R.ARAVIND

Reflection Mechanism
Reflection is the process of obtaining information about any java class i.e., getting information about fields,
constructors, and methods of a java class.

Class Syntax:
<class modifiers> class <class-name> [extends <superclass name>] [implements interface1, … interfacen] {
//Fields
<field modifiers> type name;

//Constructors
<constructor modifiers> name(<parameters list>){}

//Methods
<method modifiers> <return type> name(<parameters list>){}
}
To obtain information about classes, we have to use java.lang.Class and java.lang.reflect package.

Java.lang.Class
When the class is loaded into JVM, a class object is created in heap area. Such a class object contains complete
information about specified class.
Methods:
1. public static Class forName(String fully qualified className) throws ClassNotFoundException
Example:
Class c = Class.forName(“java.lang.String”); // Returns class object but not string type

2. Getting class modifiers


Public int getModifiers();

3. Getting class name



Public String getName() Returns fully qualified class name.

Public String getSimpleName() Returns just class name without qualified with type.
4. Getting superclass information
Public Class getSuperclass()

5. Getting interface(s) information


Public Class[] getInterfaces()

6. Getting field(s) information


Public Field[] getFields();

7. Getting constructor(s) information


Public Constructor[] getConstructors()

8. Getting method(s) information

45
Realtime Professional R.ARAVIND

Public Method[] getMethods()

9. Creating new instance


Public Object newInstance()

Java.lang.reflect.Field
Every field in a class must have the following format:
<field modifiers> <field type> <field name>;
Methods:
1) Getting field modifiers.
Public int getModifiers()
2) Getting field type
Public Class getType()
3) Getting field name
Public String getName()

java.lang.reflect.Constructor
Every constructor in a class must have the following format:
<constructor modifier> <constructor name>(<parameters list>)
Methods:
1) Getting constructor modifier
Public int getModifiers()

2) Getting constructor name


Public String getName()

3) Getting constructor parameters


Public Class[] getParameterTypes()

Java.lang.reflect.Method
Every method in a class must have the following format:
<method modifiers> <return type> <method name>(<parameters list>)
Methods:
1) Getting method modifiers
Public int getModifiers()

2) Getting method return type


Public Class getReturnType()

3) Getting method name


Public String getName()

4) Getting method parameters list


Public Class[] getParameterTypes()

46
Realtime Professional R.ARAVIND

Java Beans
[ Reusable Software component ]
Java bean is a reusable software component.
In generally, a Java Bean perform a specific task.
Some Java beans are Visible and others are Invisible.
A Java bean may contains Properties, Methods, and Events.

Java beans Rules:


1) Java Bean class must be declared with public modifier.
2) Java Bean must support Persistence (Serialization) by extending java.io.Serializable interface.
3) Java Bean must support Introspection.
To support introspection, Beans must provide access methods to
properties. 4) Java Bean must provides Zero-argument constructors.
Example:
package edu.aspire; //Recommended
Public class Employee implements Serializable{
Private int eno;

Private String ename; //Bean properties


Private long mobile;
Public Employee(){}

Public void setEno(int eno){ this.eno = eno; }


Public int getEno(){ return this.eno; }
Public void setEname(String ename){ this.ename = ename; }

Public String getEname(){ return ename; }


//Bean property methods. Public void
setMobile(long mobile){ this.mobile = mobile; }
Public String getMobile() { return this.mobile;}
}

47
Realtime Professional R.ARAVIND

Introspection Mechanism
Introspection is the process (or mechanism) of obtaining information about a Java Bean i.e.,
getting information about properties, events, and methods of a java bean class.
The Java bean class have following property types:
I. Simple properties
II. Boolean properties
III. Indexed properties
Naming Conventions
The following table detailing java bean class method naming conventions for every property type:
Property type Naming patterns Example
Simple Public T getN() Public String getName(){}
Public void setN(T value) Public void setName(String name){}
Boolean Public boolean isN() Public boolean isHoliday(){}
Public boolean getN() Public boolean getHoliday(){}
Public void setN(boolean value) Public void setHoliday(boolean value){}
Indexed Public T getN(int index) Public boolean getInputs(int index){}
Public T[] getN() Public boolean[] getInputs()
Public void setN(int index, T value) Public void setInputs(int index, boolean
Public void setN(T[] value){} value){}
Public void setInputs(boolean[] values){}
Introspection mechanism uses java.beans package from JDK API to analyze Java Beans.

Java.beans.Introspector
It contains static methods that allow us to obtain information about properties, events, and methods of a
bean. Public static BeanInfo getBeanInfo(Class beanClass);
The above static method returns BeanInfo object which contains complete Java Bean information.

Java.beans.BeanInfo<<interface>>
The following methods from BeanInfo object gives information about Properties, Events, and Methods of a Java
Bean class.
1) Public PropertyDescriptor[] getPropertyDescriptors()
2) Public MethodDescriptor[] getMethodDescriptors()
3) Public EventSetDescriptor[] getEventSetDescriptors()

Example:
import java.awt.Button;
import java.beans.BeanInfo;
import java.beans.EventSetDescriptor;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.MethodDescriptor;
import java.beans.PropertyDescriptor;
public class ItrospectionEx1 {
public static void main(String[] args) {
try {
BeanInfo beanInfo = Introspector.getBeanInfo(Button.class);
48
R.ARAVIN
Realtime Professional D

System.out.println(" ---------------------");
System.out.println("Java Bean Properties:");
System.out.println("--------------------- ");
PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor prop : props) {
System.out.println(prop.getPropertyType().getSimpleName() + " "
+ prop.getName());
}
System.out.println("------------------ ");
System.out.println("Java Bean Methods:");
System.out.println("------------------ ");
MethodDescriptor[] methods = beanInfo.getMethodDescriptors();
for (MethodDescriptor method : methods) {
System.out.println(method.getName());
}
System.out.println("----------------- ");
System.out.println("Java Bean Events:");
System.out.println("----------------- ");
EventSetDescriptor[] events = beanInfo.getEventSetDescriptors();
for(EventSetDescriptor event : events){
System.out.println(event.getName());
}
} catch (IntrospectionException e) {
e.printStackTrace();
}
}
}

Conclusion:
1) The Reflection mechanism work at a low level and deal only with fields, constructors, and methods of a
class. The Introspection mechanism work at a higher level and deal with the properties, events, and
methods of a Java Bean.
2) Introspection mechanism internally uses Reflection API to retrieve properties, events, or
methods information.
49

You might also like