SlideShare a Scribd company logo
1 of 26
Download to read offline
Class: TY.BSc Computer Science
Subject Code :- CS-335
Subject Name :- Programming in Java – I
Chapter 3 – Part 2
-By Anupama Alagannawar
MIT ACSC, Department of ComputerScience 2020-21
3.6 Predefined Class – Object Class Methods
What is an Object class? Java.lang.Object
● Object class is present in java.lang package.
● The Object class is the parent class of all the classes in java by default. In
other words, it is the topmost class of java.
● Every class in Java is directly or indirectly derived from the Object class.
● If a Class does not extend any other class then it is direct child class
of Object and if extends other class then it is an indirectly derived.
Therefore the Object class methods are available to all Java classes.
● Hence Object class acts as a root of inheritance hierarchy in any Java
Program.
MIT ACSC, Department of Computer Science 2020-21
Java.lang.Object class
● Object class is the parent class of the classes in java.
● Class A
● {
● }
● When we compile the above code , the compiler verifies java syntax and checks whether class A
has any parent.
● Java compiler adds java.lang.Object as the parent of A.
● Every class in java is child of Object class either directly or indirectly.
● Class A extends java.lang.Object // directly
● {
● }
● Class B extends A // Java.lang.object //(indirectly)java.lang.Object is indirectly the parent of B
● {
● } A
B MIT ACSC, Department of Computer Science 2020-21
Methods of Object Class
● int hashCode() - Used to get a hash code value for the object.
● String toString() - Used to get a string representation of the object.
● boolean equals(Object obj) - Used to indicate whether some other object is
"equal to" this one.
● protected void finalize() - garbage collector calls this method on an object
when it determines that there are no more references to the object.
● Class<?> getClass() - Used to get the runtime class of this Object.
● protected Object clone() - Used to create and return a copy of this object.
MIT ACSC, Department of Computer Science 2020-21
int hashcode()
● To identify object uniquely.
● JVM assigns one unique value.
● It is not an address.
Syntax
public int hashCode()
Parameters
This is a default method and this will not accept any parameters.
Return Value
This method returns a hash code value for this object.
MIT ACSC, Department of Computer Science 2020-21
int hashcode()
● Example
● import java.io.*;
● public class Test
● {
● public static void main(String args[])
● {
● String Str = new String("Welcome to JAVA Programming”);
● System.out.println("Hashcode for Str :" + Str.hashCode() );
}
● }
● Output
● Hashcode for Str :1186874997
MIT ACSC, Department of Computer Science 2020-21
String toString()
● toString() : toString() provides String representation of an Object and used
to convert an object to String.
● If you want to represent any object as a string, toString() method is used.
● Object class contains toString() method. We can use toString() method to get
string representation of an object.
● Whenever we try to print the Object reference then internally toString()
method is invoked.
● If we did not define toString() method in your class then Object class
toString() method is invoked otherwise our implemented/Overridden
toString() method will be called.
MIT ACSC, Department of Computer Science 2020-21
toString()
● Syntax of Object class toString() method:
● public String toString() {
return getClass().getName()+"@"+Integer.toHexString(hashCode()); }
Default behavior of toString() is to print class name, then @, then
unsigned hexadecimal representation of the hash code of the object
● It is always recommended to override toString() method to get our
own String representation of Object.
● Note : Whenever we try to print any Object reference, then
internally toString() method is called.
● Student s = new Student(); // Below two statements are equivalent
System.out.println(s); System.out.println(s.toString());
Understanding problem without toString() method
(Let's see the simple code that prints reference.
● class Student{
● int rollno;
● String name;
● String city;
●
● Student(int rollno, String name, String city){
● this.rollno=rollno;
● this.name=name;
● this.city=city;
● }
● public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad"
);
● System.out.println(s1);
● //compiler writes here s1.toString()
● System.out.println(s2);
● //compiler writes here s2.toString()
● }
● }
● Output:
Student@1fee6fc
Student@1eed786
Example of Java toString() method (Now let's see
the real example of toString() method.)
● class Student{
● int rollno;
● String name;
● String city;
●
● Student(int rollno, String name, String city)
● { this.rollno=rollno;
● this.name=name;
● this.city=city;
● }
● public String toString(){
● //overriding the toString() method
● return rollno+" "+name+" "+city;
● }
●
● public static void main(String args[]){
● Student s1=new Student(101,"Raj","luckn
ow");
● Student s2=new Student(102,"Vijay","gha
ziabad");
●
● System.out.println(s1);//compiler writes h
ere s1.toString()
● System.out.println(s2);//compiler writes h
ere s2.toString()
● }
● }
● Output:101 Raj lucknow
102 Vijay ghaziabad
boolean equals(Object obj)
● Java Object equals(Object obj) Method
● equals(Object obj) is the method of Object class. This method is
used to compare the given objects. It is suggested to override
equals(Object obj) method to get our own equality condition on
Objects.
● Syntax
public boolean equals(Object obj)
● Parameter example: s1.equals(s2)
obj - it is the reference object.
● Returns
It returns true if this object is same as the obj argument else it
returns false otherwise.
MIT ACSC, Department of Computer Science 2020-21
Example of equals() Object Method
● public class JavaObjectequalsExample1
● {
● static int a = 10, b=20;
● int c;
● // Constructor
● JavaObjectequalsExample1()
● {
● System.out.println("Addition of 10 a
nd 20 : ");
● c=a+b;
● System.out.println("Answer : "+c);
● }
●
● public static void main(String args[])
● {
● System.out.println("1st object created...");
● JavaObjectequalsExample1 obj1 = new Jav
aObjectequalsExample1();
● System.out.println("2nd object created...");
● JavaObjectequalsExample1 obj2 = new Java
ObjectequalsExample1();
System.out.println("Objects are equal:" + o
bj1.equals(obj2));
● }
● } //for any non-null reference values obj1 and obj2, this
method returns true if and only if obj1 and obj2 refer to
the same object (obj1 == obj2 has the value true).
Difference between == and equals() Method
● == is used for reference
comparison(address comparison). It means
the == operator checks if both objects
refer to the same memory location or not.
● String s1=new String(“KARAN”);
● String s2=new String(“KARAN”);
● SOP(s1==s2); //false // s1.equals(s2)
● String s3=“Naman”;
● String s4=“Naman”;
● SOP(s3==s4); //true
Heap Area
○ S1
○ S2
S3
S4
○ SCP – String Constant Pool
SCP
KARAN
KARAN
KARAN
Naman
Equals() method in Object class and String class
Object Class
● equals() method in Object class is used to compare
the reference or address of two Objects, that is if two
objects point to the same memory location.
● Class Object
● {
● public boolean equals(Object obj)
● {
● return(this==obj) //s1.equals(s2)
● }
● }
● Class Demo {
● p.s.v.m{
● String s1=new String(“KARAN”);
● String s2=new String(“KARAN”);
● SOP(s1==s2); //false
● Equals() method and == are same if you are talking
about Object class
String class
● equals() method in String class is used for content
comparison. It means the equals method is used to
check object values.
● Class String extends Object
● {
● --------
● //override equals
● public boolean equals(Object obj)
● {
● //statements (Content check)
● }
● }
● SOP(s1.equals(s2)) ; //true
finalize() method
● The java.lang.Object.finalize() is called by the garbage collector on an object when
garbage collection determines that there are no more references to the object. A
subclass overrides the finalize method to dispose of system resources or to perform
other cleanup.
● Declaration
protected void finalize()
● Parameters : NA
● Return Value
This method does not return a value.
● The finalize() method of Object class is a method that the Garbage
Collector always calls just before the deletion/destroying the object which is eligible
for Garbage Collection, so as to perform clean-up activity. Clean-up activity means
closing the resources associated with that object like Database Connection, Network
Connection or we can say resource de-allocation. Remember it is not a reserved
keyword. Once the finalize method completes immediately Garbage Collector destroy
that object.
MIT ACSC, Department of Computer Science 2020-21
getclass() method
● The java.lang.Object.getClass() method returns the runtime class of an object.
● The Java Object getClass() method returns the class name of the object.
● The syntax of the getClass() method is: object.getClass()
● getClass() Parameters
● The getClass() method does not take any parameters.
● getClass() Return Values
● the class of the object that calls the method
● class student
● {
● public static void main(String args[])
● {
● student s1=new student();
● System.out.println(s1.getClass());
● String ss=new String();
● System.out.println(ss.getClass());
● }
● }
clone()
● Java provides an assignment operator to copy the values but no operator
to copy the object.
● Object class has a clone method which can be used to copy the values of
an object without any side-effect.
● Assignment operator has a side-effect that when a reference is assigned to
another reference then a new object is not created and both the reference
point to the same object. This means if we change the value in one object
then same will reflect in another object as well.
● clone() method handles this problem.
● //cloning method copies the object
● B b2 = b1.clone(); //b2 and b1 are now pointing to different object
● b2.a = 3; //modify b2 and changes will not reflect in b1
Methods of Object Class continued.....
● void notify() - Used to wake up a single thread that is waiting on this object's
monitor.
● void notifyAll() - Used to wake up all threads that are waiting on this object's
monitor.
● void wait() - marks the current thread to wait until another thread invokes
the notify() method or the notifyAll() method for this object.
● void wait(long timeout) - marks the current thread to wait until either
another thread invokes the notify() method or the notifyAll() method for this
object, or a specified amount of time has elapsed.
● void wait(long timeout, int nanos) - marks the current thread to wait until
another thread invokes the notify() method or the notifyAll() method for this
object, or some other thread interrupts the current thread, or a certain
amount of real time has elapsed.
MIT ACSC, Department of Computer Science 2020-21
Inner Classes
● Nested Classes
● In Java, just like methods, variables of a class too can have another
class as its member. Writing a class within another is allowed in
Java. The class written within is called the nested class, and the
class that holds the inner class is called the outer class.
● Syntax
● The class Outer_Demo is the outer class and the
class Inner_Demo is the nested class.
● class Outer_Demo
● {
● class Inner_Demo
● {
● }
● }
MIT ACSC, Department of Computer Science 2020-21
Nested classes
● Nested classes are divided into two types −
● Non-static nested classes − These are the non-static members
of a class.
● Static nested classes − These are the static members of a class.
MIT ACSC, Department of Computer Science 2020-21
Inner Classes (Non-static Nested Classes)
● Any non-static nested class is known as inner class in java. Java inner class is
associated with the object of the class and they can access all the variables and
methods of the outer class.
● Since inner class are associated with the instance , we can’t have any static variables in
them.
● Java inner class or nested class is a class that is declared inside the class or interface.
We use inner classes to logically group classes and interface in one place so that it can
be more readable and maintainable.
● It can access all the members of the outer class including private data members and
methods.
● Inner classes are a security mechanism in Java. We know a class cannot be associated
with the access modifier private, but if we have the class as a member of other class,
then the inner class can be made private. And this is also used to access the private
members of a class.
● Inner classes are of three types depending on how and where you define them. They are
● Inner Class, Method –local inner class, Anonymous Inner class
Advantages of Java Inner class
● There are basically three advantages of inner classes in java. They
are as follows:
1) Nested classes represent a special type of relationship that is it
can access all the members (data members and methods)
of outer class including private.
2) Nested classes are used to develop more readable and
maintainable code because it logically group classes and
interfaces in one place only.
3) Code Optimization: It requires less code to write
MIT ACSC, Department of Computer Science 2020-21
Anonymous inner class
● A class that have no name is known as anonymous inner class in java. It
should be used if you have to override method of class or interface.
● abstract class Person{
● abstract void eat();
● }
● class TestAnonymousInner{
● public static void main(String args[]){
● Person p=new Person(){
● void eat(){System.out.println("nice fruits");}
● };
● p.eat();
● }
● }
MIT ACSC, Department of Computer Science 2020-21
Wrapper Classes in Java
● A Wrapper class is a class whose object wraps or contains primitive data
types. When we create an object to a wrapper class, it contains a field and
in this field, we can store primitive data types. In other words, we can wrap
a primitive value into a wrapper class object.
Need of Wrapper Classes
● They convert primitive data types into objects. Objects are needed if we
wish to modify the arguments passed into a method (because primitive
types are passed by value).
● The classes in java.util package handles only objects and hence wrapper
classes help in this case also.
● Data structures in the Collection framework, such as ArrayList and Vector,
store only objects (reference types) and not primitive types.
● An object is needed to support synchronization in multithreading.
MIT ACSC, Department of Computer Science 2020-21
Wrapper Class in Java .Continued.......
● Wrapper classes are used to convert primitive data types into Object and
Vice Versa
● Eight classes of java.lang package are known as wrapper class in java
● Primitive Data types and their Corresponding Wrapper class
Autoboxing and Unboxing in wrapper class
● Autoboxing: Converting primitive data
types into Object.
● Eg: Primitive to Wrapper
class Wrapper1
{
public static void main(String args[])
{
int i=100;
Integer j = Integer.valueOf(i);
Integer ab==i; //Autoboxing (JVM
will write Integer.valueOf automatically)
System.out.println( i, j, ab);
}
}
● Unboxing: Converting Object to Primitive
data types.
● Eg. Wrapper to Primitive
Class Wrapper2
{
public static void main(String args[])
{
Integer i = new Integer(10);
int ab = i.intValue();
int j = i; //unboxing
System.out.println( i, ab, j);
}
}

More Related Content

Similar to CHAPTER 3 part2.pdf

Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword pptVinod Kumar
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxchetanpatilcp783
 
Android Development Course in HSE lecture #2
Android Development Course in HSE lecture #2Android Development Course in HSE lecture #2
Android Development Course in HSE lecture #2Empatika
 
Core java concepts
Core java  conceptsCore java  concepts
Core java conceptsRam132
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptxEpsiba1
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3Mahmoud Alfarra
 
javascript objects
javascript objectsjavascript objects
javascript objectsVijay Kalyan
 
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals WebStackAcademy
 
Java Tutorial Lab 3
Java Tutorial Lab 3Java Tutorial Lab 3
Java Tutorial Lab 3Berk Soysal
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in javaElizabeth alexander
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programmingshinyduela
 

Similar to CHAPTER 3 part2.pdf (20)

Oop
OopOop
Oop
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
 
BCA Class and Object (3).pptx
BCA Class and Object (3).pptxBCA Class and Object (3).pptx
BCA Class and Object (3).pptx
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Android Development Course in HSE lecture #2
Android Development Course in HSE lecture #2Android Development Course in HSE lecture #2
Android Development Course in HSE lecture #2
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Rd
RdRd
Rd
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
 
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
 
Java Tutorial Lab 3
Java Tutorial Lab 3Java Tutorial Lab 3
Java Tutorial Lab 3
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
constructer.pptx
constructer.pptxconstructer.pptx
constructer.pptx
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programming
 

Recently uploaded

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 

CHAPTER 3 part2.pdf

  • 1. Class: TY.BSc Computer Science Subject Code :- CS-335 Subject Name :- Programming in Java – I Chapter 3 – Part 2 -By Anupama Alagannawar MIT ACSC, Department of ComputerScience 2020-21
  • 2. 3.6 Predefined Class – Object Class Methods What is an Object class? Java.lang.Object ● Object class is present in java.lang package. ● The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java. ● Every class in Java is directly or indirectly derived from the Object class. ● If a Class does not extend any other class then it is direct child class of Object and if extends other class then it is an indirectly derived. Therefore the Object class methods are available to all Java classes. ● Hence Object class acts as a root of inheritance hierarchy in any Java Program. MIT ACSC, Department of Computer Science 2020-21
  • 3. Java.lang.Object class ● Object class is the parent class of the classes in java. ● Class A ● { ● } ● When we compile the above code , the compiler verifies java syntax and checks whether class A has any parent. ● Java compiler adds java.lang.Object as the parent of A. ● Every class in java is child of Object class either directly or indirectly. ● Class A extends java.lang.Object // directly ● { ● } ● Class B extends A // Java.lang.object //(indirectly)java.lang.Object is indirectly the parent of B ● { ● } A B MIT ACSC, Department of Computer Science 2020-21
  • 4. Methods of Object Class ● int hashCode() - Used to get a hash code value for the object. ● String toString() - Used to get a string representation of the object. ● boolean equals(Object obj) - Used to indicate whether some other object is "equal to" this one. ● protected void finalize() - garbage collector calls this method on an object when it determines that there are no more references to the object. ● Class<?> getClass() - Used to get the runtime class of this Object. ● protected Object clone() - Used to create and return a copy of this object. MIT ACSC, Department of Computer Science 2020-21
  • 5. int hashcode() ● To identify object uniquely. ● JVM assigns one unique value. ● It is not an address. Syntax public int hashCode() Parameters This is a default method and this will not accept any parameters. Return Value This method returns a hash code value for this object. MIT ACSC, Department of Computer Science 2020-21
  • 6. int hashcode() ● Example ● import java.io.*; ● public class Test ● { ● public static void main(String args[]) ● { ● String Str = new String("Welcome to JAVA Programming”); ● System.out.println("Hashcode for Str :" + Str.hashCode() ); } ● } ● Output ● Hashcode for Str :1186874997 MIT ACSC, Department of Computer Science 2020-21
  • 7. String toString() ● toString() : toString() provides String representation of an Object and used to convert an object to String. ● If you want to represent any object as a string, toString() method is used. ● Object class contains toString() method. We can use toString() method to get string representation of an object. ● Whenever we try to print the Object reference then internally toString() method is invoked. ● If we did not define toString() method in your class then Object class toString() method is invoked otherwise our implemented/Overridden toString() method will be called. MIT ACSC, Department of Computer Science 2020-21
  • 8. toString() ● Syntax of Object class toString() method: ● public String toString() { return getClass().getName()+"@"+Integer.toHexString(hashCode()); } Default behavior of toString() is to print class name, then @, then unsigned hexadecimal representation of the hash code of the object ● It is always recommended to override toString() method to get our own String representation of Object. ● Note : Whenever we try to print any Object reference, then internally toString() method is called. ● Student s = new Student(); // Below two statements are equivalent System.out.println(s); System.out.println(s.toString());
  • 9. Understanding problem without toString() method (Let's see the simple code that prints reference. ● class Student{ ● int rollno; ● String name; ● String city; ● ● Student(int rollno, String name, String city){ ● this.rollno=rollno; ● this.name=name; ● this.city=city; ● } ● public static void main(String args[]){ Student s1=new Student(101,"Raj","lucknow"); Student s2=new Student(102,"Vijay","ghaziabad" ); ● System.out.println(s1); ● //compiler writes here s1.toString() ● System.out.println(s2); ● //compiler writes here s2.toString() ● } ● } ● Output: Student@1fee6fc Student@1eed786
  • 10. Example of Java toString() method (Now let's see the real example of toString() method.) ● class Student{ ● int rollno; ● String name; ● String city; ● ● Student(int rollno, String name, String city) ● { this.rollno=rollno; ● this.name=name; ● this.city=city; ● } ● public String toString(){ ● //overriding the toString() method ● return rollno+" "+name+" "+city; ● } ● ● public static void main(String args[]){ ● Student s1=new Student(101,"Raj","luckn ow"); ● Student s2=new Student(102,"Vijay","gha ziabad"); ● ● System.out.println(s1);//compiler writes h ere s1.toString() ● System.out.println(s2);//compiler writes h ere s2.toString() ● } ● } ● Output:101 Raj lucknow 102 Vijay ghaziabad
  • 11. boolean equals(Object obj) ● Java Object equals(Object obj) Method ● equals(Object obj) is the method of Object class. This method is used to compare the given objects. It is suggested to override equals(Object obj) method to get our own equality condition on Objects. ● Syntax public boolean equals(Object obj) ● Parameter example: s1.equals(s2) obj - it is the reference object. ● Returns It returns true if this object is same as the obj argument else it returns false otherwise. MIT ACSC, Department of Computer Science 2020-21
  • 12. Example of equals() Object Method ● public class JavaObjectequalsExample1 ● { ● static int a = 10, b=20; ● int c; ● // Constructor ● JavaObjectequalsExample1() ● { ● System.out.println("Addition of 10 a nd 20 : "); ● c=a+b; ● System.out.println("Answer : "+c); ● } ● ● public static void main(String args[]) ● { ● System.out.println("1st object created..."); ● JavaObjectequalsExample1 obj1 = new Jav aObjectequalsExample1(); ● System.out.println("2nd object created..."); ● JavaObjectequalsExample1 obj2 = new Java ObjectequalsExample1(); System.out.println("Objects are equal:" + o bj1.equals(obj2)); ● } ● } //for any non-null reference values obj1 and obj2, this method returns true if and only if obj1 and obj2 refer to the same object (obj1 == obj2 has the value true).
  • 13. Difference between == and equals() Method ● == is used for reference comparison(address comparison). It means the == operator checks if both objects refer to the same memory location or not. ● String s1=new String(“KARAN”); ● String s2=new String(“KARAN”); ● SOP(s1==s2); //false // s1.equals(s2) ● String s3=“Naman”; ● String s4=“Naman”; ● SOP(s3==s4); //true Heap Area ○ S1 ○ S2 S3 S4 ○ SCP – String Constant Pool SCP KARAN KARAN KARAN Naman
  • 14. Equals() method in Object class and String class Object Class ● equals() method in Object class is used to compare the reference or address of two Objects, that is if two objects point to the same memory location. ● Class Object ● { ● public boolean equals(Object obj) ● { ● return(this==obj) //s1.equals(s2) ● } ● } ● Class Demo { ● p.s.v.m{ ● String s1=new String(“KARAN”); ● String s2=new String(“KARAN”); ● SOP(s1==s2); //false ● Equals() method and == are same if you are talking about Object class String class ● equals() method in String class is used for content comparison. It means the equals method is used to check object values. ● Class String extends Object ● { ● -------- ● //override equals ● public boolean equals(Object obj) ● { ● //statements (Content check) ● } ● } ● SOP(s1.equals(s2)) ; //true
  • 15. finalize() method ● The java.lang.Object.finalize() is called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup. ● Declaration protected void finalize() ● Parameters : NA ● Return Value This method does not return a value. ● The finalize() method of Object class is a method that the Garbage Collector always calls just before the deletion/destroying the object which is eligible for Garbage Collection, so as to perform clean-up activity. Clean-up activity means closing the resources associated with that object like Database Connection, Network Connection or we can say resource de-allocation. Remember it is not a reserved keyword. Once the finalize method completes immediately Garbage Collector destroy that object. MIT ACSC, Department of Computer Science 2020-21
  • 16. getclass() method ● The java.lang.Object.getClass() method returns the runtime class of an object. ● The Java Object getClass() method returns the class name of the object. ● The syntax of the getClass() method is: object.getClass() ● getClass() Parameters ● The getClass() method does not take any parameters. ● getClass() Return Values ● the class of the object that calls the method ● class student ● { ● public static void main(String args[]) ● { ● student s1=new student(); ● System.out.println(s1.getClass()); ● String ss=new String(); ● System.out.println(ss.getClass()); ● } ● }
  • 17. clone() ● Java provides an assignment operator to copy the values but no operator to copy the object. ● Object class has a clone method which can be used to copy the values of an object without any side-effect. ● Assignment operator has a side-effect that when a reference is assigned to another reference then a new object is not created and both the reference point to the same object. This means if we change the value in one object then same will reflect in another object as well. ● clone() method handles this problem. ● //cloning method copies the object ● B b2 = b1.clone(); //b2 and b1 are now pointing to different object ● b2.a = 3; //modify b2 and changes will not reflect in b1
  • 18. Methods of Object Class continued..... ● void notify() - Used to wake up a single thread that is waiting on this object's monitor. ● void notifyAll() - Used to wake up all threads that are waiting on this object's monitor. ● void wait() - marks the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. ● void wait(long timeout) - marks the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. ● void wait(long timeout, int nanos) - marks the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed. MIT ACSC, Department of Computer Science 2020-21
  • 19. Inner Classes ● Nested Classes ● In Java, just like methods, variables of a class too can have another class as its member. Writing a class within another is allowed in Java. The class written within is called the nested class, and the class that holds the inner class is called the outer class. ● Syntax ● The class Outer_Demo is the outer class and the class Inner_Demo is the nested class. ● class Outer_Demo ● { ● class Inner_Demo ● { ● } ● } MIT ACSC, Department of Computer Science 2020-21
  • 20. Nested classes ● Nested classes are divided into two types − ● Non-static nested classes − These are the non-static members of a class. ● Static nested classes − These are the static members of a class. MIT ACSC, Department of Computer Science 2020-21
  • 21. Inner Classes (Non-static Nested Classes) ● Any non-static nested class is known as inner class in java. Java inner class is associated with the object of the class and they can access all the variables and methods of the outer class. ● Since inner class are associated with the instance , we can’t have any static variables in them. ● Java inner class or nested class is a class that is declared inside the class or interface. We use inner classes to logically group classes and interface in one place so that it can be more readable and maintainable. ● It can access all the members of the outer class including private data members and methods. ● Inner classes are a security mechanism in Java. We know a class cannot be associated with the access modifier private, but if we have the class as a member of other class, then the inner class can be made private. And this is also used to access the private members of a class. ● Inner classes are of three types depending on how and where you define them. They are ● Inner Class, Method –local inner class, Anonymous Inner class
  • 22. Advantages of Java Inner class ● There are basically three advantages of inner classes in java. They are as follows: 1) Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of outer class including private. 2) Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only. 3) Code Optimization: It requires less code to write MIT ACSC, Department of Computer Science 2020-21
  • 23. Anonymous inner class ● A class that have no name is known as anonymous inner class in java. It should be used if you have to override method of class or interface. ● abstract class Person{ ● abstract void eat(); ● } ● class TestAnonymousInner{ ● public static void main(String args[]){ ● Person p=new Person(){ ● void eat(){System.out.println("nice fruits");} ● }; ● p.eat(); ● } ● } MIT ACSC, Department of Computer Science 2020-21
  • 24. Wrapper Classes in Java ● A Wrapper class is a class whose object wraps or contains primitive data types. When we create an object to a wrapper class, it contains a field and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object. Need of Wrapper Classes ● They convert primitive data types into objects. Objects are needed if we wish to modify the arguments passed into a method (because primitive types are passed by value). ● The classes in java.util package handles only objects and hence wrapper classes help in this case also. ● Data structures in the Collection framework, such as ArrayList and Vector, store only objects (reference types) and not primitive types. ● An object is needed to support synchronization in multithreading. MIT ACSC, Department of Computer Science 2020-21
  • 25. Wrapper Class in Java .Continued....... ● Wrapper classes are used to convert primitive data types into Object and Vice Versa ● Eight classes of java.lang package are known as wrapper class in java ● Primitive Data types and their Corresponding Wrapper class
  • 26. Autoboxing and Unboxing in wrapper class ● Autoboxing: Converting primitive data types into Object. ● Eg: Primitive to Wrapper class Wrapper1 { public static void main(String args[]) { int i=100; Integer j = Integer.valueOf(i); Integer ab==i; //Autoboxing (JVM will write Integer.valueOf automatically) System.out.println( i, j, ab); } } ● Unboxing: Converting Object to Primitive data types. ● Eg. Wrapper to Primitive Class Wrapper2 { public static void main(String args[]) { Integer i = new Integer(10); int ab = i.intValue(); int j = i; //unboxing System.out.println( i, ab, j); } }