SlideShare a Scribd company logo
© 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.
Ad

More Related Content

What's hot (20)

Java generics
Java genericsJava generics
Java generics
Hosein Zare
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
Woxa Technologies
 
03 Java Language And OOP Part III
03 Java Language And OOP Part III03 Java Language And OOP Part III
03 Java Language And OOP Part III
Hari Christian
 
Java Wrapper Classes and I/O Mechanisms
Java Wrapper Classes and I/O MechanismsJava Wrapper Classes and I/O Mechanisms
Java Wrapper Classes and I/O Mechanisms
Subhadra Sundar Chakraborty
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
SRM Institute of Science & Technology, Tiruchirappalli
 
Ios development
Ios developmentIos development
Ios development
elnaqah
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
Rakesh Waghela
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
Ram132
 
Java Generics
Java GenericsJava Generics
Java Generics
Carol McDonald
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
Connex
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
Ramrao Desai
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Concepts
mdfkhan625
 
Java generics final
Java generics finalJava generics final
Java generics final
Akshay Chaudhari
 
06 Java Language And OOP Part VI
06 Java Language And OOP Part VI06 Java Language And OOP Part VI
06 Java Language And OOP Part VI
Hari Christian
 
Autoboxing And Unboxing In Java
Autoboxing And Unboxing In JavaAutoboxing And Unboxing In Java
Autoboxing And Unboxing In Java
chathuranga kasun bamunusingha
 
04 Java Language And OOP Part IV
04 Java Language And OOP Part IV04 Java Language And OOP Part IV
04 Java Language And OOP Part IV
Hari Christian
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
Woxa Technologies
 
05 Java Language And OOP Part V
05 Java Language And OOP Part V05 Java Language And OOP Part V
05 Java Language And OOP Part V
Hari Christian
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java Generics
Yann-Gaël Guéhéneuc
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
Sunil OS
 

Similar to Java Day-4 (20)

Java tutorial part 3
Java tutorial part 3Java tutorial part 3
Java tutorial part 3
Mumbai Academisc
 
DAY_1.3.pptx
DAY_1.3.pptxDAY_1.3.pptx
DAY_1.3.pptx
ishasharma835109
 
Java
Java Java
Java
Prabhat gangwar
 
Fundamental classes in java
Fundamental classes in javaFundamental classes in java
Fundamental classes in java
Garuda Trainings
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
Sandesh Sharma
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
Radhika Talaviya
 
Class and Object.pptx from nit patna ece department
Class and Object.pptx from nit patna ece departmentClass and Object.pptx from nit patna ece department
Class and Object.pptx from nit patna ece department
om2348023vats
 
Java R20 - UNIT-5.docx
Java R20 - UNIT-5.docxJava R20 - UNIT-5.docx
Java R20 - UNIT-5.docx
Pamarthi Kumar
 
Class and Object JAVA PROGRAMMING LANG .pdf
Class and Object JAVA PROGRAMMING LANG .pdfClass and Object JAVA PROGRAMMING LANG .pdf
Class and Object JAVA PROGRAMMING LANG .pdf
sameer2543ynr
 
Wrapper class
Wrapper classWrapper class
Wrapper class
kamal kotecha
 
Java R20 - UNIT-5.pdf
Java R20 - UNIT-5.pdfJava R20 - UNIT-5.pdf
Java R20 - UNIT-5.pdf
Pamarthi Kumar
 
Lecture20 vector
Lecture20 vectorLecture20 vector
Lecture20 vector
nurkhaledah
 
More topics on Java
More topics on JavaMore topics on Java
More topics on Java
Ahmed Misbah
 
String in JAVA --------------------------
String in JAVA --------------------------String in JAVA --------------------------
String in JAVA --------------------------
2003sayanch
 
Java String
Java String Java String
Java String
SATYAM SHRIVASTAV
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
Rohit Rao
 
00 OOP Introduction to Java Lecture Notes.ppt
00 OOP Introduction to Java Lecture Notes.ppt00 OOP Introduction to Java Lecture Notes.ppt
00 OOP Introduction to Java Lecture Notes.ppt
Ijaduola Ilerioluwa
 
00-review.ppt
00-review.ppt00-review.ppt
00-review.ppt
MiltonMolla1
 
L9 wrapper classes
L9 wrapper classesL9 wrapper classes
L9 wrapper classes
teach4uin
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxing
Geetha Manohar
 
Fundamental classes in java
Fundamental classes in javaFundamental classes in java
Fundamental classes in java
Garuda Trainings
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
Sandesh Sharma
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
Radhika Talaviya
 
