Hello guys, in this post I will try to cover as many interview questions as possible.These are most commonly asked interview questions that can be useful for freshers as well as experienced people.
In this post I will try to concentrate maximum on core Java questions only.
1. What is the difference between String, StringBuffer and StringBuilder?
String
Object is immutable. I.e. if we create a String object, we cannot change it at
the same memory location.
If
we change the string object, it creates a new memory location and copies the
content into that new location.
Example
String s1 = new String
("Java interview")
Suppose
that Address of s1 is 200
if we say s1 = s1 +" questions”
Then
it will create a new memory location (say at 300) and copies the content to new
location.
I.e.
address of s1 will change to 300. Please click on the image below to maximize it.
StringBuffer :
StringBuffer
is mutable. I.e. if we create a string buffer object, then we can modify it at
the same location.
StringBuffer sb = new String Buffer (“Java interview”);
Suppose
that address of sb is 200
Sb.sppend(“questions”)
Then
its value will be changed to Java Interview Questions and address will be same 200.
String Builder :
- String Builder is Non-synchronized version of String buffer. i.e String Buffer is synchronized where as String builder is non-synchronized.
- StringBuilder is much faster than StringBuffer as it doesnt have to deal with synchronization methods and locks
- so if you are not going to use threading in java then using StringBuilder will improve the efficiency of the program.
- StringBuffer is old class in java where as StringBuilder was introduced from java 1.5 version.
1. Explain about finalize method in
JAVA.
v Finalize method is a protected method
declared in Object class
v It is by default available to all classes
defined in Java.
v This method is called by the garbage
collected before destroying an object.
v We can override this method in our
class. When we override, it is our responsibility to call the finalize method
of the super class.
v Below is the syntax of finalize
method.
Protected void
finalize() throws Throwable;