How many objects will be created?
String a = new String("Examveda");
String b = new String("Examveda");
String c = "Examveda";
String d = "Examveda";
String a = new String("Examveda");
String b = new String("Examveda");
String c = "Examveda";
String d = "Examveda";
A. 4
B. 3
C. 2
D. None of this
Answer: Option B
Solution(By Examveda Team)
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.
Join The Discussion
Comments ( 3 )
In Java, which class is used to represent a sequence of characters as a string?
A. String
B. StringBuilder
C. StringSequence
D. StringArray
What is the correct way to create a new empty String object in Java?
A. String emptyString = "";
B. String emptyString = new String();
C. String emptyString = " ";
D. String emptyString = null;
E. Both A and B
Which of the following methods is used to compare two strings for equality in Java?
A. equals()
B. compareTo()
C. equalsIgnoreCase()
D. compare()
First line will create 2 objects- 1 in pool and 1 in heap ------------>2
Second line will create - 1 in heap, pool already has same object ---->1
third and fourth line will refer to existing pool object --->0
so total 2+1=3
If there is a String a ,String B and String C= A+B how many objects are created in memory?
In the case of String, String a = new String("Examveda");
2 objects will be created .
So answer should be 2 +2+ 1 = 5 i.e. None of these as per options