Project Management Professional: Core Java Interview Questions!

Tuesday, July 21, 2020

Core Java Interview Questions!

15.Why is String immutable in Java ?

Ans. 1. String Pool - When a string is created and if it exists in the pool, the reference of the existing string will be returned instead of creating a new object. If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.


Example -


String str1 = "String1";

String str2 = "String1"; // It doesn't create a new String and rather reuses the string literal from pool


// Now both str1 and str2 pointing to same string object in pool, changing str1 will change it for str2 too


2. To Cache its Hashcode - If string is not immutable, One can change its hashcode and hence it's not fit to be cached.


3. Security - String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Making it mutable might possess threats due to interception by the other code segment.


16.Difference between == and .equals() ? example in eclipse

"equals" is the method of object class which is supposed to be overridden to check object equality, whereas "==" operator evaluate to see if the object handlers on the left and right are pointing to the same object in memory.

x.equals(y) means the references x and y are holding objects that are equal. x==y means that the references x and y have same object.

Sample code:



No comments: