How many objects will be created? String a = new String("Examveda"); String b = new String("Examveda"); String c = "Examveda"; String d = "Examveda";

How many objects will be created? String a = new String("Examveda"); String b = new String("Examveda"); String c = "Examveda"; String d = "Examveda"; Correct Answer 3

Answer: Option 2

Object will be created each time whenever we use new keyword. So, 2 object will be created simply for the first two line and matter is with remaining two bottom line. String c="examveda" creates an object and store it in String pool, next time when we are writing String d="examveda" it will first check in String pool whether object already exists or not. Since, it is existing, no new object will be created. Hence reference "d" points to existing object "examveda". So ultimately 3 object will be created at the end.

Related Questions

What will be the output when the following program is compiled and executed? abstract class TestAbstract{ String my_name; String myName(){ my_name = "Examveda"; return my_name; } abstract void display(); } public class Test extends TestAbstract{ void display(){ String n = myName(); System.out.print("My name is "+ n); } public static void main(String args[]){ Test t = new Test(); t.display(); } }
What happens if the following program is compiled and executed? interface MyInterface{ void display(); } interface MySubInterface extends MyInterface{ void display(); } public class Test implements MySubInterface{ public void display(){ System.out.print("Welcome to Examveda."); } public static void main(String args[]){ Test t = new Test(); t.display(); } }