java day-4

67
© People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 1

Upload: people-strategists

Post on 17-Aug-2015

518 views

Category:

Technology


0 download

TRANSCRIPT

© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com

1

Java.lang

Wrapper Classes

• Wrapper classes include methods to unwrap the object and give backthe data type.

• The Java platform provides wrapper classes for each of the primitivedata types.

• Eight wrapper classes exist in java.lang package that represent eightdata types.

Wrapper Classes (Contd.)

• The list of primitive data types and its corresponding wrapper classesis 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 createwrapper 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 itsdecimal 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 thevalue 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 thestring 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() toconvert 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 intoString object. The toString() method is a method of Object class whichis 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 makesbetween the primitive types and their corresponding object wrapperclasses.

• An example of autoboxing:Character ch = 'a';

• Unboxing is the automatic conversion that the Java compiler makesbetween the object wrapper classes and their correspondingprimitive 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 12Int 89Int 56Long 89

• The getNumber() method that used byte and short arguments areimplicitly widened to match the version of getNumber() method thataccepts int argument and the long argument is matched with doubleargument.

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,1Int...a 40Int...a 12Int...a 65Int...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 compilerdoes 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: 2No Of Wheels: 4

• Here, the displayWheels() method accepts a base class reference as aparameter. When the displayWheels() method called by passing Carand Bike reference variable, the compiler widens the Car and Bikereference to Vehicle.

hashCode() and equals() Methods

• The hashCode() method is used to get a unique integer for givenobject.

• The integer is used for determining the bucket location, when theobject needs to be stored in some HashTable like data structure.

• By default, Object’s hashCode() method returns and integerrepresentation 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:falseobj1 equals obj2:true

hashCode() and equals() Methods (Contd.)

• In the preceding code, when the equals() method is overridden in thePoint 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:trueobj1 equals obj2:true

• Here, the instanceof operator is used whether the reference variableholds 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:true6060

• It is a good practice to used to write the hashcode() implementationlogic using the instance variable used in the equals() method.

• If the two objects are equal according to the equals() method, thenthe hashcode() method on each object must produce same integerresult.

• However, it is not required if the two objects are unequal according toequals() methods should return distinct hash code value.

String, StringBuffer, and StringBuilder Classes

• String, StringBuffer, and StringBuilder classes are used to work withstring 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 andStringBuilder objects are mutable.

• Immutable means that the value stored in the String object cannot bechanged. Therefore, whenever changes are done to String objectsinternally 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 Descriptionpublic 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 booleanequalsIgnoreCase(StringanotherString)

Returns a Boolean value depending on the comparisonthe 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 occurrencesof oldChar in this string with newChar.

String, StringBuffer, and StringBuilder Classes(Contd.)Method Descriptionpublic String substring(intbeginIndex)

Returns a new string that is a substring of this string.

public String substring(intbeginIndex, int endIndex)

Returns a new string that is a substring of this stringbased on beginning index and end index.

public String toLowerCase() Returns a string by converting all of the characters inthe String to lower case.

public String toUpperCase() Returns a string by converting all of the characters inthe 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.substring(5));

System.out.println("sObj1.substring(2,4):"+sObj1.substring(2,4));

System.out.println("sObj1.toLowerCase():"+sObj1.toLowerCase());

System.out.println("sObj1.toUpperCase():"+sObj1.toUpperCase());

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):vsObj1.concat(" Language"):Java Programming LanguagesObj1.equalsIgnoreCase(sObj2):truesObj1.length():16sObj1.replace('J', 'j'):java ProgrammingsObj1.substring(5):ProgrammingsObj1.substring(2,4):vasObj1.toLowerCase():java programmingsObj1.toUpperCase():JAVA PROGRAMMINGsObj1.toString():Java ProgrammingsObj3.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 bythe reverse of the sequence.

public String toString() Returns a string representing the data in thissequence.

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("JavaProgramming");

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 LanguageJava ProgrammingeJava Programming LanguageegaugnaL gnimmargorP avaJegaugnaL gnimmargorP avaJ

Nested Classes, Local Classesand 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 classesclass 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 innerclass outside the outer class:OuterClass outer=new OuterClass();OuterClass.InnerClass inner=outer.new InnerClass();inner.accessOuter();(Or)OuterClass.InnerClass inner = new OuterClass().newInnerClass();inner.accessOuter();

Nested Classes (Contd.)

• An example to demonstrate the usage of this keyword in non-static innerclass: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 20The Inner class's privInt is 20The 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=10z=30

• A method-local inner class can be instantiated only within themethod where the inner class is defined.

• The method-local inner class can access the member variables ofouter class.

• The method-local inner class can not access the local variables of themethod in which the inner class is defined. However, final localvariables are accessible.

Anonymous Classes

• Anonymous classes are expressions, which means that a class isdefined 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 theProgrammerInterview class called pInstance, but what actuallyhappening is, an instance of an anonymous class is being created.

• The instance, pInstance, is of type ProgrammerInterview, which is thesuperclass, but pInstance refers to a annonymus subclass of theProgrammerInterview 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 theanonymous inner class can not invoke a method that is not in thesuper 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 MethodAnonymous Programmer Interview

Instance Initializer Block

• Instance initializer block is used to initialize the instance datamember.

• The Java compiler copies instance initializer blocks into everyconstructor.

• An initializer block:{

// whatever code is needed for initialization goeshere}

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 aremutable.

• 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.