Java Interview Questions – Part 2

What is meant by Immutable?In Java, Strings are treated as Objects. Immutable means once the object has been created it cannot be changed.

What are the advantages of String being Immutable?

It helps in Multi-threading, We can be sure that no one will change the string

Reduction in Memory usage

Two ways of Creating Strings:

String s1 = “StringValue”;

String S2 = new String(“StringValue2”);

What is the difference between creating Strings?Consider an example,

We are creating 2 strings with S1 and S2,

String S1 = “Java”

String S2 = “Java”

This will create a single reference in string pool and S1 and S2 will point to that Reference

String S1 = new String(“Java”)

String S2 = new String(“Java”)

This will create two separate objects in string pool

String s1 = “Java”, String S2 = “Java”

String S1 = new String(“Java”), String S2 = new String(“Java”)

Difference Between StringBuilder and StringBuffer:

StringBuilder

StringBuffer

StringBuilder is mutable

StringBuffer is mutable

StringBuilder is unsynchronized

StringBuffer is Synchronized

StringBuilder is faster

StringBuffer is slower when compared to StringBuilder

NOTE: StringBuffer and StringBuilder does not Override equals() and hashcode()

When to use String, StringBuffer and StringBuilder?If our string is not going change, We use String.
If our string can change and accessed only from single thread, We can use StringBuilder.
If our string can change and can be accessed from multiple threads, We can use StringBuffer.

Difference between == and Equals()

== : Will check if the address of the values are same and NOT the values itself

Equals(): Will check if both the values are equals

Example:

String S1 = “Java”, String S2 = “Java”
S1==S2 will be True

String S1 = new String(“Java”), String S2 = new String(“Java”)
Here S1 == S2 will be false, But S1.equals(S2) will be true