Sunday, April 1, 2018

Java Strings Interview Questions

Java Strings Interview Questions


Strings in java is a very interesting topic for every interviewer. They will trick you in every aspect if your understanding is not clear. Stings are easy, as well as complex. Lets begin with the concepts first:
Java Heap memory can be divided into 2 parts- String constant pool, Sting non-constant pool. Sting constant pool would be around 10-20% of Heap memory and Sting non-constant pool would be around 80-90% of Heap memory.

An string object can be created by 2 way:
1. String literal way:
    String s1="abc";
2. New operator way:
    String s2=new String("abc");

When we execute the below 3 statements:
    String s1="abc";
String s2="abc";
String s3="abc";
And object is created in "Non-constant" pool and a reference called "s1" points to the same object.
Then, for the 2nd object "abc" compiler checks whether an object having the same value exits, if yes, then it will not create the object. s2 points to the same existing object.
Then for 3rd object "abc", the same above step happens. s3 points to the same existing object.

That means after the end of the above 3 statements only 1 String object is created in memory.

Question: How to check whether s1, s2 and s3 are pointing to the same object ?
Answer: By "==" operator. (The .equals() operator checks if the content of the objects are same)
System.out.println(s1==s2); 
If the above statement prints "true"" then its pointing to the same object.





Java Strings Interview Questions

Java Strings Interview Questions Strings in java is a very interesting topic for every interviewer. They will trick you in ever...