Core Java Part 2
Core Java Part 2
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)
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;
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;
//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”);
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(){
~ 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.
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 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){}
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
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.
The method overriding is also called as Dynamin Method Dispatching, Dynamic Polymorphism, or
Late 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;
}
}
Constructors
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
}
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.
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
Note:
1) Final with variables prevents re-initialization.
2) Final with methods prevents method overriding.
3) Final with classes prevents inheritance.
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();
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(){}
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 Provider
Syntax:
<modifier> interface <interface name> [extends interface1,… interfacen]{
[field declarations]
[method declarations]
}
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();
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
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
ArrayIndexOutOfBoundsException StringIndexOutOfBoudsException
E-Mail: [email protected] Phone: (+91) 9865358359 20
R.ARAVIND
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 exception must be handled, otherwise the program will not be compiled.
Example:
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.
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){
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>
}
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.
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.
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
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.
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.
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
SOP(b1.equals(b2));//true
SOP (b1 == b2); //false
SOP(b1.equals(b3));//true
SOP (b1 == b3); //true
SOP (b2 == b3); //false
Box b = (Box)o;
//content comparison
if ((this.width == b.width) && (this.height == b.height) && (this.depth == b.depth)) {
return true;
} else {
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
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);
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”
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.
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
Wrapper classes
Object
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.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”);
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
Methods
typeValue() Primitive
data static
toString(primitive
valueOf()
parseType()
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.
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.
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
45
Realtime Professional R.ARAVIND
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()
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()
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.
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