Interview Questions on Java - Objects

1. Which class is the super class of all classes?

java.lang.Object class

2. What are the methods exist in Object class?

1. toString();
2. equals();
3. hashCode();
4. finalize();
5. clone();
6. getClass();

3. What is the use of toString() method?

The purpose of toString() method is to return the all attribute values of an object.By default it returns the memory address of object associate with classname and special charecater '@'.

4. What is the use of equals method()?

equals() method is used to check the contents of two similar Objects.Its return type is boolean.

5. What is the use of hashCode()?

hashCode() is used to represent the memory address of an object in integer format.Its return type is int.

6. What is the use of finalize()?

It will execute before the Garbage Collector clean the Objects.

7. Can we call Garbage Collector explicitly? if Yes how?

Yes. we can call it in two ways:
1. System.gc();
2. Runtime.getRuntime().gc();

8. What is the use of Clone()?

Clone() is used to create seperate copy of an object. It is protected method. To clone Object we need to implement 'cloneable' marker interface.

9. What are the types of Clone operations?

There are two types Clone Operations.
1. Deep Copy : Modification of one object doesn't reflects in Cloned Object.
2. Shallow Copy: Modification of one Object reflects in another objects.

10. explain about getClass()?

In java.lang package there is a class which name has "class". getClass() is used to get the "class" object of particular class. ex : class A
class B
A a1 = new A();
Class c1 = a1.getClass() // here "class" object of "a1" is assigned to c1;
here "class" object of "a1" is assigned to c1;

11. How many ways can we create the objects?

1. By using new() operator.
2. By calling newInstance() method
ex: Class c1 = class.forName(classname);
     Object o1 = c1.newInstance();
3. By using Clone() method.
4. while de-serialization
     FileInputStream fis = new FileInputStream(file1);
     Object o1= in.readObject();