String conflict questions-answer


1.

public class Main
{
    public static void main (String[] args) {
        String s=new String("ABC");
        String s1="ABC";
        String s2=new String("ABC");
    }
}


How many Objects will be created over here ?


solutions:
--------------

Here Objects will be created


Explanation :

***In first line as we are using new() ,then first time object will be created in heap.

***In second line when we are creating string using string literal then for the first time object will be created in the String Constant Pool.

***In 3rd  line we are using new() to create the same string ,but as per source below each time we use new() then a new object is created in heap .So 2nd object is created in heap

Sum total in 1st line 1 object is created in heap , the second object is created in the SCP as per second line and the 3rd object is created in the heap as per 3rd line.


Source:

As per the source 

https://www.java67.com/2014/08/difference-between-string-literal-and-new-String-object-Java.html


Whenever we create a String using new() ,then jvm forces to create a new object every time.



But in String literal ,There is a concept of String Constant Pool .When ever we create a string using string literal ,then the string constant pool will be checked.If the string exists already the reference of that string will be returned .No new object is created .If it is not there previously ,a new reference will be created 1st time.


For the best clarity ...
Source is :

https://www.edureka.co/blog/java-string-pool/

Comments

Popular posts from this blog

Java Interview Preparation (conceptual)

Git Commands With Output Log

Java 8 Function Interface