Pages

Saturday 24 August 2013

Core Java - Java.lang Package (FAQ's)




1.    What is Java.lang Package ?

For writing any java program, the most commonly required classes & interfaces are defined in a seperate package called java.lang package. This package is by default available for every java program, no import statement is required to include this package.




2.    What is Object class ?

For every java class whether predefined or customized, the most commonly required methods are defined in Object class. It is also defined as root for all java classes by SUN people.


Example:
If class X is defined which is not extending any other class then it will be direct child of Object Class.

       Class X 
               {
                }   


  If class X extends class Y then X is indirect child of Object class.

  Class X extends Y
                                            {
                                             }



Note: Every class in Java is child class of Object class, either directly or indirectly.
         Multiple inheritance is not allowed in Java but Multi-level inheritance is allowed.




3.    List the methods defined in Object class

Object class has 11 methods:


  1. toString() 
  2. hashCode()
  3. equals(Object o)
  4. clone()
  5. finalize()
  6. getClass()
  7. wait()
  8. wait(long ms)
  9. wait(long ms, int ns)
  10. notify()
  11. notifyAll()




4.    What is hashCode ? What is importance of hashcode ?

JVM generates a unique identification number for every object which is called hashCode.
JVM will use hashcode while saving objects into hashing related data structures like Hashset, Hashtable &
HashMap.

Biggest advantage of saving objects according to hashcode is, it makes Search operation very easy and comparatively faster.

hashCode() method defined in Object class will be executed to generate hashcode based on address of object, if hashCode() method is not overridden in a class. This is default way hashcode is generated for any object. But it is highly recommended to override hashCode() method to customize order of elements in hashing related data structures.

Note: Make sure to generate unique hashcode for every object, then only it make sense.



5.  What is basic difference between "==" operator & .equals(Object o) method ?


  • The "==" operator is meant for reference comparison & .equals() method for content comparison.
  • Assuming, our class is creating two objects o1 & o2, 
  • if o1 == o2 returns true then o1.equals(o2) will always return true.
  • if o1 == o2 returns false then o1.equals(o2) will return either true or false because o1 and o2 are pointing to two different objects, if their content is same .equals method will return true otherwise it will return false. 
  • if o1.equals(o2) returns true then o1 == o2 will return either true or false because here content is same but we are not sure about o1 and o2 pointing to same or two different objects, if they pointing to same object o1==o2 will return true otherwise it will return false. 
  • For object references '==' operator meant for reference comparison. On the other side .equals() method in Object class also meant for reference comparison by default, it can be overridden for content comparison.
  • "==" operator cannot be overridden for content comparison.
  • If we try to compare arguments using "==" where their is no relation between argument types, compile time error will occur saying "incomparable types".
  • On the other hand for comparing argument with different argument types .equals() method will not issue any compile time or run time error, instead it will simply return false.
  • "==" operators are applicable for both primitives & object types while .equals() method is applicable for only object types.


Note:   In short we can say, "==" operator is used for reference comparison & .equals() method for content comparison.



6.    Define clone() method ? When we get "cloneNotSupported" exception ?

Clone() method is created in object class & is used to create exact duplicate object (this process is called cloning). Purpose of cloning is to maintain backup.

If we have to create clone of any object then corresponding class should implement clonable interface (It is defined in java.lang package and also called as Marker interface). if object is defined in class which extends clonable interface then this object is called as clonable object.
If we try to create clone of object which is not clonable then we will get run time error called "cloneNotSupported".



7.    What is Shallow cloning ? What is Deep Cloning ? Which cloning is best ?

Shallow cloning is the process which creates the bitwise copy of an object. In shallow cloning if main object contains primitive variables then exact copy duplicate copy will be created. And if main object contains reference variable then corresponding object won't be created, just reference variable will be created by pointing to the old contained object. If any changes performed by main object on contained object then same changes will be reflected in cloned object. Object class clone() method performs shallow cloning by default. Shallow cloning is preferred if object contains only primitive values. In the diagram after creating clone object if main object performs any changes to reference object (r_object.i) then same will be reflected in clone_object.

Deep Cloning is the process of creating exact duplicate copy of an object including contained object also. If main object contains reference object then similar copy will be created for clone_object also. To achieve deep cloning, user has to override object class clone() method. In deep cloning, if user performs any changes to reference object (main_object.r_object) then those changes will not be reflected in clone_object.

If main_object contains only primitive variables then shallow cloning is the best choice. On the other side if main_object contains reference variable then deep cloning is preferred choice.



8.    What is difference between String & StringBuffer ?

Mutable & Immutable objects
When we create string object, we can not perform any changes the same object. If we try changing the string object, new object will be created & this behavior is called as Immutability of string object. Immutability is applicable to object only & not variables.

On the other end if we try to modify StringBuffer object, same object will be modified, no new object will be created. This behavior is called Mutability of StringBuffer object.

Memory utilization for object creation
If we create one string object, internally always* 2 objects will be created, one in Heap memory & other in SCP (String Control Pool). *Object in SCP is only created if same object is not already created. If SCP has object created and we are trying to create similar string object then existing object will be referred instead of creating one more copy.

.equals() method behavior
For string class, .equals() method is overridden for content comparison. While in stringBuffer class .equals() methods is not overridden for content comparison.

In above case, if we compare 2 different string objects with similar content using overridden .equals() method, then it will return true value. But for similar case in StringBuffer, .equals() method will return false value because in stringBuffer .equals() method is meant for reference comparison.


9.    What is SCP ? Why it is important ?

SCP is String Control Pool. SCP & is specially designed memory area for String constants. Lets discuss some of its advantages:

Memory Utilization & High Performance
When ever we have use string object repeatedly, its never recommended to create multiple copies of similar objects because it will utilize more memory & reduce performance. So instead of creating seperate object copy everytime if we use the same object for multiple requirements, we can reduce the memory utilization & performance will be increased. This can be achieved by SCP.

Immutable behavior
In SCP, if several references pointing to the same object & if the object is modified, all references will be affected. So to avoid this problem SUN people have made String objects Immutable. This immutable behavior doen't allow anyone to modify string object, if  we try to modify the string object, then new object will be created instead of modifying the same object.

String objects are most commonly used in Java, this is the only reason SCP is specially designed for String constants. This is not applicable for StringBuffer because they are not commonly used.

Access to SCP:
SCP is not accessible for Garbage Collector & hence garbage collector cannot delete any object in SCP though they donn't contain any reference. All SCP objects are destroyed automatically at the time of JVM shut down.



10.    What is basic difference between final & Immutable ?

Final means we cannot change value once initialized & Immutable means we cannot change value once assigned. But still they are different:

Final is applicable for variables & not for objects while Immutable is applicable for objects and not for variables.

If final is used for object then we won't get immutability because we can perform any kind of changes to the object. But we cannot reassign the value again for the final object. If we try to reassign value to final object, compilation error will occur.



11.    What is stringBuffer & StringBuilder ? How they are different ?

In Java program if content is not fixed and keep on changing then we cannot use string objects as they are immutable and cannot be modified. To handle this problem, stringBuffer is used. Using stringBuffer we can perform changes within the same object & it will not create new object every time like in string objects.
Initial Capacity of stringBuffer is 16 which will be increase if stringBuffer reaches beyond this capacity. New capacity for stringBuffer is calculated as:
New Capacity = [[Current Capacity + 1] * 2]

Every method in stringBuffer is synchronized & only one thread is allowed to operate on stringBuffer at a time. This increases the wait time for other thread who needs to operate on same stringBuffer object & leads to performance issues. To overcome this problem StringBuilder is introduced. Every method present in StringBuilder is non-synchronized.
As stringBuffer operates on single thread at a time, they are thread safe while stringBuilder objects are not thread safe.
StringBuilder has comparatively high performance & low security.



12.    What is toString() method ?

toString() method is object class method and is available for all java programs by default.
This method is called whenever we are trying to print the object reference variable. For eaxample:

String s = new String("Hadoop Guru")
System.out.println(s);                            <==  Display 1
System.out.println(s.toString());             <==  Display 2

In above 2 cases for displaying/printing the object reference, we will get same output because in if we dont provide toString() method with object reference then compiler will add the same. So during run time both Display's will be perform as:
System.out.println(s.toString());             <==  Display 1   (toString() method added by compiler)
System.out.println(s.toString());             <==  Display 2

In above 2 print statement, Object class toString() method will be called. We can override toString() method by declaring the same in our class.

Object Class toString() method:

Public String toString()
   { 
       return getClass().getName() + "@" + Integer.toHexString(hashcode());
   }



13.    What are Wrapper Classes ? 

Classes to wrap primitives into object form are called Wrapper classes. This way we can handle primitives also like objects.

List of Wrapper classes:
Byte, Short, Integer, Long, Float, Double, Character, Boolean

Wrapper classes define different types of constructors for each Wrapper class:

Public byte Byte(byte)          { ...... }
Public byte Byte(String)        { ...... }

Public short Short(short)       { ...... }
Public short Short(String)      { ...... }

Public int Integer(int)         { ...... }
Public int Integer(String)      { ...... }

Public long Long(long)          { ...... }
Public long Long(String)        { ...... }

Public float Float(float)       { ...... }
Public float Float(double)      { ...... }
Public float Float(String)      { ...... }

Public double Double(double)    { ...... }
Public double Double(String)    { ...... }

Public char Character(char)     { ...... }

Public boolean Boolean(boolean) { ...... }
Public boolean Boolean(String)  { ...... }



Examples:

Integer I = new Integer(20)             <== (Valid) We can pass corresponding primitives      Type-01
Integer I = new Integer("20")           <== (Valid) We can pass string argument                    Type-02
Integer I = new Integer("Twenty")    <== (Invalid) We can only pass numbers in string form
                                                                             Runtime Error (NumberFormatException)

Boolean b = new Boolean(true)      <==  (Valid) We can pass true (Boolean)                     Type-01
Boolean b = new Boolean(false)     <==  (Valid) We can pass false (Boolean)                
Boolean b = new Boolean("true")    <==  (Valid) We can pass true (String)                        Type-02
Boolean b = new Boolean("True")   <==  (Valid) We can pass (String) is not Case-Sensitive for true only
Boolean b = new Boolean("Guru")  <==  (Invalid) Only true & false allowed in lower case

Float I = new Float(20.5f)              <== (Valid) We can pass float                                     Type-01
Float I = new Float(20.5)               <== (Valid) We can pass double                                 Type-02
Float I = new Float("20.5f")            <== (Valid) We can pass string argument                    Type-03

Character I = new Character('h')     <== (Valid) We can pass char in single quotes only     Type-01
Character I = new Character("h")    <== (Invalid)


Note:

  • For all Wrapper classes, .equals(object) method is overridden for content comparison & .toString() method is overridden to return its content.
  • Number, Boolean & Character are direct child classes of Object class.
  • Byte, Short, Integer, Long, Float & Double are indirect child classes of Object class but direct child classes of Number class.
  • All wrapper classes are immutable in behavior.





14.    What is Autoboxing & AutoUnboxing ?

Process of automatic conversion of primitives to wrapper object by compiler is known as Autoboxing & Wrapper objects to primitives is known as AutoUnboxing. This is introducted in 1.5 version of Java.

Example:
Integer I = 100;           <== Here 100 is int value (primitive)
int i = I;                 <== Here i is primitive variable & I is Wrapper class.

After compilation this statement will look like:

Integer I = Integer.valueOf(100);   <== Autoboxing implemented by compiler
int i = I.intValue();               <== AutoUnboxing implemented by compiler

Note:
valueOf() method is used to achieve Autoboxing &
xxxValue() method is used to achieve AutoUnboxing.






More Java Interview questions:

OOPS concepts      |       Exception handling      |       Access Modifiers      |       Interfaces