© People Strategists - Duplication is strictly prohibited -
www.peoplestrategists.com
1
Java.lang
Wrapper Classes
• Wrapper classes include methods to unwrap the object and give back
the data type.
• The Java platform provides wrapper classes for each of the primitive
data types.
• Eight wrapper classes exist in java.lang package that represent eight
data types.
Wrapper Classes (Contd.)
• The list of primitive data types and its corresponding wrapper classes
is shown in the following table:
Wrapper Classes (Contd.)
• All the wrapper class except Character class provides two constructor:
• A constructor that accepts primitive of the type being constructed.
• A constructor that accepts String representation of the type being
constructed.
• Example:
Integer iObj=new Integer(1);
Integer iObj2=new Integer("1");
Character cObj1=new Character('a');
• The wrapper classes provide static valueOf() methods to create
wrapper objects.
Wrapper Classes (Contd.)
• Example:
Integer iObj3=Integer.valueOf("101010", 2);
Here, 101010, is the string value and 2 is the radix which represents the base.
Therefore, the string values is treated as binary number and is converted to its
decimal value. The iObj3 will hold the value, 42.
Integer iObj3=Integer.valueOf("101010");
Here, iObj3 will hold the value, 101010.
• The wrapper classes provide static xxxValue() method to convert the
value of wrapped numeric to its primitive data type.
Wrapper Classes (Contd.)
• Example:
byte b=iObj1.byteValue();
short s=iObj1.shortValue();
double d=iObj1.doubleValue();
• The wrapper classes provide static parseXxx() method to convert the
string representation into its primitive data type.
Example:
int i=Integer.parseInt("1");
double d=Double.parseDouble("1.2");
int j=Integer.parseInt("101010", 2);
Wrapper Classes (Contd.)
• The Integer and Long wrapper classes provide the toXxxString() to
convert the int or long value into binary, octal, or hexadecimal value.
• Example:
String sBinary=Integer.toBinaryString(52);
String sOctal=Integer.toOctalString(52);
String sHexa=Long.toHexString(52);
• The wrapper class provide toString() method to convert an object into
String object. The toString() method is a method of Object class which
is the base class for all Java classes.
• Example:
Integer iObj1=new Integer(1);
String sInteger=iObj1.toString();
Autoboxing and Unboxing
• Autoboxing is the automatic conversion that the Java compiler makes
between the primitive types and their corresponding object wrapper
classes.
• An example of autoboxing:
Character ch = 'a';
• Unboxing is the automatic conversion that the Java compiler makes
between the object wrapper classes and their corresponding
primitive types .
• An example of unboxing:
Character ch=new Character('a');
char chc=ch;
Autoboxing and Unboxing (Contd.)
• Consider the following code:
public class AutoboxingDemo {
static void getNumber(int a){
System.out.println("Int "+a);
}
static void getNumber(double a){
System.out.println("Double "+a);
}
Autoboxing and Unboxing (Contd.)
public static void main(String args[]){
byte b=12;
short s=89;
int i=56;
long l=89l;
getNumber(b);
getNumber(s);
getNumber(i);
getNumber(l);
}
}
Autoboxing and Unboxing (Contd.)
• The preceding code output will be:
Int 12
Int 89
Int 56
Long 89
• The getNumber() method that used byte and short arguments are
implicitly widened to match the version of getNumber() method that
accepts int argument and the long argument is matched with double
argument.
Autoboxing and Unboxing (Contd.)
• Consider the following code:
public class AutoboxingDemo {
static void getNumber(Long l){
System.out.println("Long "+l);
}
public static void main(String args[]){
byte b=9;
getNumber(b);
}
}
Autoboxing and Unboxing (Contd.)
• The preceding code will generate a compilation error.
• In the preceding code more than one conversion has to be done.
• Widen the data first
• Then, autobox to match the parameter.
• The Java compiler can not handle such conversions.
Autoboxing and Unboxing (Contd.)
• Consider the following code snippet:
public class AutoboxingDemo {
static void getNumber(int a, int b){
System.out.println("Int "+a+","+b);
}
static void getNumber(int...a){
for(int x:a)
System.out.println("Int...a "+x);
}
Autoboxing and Unboxing (Contd.)
public static void main(String args[]){
getNumber(1,1);
getNumber(40);
getNumber(12,65,79);
}
}
• The preceding code output will be:
Int 1,1
Int...a 40
Int...a 12
Int...a 65
Int...a 79
Autoboxing and Unboxing (Contd.)
• Consider the following code:
public class AutoboxingDemo {
static void getNumber(long... l){
for(long i:l)
System.out.println("Long "+i);
}
static void getNumber(Integer... i){
for(Integer iObj:i)
System.out.println("Integer...
"+iObj.toString());
}
Autoboxing and Unboxing (Contd.)
public static void main(String args[]){
getNumber(5,6);
}
}
• The preceding code will generate a compilation error as the compiler
does not understands which overloaded method should be called.
Autoboxing and Unboxing (Contd.)
• Consider the following code:
class Vehicle{
int noOfWheels;
void display(){
System.out.println("No Of Wheels: "+noOfWheels);
}
}
class Car extends Vehicle{
Car(int noOfWheels){
super.noOfWheels=noOfWheels;
}
}
Autoboxing and Unboxing (Contd.)
class Bike extends Vehicle{
Bike(int noOfWheels){
super.noOfWheels=noOfWheels;
}
}
public class AutoboxingDemo {
static void displayWheels(Vehicle v){
v.display();
}
public static void main(String args[]){
Bike b=new Bike(2);
displayWheels(b);
Car c=new Car(4);
displayWheels(c);
}
}
Autoboxing and Unboxing (Contd.)
• The preceding code output will be:
No Of Wheels: 2
No Of Wheels: 4
• Here, the displayWheels() method accepts a base class reference as a
parameter. When the displayWheels() method called by passing Car
and Bike reference variable, the compiler widens the Car and Bike
reference to Vehicle.
hashCode() and equals() Methods
• The hashCode() method is used to get a unique integer for given
object.
• The integer is used for determining the bucket location, when the
object needs to be stored in some HashTable like data structure.
• By default, Object’s hashCode() method returns and integer
representation of memory address where object is stored.
• The equals() method is used to determine the equality of two objects.
• The equals() and hashCode() methods are defined inside the
java.lang.Object class.
hashCode() and equals() Methods (Contd.)
• An example to determine the default behavior of equals() method:
class Point{
int x,y;
Point(int x, int y){
this.x=x;
this.y=y;
}
}
hashCode() and equals() Methods (Contd.)
public class EqualsMethoDemo {
public static void main(String args[]){
Point obj1=new Point(1,2);
Point obj2=new Point(1,2);
Point obj3=obj1;
System.out.println("obj1 equals
obj2:"+obj1.equals(obj2));
System.out.println("obj1 equals
obj2:"+obj1.equals(obj3));
}
}
hashCode() and equals() Methods (Contd.)
• The preceding code output will be:
obj1 equals obj2:false
obj1 equals obj2:true
hashCode() and equals() Methods (Contd.)
• In the preceding code, when the equals() method is overridden in the
Point class as shown in the following code snippet:
public boolean equals(Object obj) {
boolean result=false;
if (obj instanceof Point){
Point p=(Point)obj;
if(x==p.x && y==p.y )
result=true;
}
return result;
}
hashCode() and equals() Methods (Contd.)
• The output will be:
obj1 equals obj2:true
obj1 equals obj2:true
• Here, the instanceof operator is used whether the reference variable
holds the object of a particular class.
hashCode() and equals() Methods (Contd.)
• An example to determine the default behavior of equals() method:
public class HashCodeDemo {
int x;
HashCodeDemo(int x){
this.x=x;
}
public boolean equals(Object o){
boolean result=false;
if(o instanceof HashCodeDemo){
HashCodeDemo hcd=(HashCodeDemo)o;
if(hcd.x==this.x)
result=true;
else
result=false;
}
return result;
}
hashCode() and equals() Methods (Contd.)
public int hashCode(){
return x*5;
}
public static void main(String args[]){
HashCodeDemo hcd1=new HashCodeDemo(12);
HashCodeDemo hcd2=new HashCodeDemo(1);
System.out.println(hcd1.equals(hcd2));
System.out.println(hcd1.hashCode());
System.out.println(hcd2.hashCode());
}
}
hashCode() and equals() Methods (Contd.)
• The preceding code output will be:
true
60
60
• It is a good practice to used to write the hashcode() implementation
logic using the instance variable used in the equals() method.
• If the two objects are equal according to the equals() method, then
the hashcode() method on each object must produce same integer
result.
• However, it is not required if the two objects are unequal according to
equals() methods should return distinct hash code value.
String, StringBuffer, and StringBuilder Classes
• String, StringBuffer, and StringBuilder classes are used to work with
string data.
• These classes provides set of methods to work with string data.
• The major difference between String, StringBuffer, and StringBuilder
class is that String object is immutable whereas StringBuffer and
StringBuilder objects are mutable.
• Immutable means that the value stored in the String object cannot be
changed. Therefore, whenever changes are done to String objects
internally a new String object is created.
String, StringBuffer, and StringBuilder Classes
(Contd.)
• StringBuffer and StringBuilder have the same methods with one
difference and that is of synchronization.
• StringBuffer is synchronized, which means it is thread safe and hence
you can use it when you implement threads for your methods.
• StringBuilder is not synchronized, which implies it is not thread safe.
String, StringBuffer, and StringBuilder Classes
(Contd.)
• Some of the commonly used methods of String class is displayed in
the following table:
Method Description
public char charAt(int index) Returns the character located at the String’s specified
index.
Public String concat(String) Returns a string by appending the specified string to the
end of the string.
public boolean
equalsIgnoreCase(String
anotherString)
Returns a Boolean value depending on the comparison
the two string ignoring case considerations.
public int length() Returns the length of the String.
public String replace(char old,
char new)
Returns a String resulting from replacing all occurrences
of oldChar in this string with newChar.
String, StringBuffer, and StringBuilder Classes
(Contd.)
Method Description
public String substring(int
beginIndex)
Returns a new string that is a substring of this string.
public String substring(int
beginIndex, int endIndex)
Returns a new string that is a substring of this string
based on beginning index and end index.
public String toLowerCase() Returns a string by converting all of the characters in
the String to lower case.
public String toUpperCase() Returns a string by converting all of the characters in
the String to upper case.
public String toString() Returns a String object.
public String trim() Returns a copy of the string, with leading and trailing
whitespace omitted.
String, StringBuffer, and StringBuilder Classes
(Contd.)
• An example to work with methods of String class:
public class StringDemo {
public static void main(String args[]){
String sObj1="Java Programming";
String sObj2="java programming";
String sObj3=" java programming ";
System.out.println("sObj1.charAt(2):"+sObj1.charAt(2));
System.out.println("sObj1.concat("
Language"):"+sObj1.concat(" Language"));
System.out.println("sObj1.equalsIgnoreCase(sObj2):"+sOb
j1.equalsIgnoreCase(sObj2));
System.out.println("sObj1.length():"+sObj1.length());
String, StringBuffer, and StringBuilder Classes
(Contd.)
System.out.println("sObj1.replace('J',
'j'):"+sObj1.replace('J', 'j'));
System.out.println("sObj1.substring(5):"+sObj1.substrin
g(5));
System.out.println("sObj1.substring(2,4):"+sObj1.substr
ing(2,4));
System.out.println("sObj1.toLowerCase():"+sObj1.toLower
Case());
System.out.println("sObj1.toUpperCase():"+sObj1.toUpper
Case());
System.out.println("sObj1.toString():"+sObj1.toString()
);
System.out.println("sObj3.trim():"+sObj3.trim());
}
}
String, StringBuffer, and StringBuilder Classes
(Contd.)
• The preceding code output will be:
sObj1.charAt(2):v
sObj1.concat(" Language"):Java Programming Language
sObj1.equalsIgnoreCase(sObj2):true
sObj1.length():16
sObj1.replace('J', 'j'):java Programming
sObj1.substring(5):Programming
sObj1.substring(2,4):va
sObj1.toLowerCase():java programming
sObj1.toUpperCase():JAVA PROGRAMMING
sObj1.toString():Java Programming
sObj3.trim():java programming
String, StringBuffer, and StringBuilder Classes
(Contd.)
• Some of the commonly used methods of StringBuilder class is
displayed in the following table:
• The StringBuffer and StringBuilder class have same set of methods.
However, the methods in StringBuffer class are synchronized.
Method Description
public StringBuilder append(String str) Appends the specified string
public StringBuilder delete(int start, int end) Removes the characters in a substring
public StringBuilder insert(int offset,
String str)
Inserts the string into this character sequence.
public StringBuilder reverse() Causes this character sequence to be replaced by
the reverse of the sequence.
public String toString() Returns a string representing the data in this
sequence.
String, StringBuffer, and StringBuilder Classes
(Contd.)
• An example to work with StringBuilder class methods:
public class StringBuilderDemo {
public static void main(String args[]){
StringBuilder sb1=new StringBuilder("Java
Programming");
System.out.println(sb1.append(" Language"));
System.out.println(sb1.delete(16, 24));
System.out.println(sb1.insert(16," Languag"));
System.out.println(sb1.reverse());
System.out.println(sb1.toString());
}
}
String, StringBuffer, and StringBuilder Classes
(Contd.)
• The preceding code output will be:
Java Programming Language
Java Programminge
Java Programming Language
egaugnaL gnimmargorP avaJ
egaugnaL gnimmargorP avaJ
Nested Classes, Local Classes
and Anonymous Classes
Nested Classes
• Nested class, is a class defined within another class.
• Nested classes are divided into two categories:
• Static
• Non-static.
• Nested classes that are declared static are called static nested classes.
• Non-static nested classes are called inner classes or member classes
or regular inner classes.
Nested Classes (Contd.)
• An example of static and non-static nested classes
class OuterClass {
...
static class StaticNestedClass {
...
}
class InnerClass {
...
}
}
Nested Classes (Contd.)
• Advantages of using nested classes:
• Allows logical grouping of classes that are only used in one place.
• Increases encapsulation.
• Makes the code readable and maintainable.
Nested Classes (Contd.)
• An example to work with static nested class:
public class TestOuter{
static int data=30;
static class Inner
{
void msg(){System.out.println("Data is "+data);}
}
public static void main(String args[]){
TestOuter.Inner obj=new TestOuter.Inner();
obj.msg();
}
}
Nested Classes (Contd.)
• The preceding code output will be:
Data is 30
Nested Classes (Contd.)
• An example to work with non-static nested class:
public class OuterClass {
private int privInt = 10;
public void createInnerClass() {
InnerClass inClass = new InnerClass();
inClass.accessOuter();
}
class InnerClass {
public void accessOuter() {
System.out.println("The outer class's privInt is " + privInt);
}
}
public static void main(String arg[]){
OuterClass obj=new OuterClass();
obj.createInnerClass();
}
}
Nested Classes (Contd.)
• The preceding code output will be:
The outer class's privInt is 10
• In the following code snippet is used to create an instance of inner
class outside the outer class:
OuterClass outer=new OuterClass();
OuterClass.InnerClass inner=outer.new InnerClass();
inner.accessOuter();
(Or)
OuterClass.InnerClass inner = new OuterClass().new
InnerClass();
inner.accessOuter();
Nested Classes (Contd.)
• An example to demonstrate the usage of this keyword in non-static inner
class:
public class OuterClass {
private int privInt = 10;
class InnerClass {
private int privInt = 20;
public void accessOuter() {
System.out.println("The Inner class's privInt is "
+ privInt);
System.out.println("The Inner class's privInt is "
+ this.privInt);
System.out.println("The outer class's privInt is "
+ OuterClass.this.privInt);
}
}
Nested Classes (Contd.)
public static void main(String arg[]){
OuterClass outer=new OuterClass();
OuterClass.InnerClass inner=outer.new
InnerClass();
inner.accessOuter();
}
}
• The preceding code output will be:
The Inner class's privInt is 20
The Inner class's privInt is 20
The outer class's privInt is 10
Local Classes
• Local classes are classes that are defined in a block.
• Generally, local classes are defined in the body of a method. These classes
are also called as method-local inner classes
• Local inner classes cannot be accessed outside the block in which they are
defined.
• An example to work with local classes defined in the body of a method:
class MyOuter
{
private int x = 10;
public void createLocalInnerClass()
{
int y = 20;
final int z = 30;
Local Classes (Contd.)
class LocalInner
{
public void accessOuter()
{
System.out.println("x="+x);
System.out.println("z="+z);
}
}
LocalInner li = new LocalInner();
li.accessOuter();
}
}
Local Classes (Contd.)
public class MethodLocalInnerClassDemo
{
public static void main(String[] args)
{
MyOuter mo = new MyOuter();
mo.createLocalInnerClass();
}
}
Local Classes (Contd.)
• The preceding code output will be:
x=10
z=30
• A method-local inner class can be instantiated only within the
method where the inner class is defined.
• The method-local inner class can access the member variables of
outer class.
• The method-local inner class can not access the local variables of the
method in which the inner class is defined. However, final local
variables are accessible.
Anonymous Classes
• Anonymous classes are expressions, which means that a class is
defined in another expression.
• Anonymous classes enable you to make your code more concise.
• Anonymous classes enable you to declare and instantiate a class at
the same time.
• An anonymous classes are created from an existing class or interface.
Anonymous Classes (Contd.)
• An example to work with anonymous class:
class Interview {
public void read() {
System.out.println("Programmer Interview!");
}
}
public class AnonymousClassDemo {
public static void main(String args[]){
Interview pInstance = new Interview() {
public void read() {
System.out.println("Anonymous Programmer
Interview");
}
};
pInstance.read();
}
}
Anonymous Classes (Contd.)
• The preceding code output will be:
Anonymous Programmer Interview
• The preceding code, we are creating an instance of the
ProgrammerInterview class called pInstance, but what actually
happening is, an instance of an anonymous class is being created.
• The instance, pInstance, is of type ProgrammerInterview, which is the
superclass, but pInstance refers to a annonymus subclass of the
ProgrammerInterview class.
Anonymous Classes (Contd.)
• Consider the following code:
class Interview {
public void read() {
System.out.println("Programmer Interview!");
}
}
public class AnonymousClassDemo {
public static void main(String args[]){
Interview pInstance = new Interview() {
public void read() {
System.out.println("Anonymous
Programmer Interview");
}
Anonymous Classes (Contd.)
public void put(){
System.out.println("Put Method");
}
};
pInstance.read();
pInstance.put();
}
}
• The preceding code will generate a compilation error, because the
anonymous inner class can not invoke a method that is not in the
super class definition.
Anonymous Classes (Contd.)
• An anonymous inner class example of interface type:
interface Interview {
public void read();
}
public class AnonymousClassDemo {
public static void main(String args[]) {
Interview pInstance = new Interview() {
public void read() {
System.out.println("Anonymous Programmer
Interview");
}
};
pInstance.read();
}
}
Anonymous Classes (Contd.)
• An anonymous inner class example of argument defined type:
interface Interview {
public void read();
}
public class AnonymousClassDemo {
void print(Interview i){
System.out.println("Print Method");
i.read();
}
Anonymous Classes (Contd.)
public static void main(String args[]) {
AnonymousClassDemo aObj=new
AnonymousClassDemo();
aObj.print(new Interview() {
public void read() {
System.out.println("Anonymous
Programmer Interview");
}
});
}
}
Anonymous Classes (Contd.)
• The preceding code output will be:
Print Method
Anonymous Programmer Interview
Instance Initializer Block
• Instance initializer block is used to initialize the instance data
member.
• The Java compiler copies instance initializer blocks into every
constructor.
• An initializer block:
{
// whatever code is needed for initialization goes
here
}
Instance Initializer Block (Contd.)
• An example to work with instance initializer block:
public class InitBlockDemo {
{
val=10;
}
int val;
public static void main(String args[]){
InitBlockDemo obj1=new InitBlockDemo();
System.out.println("obj1 val:"+obj1.val);
}
}
• The preceding code output will be:
obj1 val:10
Summary
• You learnt that:
• Wrapper classes include methods to unwrap the object and give back the data type.
• Autoboxing is the automatic conversion that the Java compiler makes between the
primitive types and their corresponding object wrapper classes.
• Unboxing is the automatic conversion that the Java compiler makes between the
object wrapper classes and their corresponding primitive types .
• The hashCode() method is used to get a unique integer for given object.
• The equals() method is used to determine the equality of two objects.
• The major difference between String, StringBuffer, and StringBuilder class is that
String object is immutable whereas StringBuffer and StringBuilder objects are
mutable.
• The toString() method is used to convert an object to String object.
• Java allow to convert a String Objects to objects of other type.
Summary (Contd.)
• Nested classes that are declared static are called static nested classes.
• Non-static nested classes are called inner classes or member classes.
• Local classes are classes that are defined in a block, which is a group of zero or
more statements between balanced braces.
• Anonymous classes enable you to declare and instantiate a class at the same
time.
• Instance initializer block is used to initialize the instance data member.

Java Day-4

  • 1.
    © People Strategists- Duplication is strictly prohibited - www.peoplestrategists.com 1
  • 2.
  • 3.
    Wrapper Classes • Wrapperclasses include methods to unwrap the object and give back the data type. • The Java platform provides wrapper classes for each of the primitive data types. • Eight wrapper classes exist in java.lang package that represent eight data types.
  • 4.
    Wrapper Classes (Contd.) •The list of primitive data types and its corresponding wrapper classes is shown in the following table:
  • 5.
    Wrapper Classes (Contd.) •All the wrapper class except Character class provides two constructor: • A constructor that accepts primitive of the type being constructed. • A constructor that accepts String representation of the type being constructed. • Example: Integer iObj=new Integer(1); Integer iObj2=new Integer("1"); Character cObj1=new Character('a'); • The wrapper classes provide static valueOf() methods to create wrapper objects.
  • 6.
    Wrapper Classes (Contd.) •Example: Integer iObj3=Integer.valueOf("101010", 2); Here, 101010, is the string value and 2 is the radix which represents the base. Therefore, the string values is treated as binary number and is converted to its decimal value. The iObj3 will hold the value, 42. Integer iObj3=Integer.valueOf("101010"); Here, iObj3 will hold the value, 101010. • The wrapper classes provide static xxxValue() method to convert the value of wrapped numeric to its primitive data type.
  • 7.
    Wrapper Classes (Contd.) •Example: byte b=iObj1.byteValue(); short s=iObj1.shortValue(); double d=iObj1.doubleValue(); • The wrapper classes provide static parseXxx() method to convert the string representation into its primitive data type. Example: int i=Integer.parseInt("1"); double d=Double.parseDouble("1.2"); int j=Integer.parseInt("101010", 2);
  • 8.
    Wrapper Classes (Contd.) •The Integer and Long wrapper classes provide the toXxxString() to convert the int or long value into binary, octal, or hexadecimal value. • Example: String sBinary=Integer.toBinaryString(52); String sOctal=Integer.toOctalString(52); String sHexa=Long.toHexString(52); • The wrapper class provide toString() method to convert an object into String object. The toString() method is a method of Object class which is the base class for all Java classes. • Example: Integer iObj1=new Integer(1); String sInteger=iObj1.toString();
  • 9.
    Autoboxing and Unboxing •Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. • An example of autoboxing: Character ch = 'a'; • Unboxing is the automatic conversion that the Java compiler makes between the object wrapper classes and their corresponding primitive types . • An example of unboxing: Character ch=new Character('a'); char chc=ch;
  • 10.
    Autoboxing and Unboxing(Contd.) • Consider the following code: public class AutoboxingDemo { static void getNumber(int a){ System.out.println("Int "+a); } static void getNumber(double a){ System.out.println("Double "+a); }
  • 11.
    Autoboxing and Unboxing(Contd.) public static void main(String args[]){ byte b=12; short s=89; int i=56; long l=89l; getNumber(b); getNumber(s); getNumber(i); getNumber(l); } }
  • 12.
    Autoboxing and Unboxing(Contd.) • The preceding code output will be: Int 12 Int 89 Int 56 Long 89 • The getNumber() method that used byte and short arguments are implicitly widened to match the version of getNumber() method that accepts int argument and the long argument is matched with double argument.
  • 13.
    Autoboxing and Unboxing(Contd.) • Consider the following code: public class AutoboxingDemo { static void getNumber(Long l){ System.out.println("Long "+l); } public static void main(String args[]){ byte b=9; getNumber(b); } }
  • 14.
    Autoboxing and Unboxing(Contd.) • The preceding code will generate a compilation error. • In the preceding code more than one conversion has to be done. • Widen the data first • Then, autobox to match the parameter. • The Java compiler can not handle such conversions.
  • 15.
    Autoboxing and Unboxing(Contd.) • Consider the following code snippet: public class AutoboxingDemo { static void getNumber(int a, int b){ System.out.println("Int "+a+","+b); } static void getNumber(int...a){ for(int x:a) System.out.println("Int...a "+x); }
  • 16.
    Autoboxing and Unboxing(Contd.) public static void main(String args[]){ getNumber(1,1); getNumber(40); getNumber(12,65,79); } } • The preceding code output will be: Int 1,1 Int...a 40 Int...a 12 Int...a 65 Int...a 79
  • 17.
    Autoboxing and Unboxing(Contd.) • Consider the following code: public class AutoboxingDemo { static void getNumber(long... l){ for(long i:l) System.out.println("Long "+i); } static void getNumber(Integer... i){ for(Integer iObj:i) System.out.println("Integer... "+iObj.toString()); }
  • 18.
    Autoboxing and Unboxing(Contd.) public static void main(String args[]){ getNumber(5,6); } } • The preceding code will generate a compilation error as the compiler does not understands which overloaded method should be called.
  • 19.
    Autoboxing and Unboxing(Contd.) • Consider the following code: class Vehicle{ int noOfWheels; void display(){ System.out.println("No Of Wheels: "+noOfWheels); } } class Car extends Vehicle{ Car(int noOfWheels){ super.noOfWheels=noOfWheels; } }
  • 20.
    Autoboxing and Unboxing(Contd.) class Bike extends Vehicle{ Bike(int noOfWheels){ super.noOfWheels=noOfWheels; } } public class AutoboxingDemo { static void displayWheels(Vehicle v){ v.display(); } public static void main(String args[]){ Bike b=new Bike(2); displayWheels(b); Car c=new Car(4); displayWheels(c); } }
  • 21.
    Autoboxing and Unboxing(Contd.) • The preceding code output will be: No Of Wheels: 2 No Of Wheels: 4 • Here, the displayWheels() method accepts a base class reference as a parameter. When the displayWheels() method called by passing Car and Bike reference variable, the compiler widens the Car and Bike reference to Vehicle.
  • 22.
    hashCode() and equals()Methods • The hashCode() method is used to get a unique integer for given object. • The integer is used for determining the bucket location, when the object needs to be stored in some HashTable like data structure. • By default, Object’s hashCode() method returns and integer representation of memory address where object is stored. • The equals() method is used to determine the equality of two objects. • The equals() and hashCode() methods are defined inside the java.lang.Object class.
  • 23.
    hashCode() and equals()Methods (Contd.) • An example to determine the default behavior of equals() method: class Point{ int x,y; Point(int x, int y){ this.x=x; this.y=y; } }
  • 24.
    hashCode() and equals()Methods (Contd.) public class EqualsMethoDemo { public static void main(String args[]){ Point obj1=new Point(1,2); Point obj2=new Point(1,2); Point obj3=obj1; System.out.println("obj1 equals obj2:"+obj1.equals(obj2)); System.out.println("obj1 equals obj2:"+obj1.equals(obj3)); } }
  • 25.
    hashCode() and equals()Methods (Contd.) • The preceding code output will be: obj1 equals obj2:false obj1 equals obj2:true
  • 26.
    hashCode() and equals()Methods (Contd.) • In the preceding code, when the equals() method is overridden in the Point class as shown in the following code snippet: public boolean equals(Object obj) { boolean result=false; if (obj instanceof Point){ Point p=(Point)obj; if(x==p.x && y==p.y ) result=true; } return result; }
  • 27.
    hashCode() and equals()Methods (Contd.) • The output will be: obj1 equals obj2:true obj1 equals obj2:true • Here, the instanceof operator is used whether the reference variable holds the object of a particular class.
  • 28.
    hashCode() and equals()Methods (Contd.) • An example to determine the default behavior of equals() method: public class HashCodeDemo { int x; HashCodeDemo(int x){ this.x=x; } public boolean equals(Object o){ boolean result=false; if(o instanceof HashCodeDemo){ HashCodeDemo hcd=(HashCodeDemo)o; if(hcd.x==this.x) result=true; else result=false; } return result; }
  • 29.
    hashCode() and equals()Methods (Contd.) public int hashCode(){ return x*5; } public static void main(String args[]){ HashCodeDemo hcd1=new HashCodeDemo(12); HashCodeDemo hcd2=new HashCodeDemo(1); System.out.println(hcd1.equals(hcd2)); System.out.println(hcd1.hashCode()); System.out.println(hcd2.hashCode()); } }
  • 30.
    hashCode() and equals()Methods (Contd.) • The preceding code output will be: true 60 60 • It is a good practice to used to write the hashcode() implementation logic using the instance variable used in the equals() method. • If the two objects are equal according to the equals() method, then the hashcode() method on each object must produce same integer result. • However, it is not required if the two objects are unequal according to equals() methods should return distinct hash code value.
  • 31.
    String, StringBuffer, andStringBuilder Classes • String, StringBuffer, and StringBuilder classes are used to work with string data. • These classes provides set of methods to work with string data. • The major difference between String, StringBuffer, and StringBuilder class is that String object is immutable whereas StringBuffer and StringBuilder objects are mutable. • Immutable means that the value stored in the String object cannot be changed. Therefore, whenever changes are done to String objects internally a new String object is created.
  • 32.
    String, StringBuffer, andStringBuilder Classes (Contd.) • StringBuffer and StringBuilder have the same methods with one difference and that is of synchronization. • StringBuffer is synchronized, which means it is thread safe and hence you can use it when you implement threads for your methods. • StringBuilder is not synchronized, which implies it is not thread safe.
  • 33.
    String, StringBuffer, andStringBuilder Classes (Contd.) • Some of the commonly used methods of String class is displayed in the following table: Method Description public char charAt(int index) Returns the character located at the String’s specified index. Public String concat(String) Returns a string by appending the specified string to the end of the string. public boolean equalsIgnoreCase(String anotherString) Returns a Boolean value depending on the comparison the two string ignoring case considerations. public int length() Returns the length of the String. public String replace(char old, char new) Returns a String resulting from replacing all occurrences of oldChar in this string with newChar.
  • 34.
    String, StringBuffer, andStringBuilder Classes (Contd.) Method Description public String substring(int beginIndex) Returns a new string that is a substring of this string. public String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string based on beginning index and end index. public String toLowerCase() Returns a string by converting all of the characters in the String to lower case. public String toUpperCase() Returns a string by converting all of the characters in the String to upper case. public String toString() Returns a String object. public String trim() Returns a copy of the string, with leading and trailing whitespace omitted.
  • 35.
    String, StringBuffer, andStringBuilder Classes (Contd.) • An example to work with methods of String class: public class StringDemo { public static void main(String args[]){ String sObj1="Java Programming"; String sObj2="java programming"; String sObj3=" java programming "; System.out.println("sObj1.charAt(2):"+sObj1.charAt(2)); System.out.println("sObj1.concat(" Language"):"+sObj1.concat(" Language")); System.out.println("sObj1.equalsIgnoreCase(sObj2):"+sOb j1.equalsIgnoreCase(sObj2)); System.out.println("sObj1.length():"+sObj1.length());
  • 36.
    String, StringBuffer, andStringBuilder Classes (Contd.) System.out.println("sObj1.replace('J', 'j'):"+sObj1.replace('J', 'j')); System.out.println("sObj1.substring(5):"+sObj1.substrin g(5)); System.out.println("sObj1.substring(2,4):"+sObj1.substr ing(2,4)); System.out.println("sObj1.toLowerCase():"+sObj1.toLower Case()); System.out.println("sObj1.toUpperCase():"+sObj1.toUpper Case()); System.out.println("sObj1.toString():"+sObj1.toString() ); System.out.println("sObj3.trim():"+sObj3.trim()); } }
  • 37.
    String, StringBuffer, andStringBuilder Classes (Contd.) • The preceding code output will be: sObj1.charAt(2):v sObj1.concat(" Language"):Java Programming Language sObj1.equalsIgnoreCase(sObj2):true sObj1.length():16 sObj1.replace('J', 'j'):java Programming sObj1.substring(5):Programming sObj1.substring(2,4):va sObj1.toLowerCase():java programming sObj1.toUpperCase():JAVA PROGRAMMING sObj1.toString():Java Programming sObj3.trim():java programming
  • 38.
    String, StringBuffer, andStringBuilder Classes (Contd.) • Some of the commonly used methods of StringBuilder class is displayed in the following table: • The StringBuffer and StringBuilder class have same set of methods. However, the methods in StringBuffer class are synchronized. Method Description public StringBuilder append(String str) Appends the specified string public StringBuilder delete(int start, int end) Removes the characters in a substring public StringBuilder insert(int offset, String str) Inserts the string into this character sequence. public StringBuilder reverse() Causes this character sequence to be replaced by the reverse of the sequence. public String toString() Returns a string representing the data in this sequence.
  • 39.
    String, StringBuffer, andStringBuilder Classes (Contd.) • An example to work with StringBuilder class methods: public class StringBuilderDemo { public static void main(String args[]){ StringBuilder sb1=new StringBuilder("Java Programming"); System.out.println(sb1.append(" Language")); System.out.println(sb1.delete(16, 24)); System.out.println(sb1.insert(16," Languag")); System.out.println(sb1.reverse()); System.out.println(sb1.toString()); } }
  • 40.
    String, StringBuffer, andStringBuilder Classes (Contd.) • The preceding code output will be: Java Programming Language Java Programminge Java Programming Language egaugnaL gnimmargorP avaJ egaugnaL gnimmargorP avaJ
  • 41.
    Nested Classes, LocalClasses and Anonymous Classes
  • 42.
    Nested Classes • Nestedclass, is a class defined within another class. • Nested classes are divided into two categories: • Static • Non-static. • Nested classes that are declared static are called static nested classes. • Non-static nested classes are called inner classes or member classes or regular inner classes.
  • 43.
    Nested Classes (Contd.) •An example of static and non-static nested classes class OuterClass { ... static class StaticNestedClass { ... } class InnerClass { ... } }
  • 44.
    Nested Classes (Contd.) •Advantages of using nested classes: • Allows logical grouping of classes that are only used in one place. • Increases encapsulation. • Makes the code readable and maintainable.
  • 45.
    Nested Classes (Contd.) •An example to work with static nested class: public class TestOuter{ static int data=30; static class Inner { void msg(){System.out.println("Data is "+data);} } public static void main(String args[]){ TestOuter.Inner obj=new TestOuter.Inner(); obj.msg(); } }
  • 46.
    Nested Classes (Contd.) •The preceding code output will be: Data is 30
  • 47.
    Nested Classes (Contd.) •An example to work with non-static nested class: public class OuterClass { private int privInt = 10; public void createInnerClass() { InnerClass inClass = new InnerClass(); inClass.accessOuter(); } class InnerClass { public void accessOuter() { System.out.println("The outer class's privInt is " + privInt); } } public static void main(String arg[]){ OuterClass obj=new OuterClass(); obj.createInnerClass(); } }
  • 48.
    Nested Classes (Contd.) •The preceding code output will be: The outer class's privInt is 10 • In the following code snippet is used to create an instance of inner class outside the outer class: OuterClass outer=new OuterClass(); OuterClass.InnerClass inner=outer.new InnerClass(); inner.accessOuter(); (Or) OuterClass.InnerClass inner = new OuterClass().new InnerClass(); inner.accessOuter();
  • 49.
    Nested Classes (Contd.) •An example to demonstrate the usage of this keyword in non-static inner class: public class OuterClass { private int privInt = 10; class InnerClass { private int privInt = 20; public void accessOuter() { System.out.println("The Inner class's privInt is " + privInt); System.out.println("The Inner class's privInt is " + this.privInt); System.out.println("The outer class's privInt is " + OuterClass.this.privInt); } }
  • 50.
    Nested Classes (Contd.) publicstatic void main(String arg[]){ OuterClass outer=new OuterClass(); OuterClass.InnerClass inner=outer.new InnerClass(); inner.accessOuter(); } } • The preceding code output will be: The Inner class's privInt is 20 The Inner class's privInt is 20 The outer class's privInt is 10
  • 51.
    Local Classes • Localclasses are classes that are defined in a block. • Generally, local classes are defined in the body of a method. These classes are also called as method-local inner classes • Local inner classes cannot be accessed outside the block in which they are defined. • An example to work with local classes defined in the body of a method: class MyOuter { private int x = 10; public void createLocalInnerClass() { int y = 20; final int z = 30;
  • 52.
    Local Classes (Contd.) classLocalInner { public void accessOuter() { System.out.println("x="+x); System.out.println("z="+z); } } LocalInner li = new LocalInner(); li.accessOuter(); } }
  • 53.
    Local Classes (Contd.) publicclass MethodLocalInnerClassDemo { public static void main(String[] args) { MyOuter mo = new MyOuter(); mo.createLocalInnerClass(); } }
  • 54.
    Local Classes (Contd.) •The preceding code output will be: x=10 z=30 • A method-local inner class can be instantiated only within the method where the inner class is defined. • The method-local inner class can access the member variables of outer class. • The method-local inner class can not access the local variables of the method in which the inner class is defined. However, final local variables are accessible.
  • 55.
    Anonymous Classes • Anonymousclasses are expressions, which means that a class is defined in another expression. • Anonymous classes enable you to make your code more concise. • Anonymous classes enable you to declare and instantiate a class at the same time. • An anonymous classes are created from an existing class or interface.
  • 56.
    Anonymous Classes (Contd.) •An example to work with anonymous class: class Interview { public void read() { System.out.println("Programmer Interview!"); } } public class AnonymousClassDemo { public static void main(String args[]){ Interview pInstance = new Interview() { public void read() { System.out.println("Anonymous Programmer Interview"); } }; pInstance.read(); } }
  • 57.
    Anonymous Classes (Contd.) •The preceding code output will be: Anonymous Programmer Interview • The preceding code, we are creating an instance of the ProgrammerInterview class called pInstance, but what actually happening is, an instance of an anonymous class is being created. • The instance, pInstance, is of type ProgrammerInterview, which is the superclass, but pInstance refers to a annonymus subclass of the ProgrammerInterview class.
  • 58.
    Anonymous Classes (Contd.) •Consider the following code: class Interview { public void read() { System.out.println("Programmer Interview!"); } } public class AnonymousClassDemo { public static void main(String args[]){ Interview pInstance = new Interview() { public void read() { System.out.println("Anonymous Programmer Interview"); }
  • 59.
    Anonymous Classes (Contd.) publicvoid put(){ System.out.println("Put Method"); } }; pInstance.read(); pInstance.put(); } } • The preceding code will generate a compilation error, because the anonymous inner class can not invoke a method that is not in the super class definition.
  • 60.
    Anonymous Classes (Contd.) •An anonymous inner class example of interface type: interface Interview { public void read(); } public class AnonymousClassDemo { public static void main(String args[]) { Interview pInstance = new Interview() { public void read() { System.out.println("Anonymous Programmer Interview"); } }; pInstance.read(); } }
  • 61.
    Anonymous Classes (Contd.) •An anonymous inner class example of argument defined type: interface Interview { public void read(); } public class AnonymousClassDemo { void print(Interview i){ System.out.println("Print Method"); i.read(); }
  • 62.
    Anonymous Classes (Contd.) publicstatic void main(String args[]) { AnonymousClassDemo aObj=new AnonymousClassDemo(); aObj.print(new Interview() { public void read() { System.out.println("Anonymous Programmer Interview"); } }); } }
  • 63.
    Anonymous Classes (Contd.) •The preceding code output will be: Print Method Anonymous Programmer Interview
  • 64.
    Instance Initializer Block •Instance initializer block is used to initialize the instance data member. • The Java compiler copies instance initializer blocks into every constructor. • An initializer block: { // whatever code is needed for initialization goes here }
  • 65.
    Instance Initializer Block(Contd.) • An example to work with instance initializer block: public class InitBlockDemo { { val=10; } int val; public static void main(String args[]){ InitBlockDemo obj1=new InitBlockDemo(); System.out.println("obj1 val:"+obj1.val); } } • The preceding code output will be: obj1 val:10
  • 66.
    Summary • You learntthat: • Wrapper classes include methods to unwrap the object and give back the data type. • Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. • Unboxing is the automatic conversion that the Java compiler makes between the object wrapper classes and their corresponding primitive types . • The hashCode() method is used to get a unique integer for given object. • The equals() method is used to determine the equality of two objects. • The major difference between String, StringBuffer, and StringBuilder class is that String object is immutable whereas StringBuffer and StringBuilder objects are mutable. • The toString() method is used to convert an object to String object. • Java allow to convert a String Objects to objects of other type.
  • 67.
    Summary (Contd.) • Nestedclasses that are declared static are called static nested classes. • Non-static nested classes are called inner classes or member classes. • Local classes are classes that are defined in a block, which is a group of zero or more statements between balanced braces. • Anonymous classes enable you to declare and instantiate a class at the same time. • Instance initializer block is used to initialize the instance data member.