Now Time to Answer my First Challenge Question. So I asked how many objects were created?
Code://Consider that a class is already created.
String s = new String("abc");
String s1="abc";
String s2= new String("abc");
Now the Answer:
Total Objects will be 3.
Now the reason, How?
A. So First line of code has "new String". This will create an Object in the Heap Memory. But then the JVM will realise that it is a String, so it will create another Object in String Constant Pool and then the Garbage Collector will remove the Object that was created in Heap and "s" will be assigned to String Constant Pool Object.
Now the second Statement.
It will refer to the same Object like "s" string.
Now the third Statement.
It will again create a new Object of "s2" in Heap. But then it will create another object in String Constant Pool(But the Object "abc" is already created so it will also refer to it and no new Object will be Created in String Constant Pool). and then Garbage Collector will remove the Object present in Heap.
Now You Know the Solution. Q& A's are All Welcomed.
No comments:
Post a Comment