Class and Object.pptx from nit patna ece department
Class and Object.pptx from nit patna ece departmentClass and Object.pptx from nit patna ece department
Class and Object.pptx from nit patna ece department
om2348023vats
 
Java R20 - UNIT-5.docx
Java R20 - UNIT-5.docxJava R20 - UNIT-5.docx
Java R20 - UNIT-5.docx
Pamarthi Kumar
 
Class and Object JAVA PROGRAMMING LANG .pdf
Class and Object JAVA PROGRAMMING LANG .pdfClass and Object JAVA PROGRAMMING LANG .pdf
Class and Object JAVA PROGRAMMING LANG .pdf
sameer2543ynr
 
Lecture20 vector
Lecture20 vectorLecture20 vector
Lecture20 vector
nurkhaledah
 
More topics on Java
More topics on JavaMore topics on Java
More topics on Java
Ahmed Misbah
 
String in JAVA --------------------------
String in JAVA --------------------------String in JAVA --------------------------
String in JAVA --------------------------
2003sayanch
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
Rohit Rao
 
00 OOP Introduction to Java Lecture Notes.ppt
00 OOP Introduction to Java Lecture Notes.ppt00 OOP Introduction to Java Lecture Notes.ppt
00 OOP Introduction to Java Lecture Notes.ppt
Ijaduola Ilerioluwa
 
L9 wrapper classes
L9 wrapper classesL9 wrapper classes
L9 wrapper classes
teach4uin
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxing
Geetha Manohar
 
Ad

More from People Strategists (20)

MongoDB Session 3
MongoDB Session 3MongoDB Session 3
MongoDB Session 3
People Strategists
 
MongoDB Session 2
MongoDB Session 2MongoDB Session 2
MongoDB Session 2
People Strategists
 
MongoDB Session 1
MongoDB Session 1MongoDB Session 1
MongoDB Session 1
People Strategists
 
Android - Day 1
Android - Day 1Android - Day 1
Android - Day 1
People Strategists
 
Android - Day 2
Android - Day 2Android - Day 2
Android - Day 2
People Strategists
 
Overview of web services
Overview of web servicesOverview of web services
Overview of web services
People Strategists
 
Spring Framework - III
Spring Framework - IIISpring Framework - III
Spring Framework - III
People Strategists
 
Spring Framework-II
Spring Framework-IISpring Framework-II
Spring Framework-II
People Strategists
 
Spring Framework -I
Spring Framework -ISpring Framework -I
Spring Framework -I
People Strategists
 
Hibernate II
Hibernate IIHibernate II
Hibernate II
People Strategists
 
Hibernate III
Hibernate IIIHibernate III
Hibernate III
People Strategists
 
Hibernate I
Hibernate IHibernate I
Hibernate I
People Strategists
 
Identifing Listeners and Filters
Identifing Listeners and FiltersIdentifing Listeners and Filters
Identifing Listeners and Filters
People Strategists
 
Exploring Maven SVN GIT
Exploring Maven SVN GITExploring Maven SVN GIT
Exploring Maven SVN GIT
People Strategists
 
Agile Dev. II
Agile Dev. IIAgile Dev. II
Agile Dev. II
People Strategists
 
Agile Dev. I
Agile Dev. IAgile Dev. I
Agile Dev. I
People Strategists
 
Working with Servlets
Working with ServletsWorking with Servlets
Working with Servlets
People Strategists
 
Overview of JEE Technology
Overview of JEE TechnologyOverview of JEE Technology
Overview of JEE Technology
People Strategists
 
JSP Technology II
JSP Technology IIJSP Technology II
JSP Technology II
People Strategists
 
JSP Technology I
JSP Technology IJSP Technology I
JSP Technology I
People Strategists
 
Ad

Recently uploaded (20)

AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 

Java Day-4

  • 1. © People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com 1
  • 3. 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.
  • 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, 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.
  • 32. 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.
  • 33. 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.
  • 34. 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.
  • 35. 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());
  • 36. 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()); } }
  • 37. 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
  • 38. 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.
  • 39. 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()); } }
  • 40. 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
  • 41. Nested Classes, Local Classes and Anonymous Classes
  • 42. 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.
  • 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.) 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
  • 51. 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;
  • 52. Local Classes (Contd.) class LocalInner { public void accessOuter() { System.out.println("x="+x); System.out.println("z="+z); } } LocalInner li = new LocalInner(); li.accessOuter(); } }
  • 53. Local Classes (Contd.) public class 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 • 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.
  • 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.) 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.
  • 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.) public static 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 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.
  • 67. 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.