2

How many objects will get created for the piece of code shown below?

String str1 = new String("nitesh");
String str2 = new String("nitesh");
String str3 = "nitesh";
String str4 = str3;
String str5 = str2;
almightyGOSU
  • 3,731
  • 6
  • 31
  • 41

4 Answers4

4
  String str1 = new String("nitesh");
  String str2 = new String("nitesh");
  String str3 = "nitesh";
  String str4 = str3;
  String str5 = str2;

  TreeSet<Integer> set = new TreeSet<Integer>();

  set.add(System.identityHashCode(str1));
  set.add(System.identityHashCode(str2));
  set.add(System.identityHashCode(str3));
  set.add(System.identityHashCode(str4));
  set.add(System.identityHashCode(str5));

  System.out.println(set.size());

  // => 3

The three objects are:

  • "nitesh" created during compilation
  • two distinct objects created by String constructor.
Amadan
  • 191,408
  • 23
  • 240
  • 301
0

3 Objects (Wrong Answer). "Well, correct number, but wrong explanation".

String str1 = new String("nitesh"); // Creates a new String object
String str2 = new String("nitesh"); // Creates a new String object
String str3 = "nitesh";             // Creates a new String object
String str4 = str3;                 // Holds the same reference as str3
String str5 = str2;                 // Holds the same reference as str2

Seems like the third line does not create a new String object, my bad.
I will go try it out in an IDE in the meantime..

Just keeping the answer here for now, for the sake of the constructive comments going on below.

Seems like the right explanation for 3 Objects will be something along the line of..

First line creates 2 objects, 1 on the heap and 1 within the String pool?
Second line creates 1 object on the heap.

almightyGOSU
  • 3,731
  • 6
  • 31
  • 41
  • 1
    `String str3 = "nitesh";` does **not** create a new object. – PM 77-1 Dec 10 '14 at 04:49
  • Really? Aren't new String(...) and "..." both valid ways of declaring strings? – almightyGOSU Dec 10 '14 at 04:50
  • but for str1 : 2 objects will get created one in heap and another one in pool . please correct me if i am wrong – Nitesh Bagri Dec 10 '14 at 04:52
  • @PM77-1 Care to explain why? – almightyGOSU Dec 10 '14 at 04:54
  • The object already exists in String Cache, so it will be used. – PM 77-1 Dec 10 '14 at 04:55
  • 2
    `"nitesh"` in the first line creates a new object (and `String(...)` creates another one). Or rather, you could say that the first object exists since compilation, and is not created by any single line in the code. `String str3 = "nitesh"` in the third line reuses that same first object, does not create anything. – Amadan Dec 10 '14 at 04:57
  • @azurefrog: He is not saying the count is wrong, he is saying that literally no object creation is going on in line 3's compiled code. (See my ninja edit above, original phrasing was unclear) – Amadan Dec 10 '14 at 05:00
  • So what would be a good way to test for the 'actual count' of objects created? I assumed it was a easy question, but this seems to go way beyond my Java knowledge. – almightyGOSU Dec 10 '14 at 05:03
  • @Amadan Ah, good point. I see what you're saying. Two are created in the first line, one in the second, none in the third. – azurefrog Dec 10 '14 at 05:03
-2

Yes 3 Objects will be created.

1) String str1=new String("nitesh"); // String object "str1" is created

2) String str2=new String("nitesh"); // String object "str2" is created

3) String str3="nitesh"; // String object "str3" is created

String str4=str3; // Will not be created a new object; But will hold the value of "str3"

String str5=str2; // Will not be created a new object; But will hold the value of "str2"

  • Nonono... `str3` is a new variable, but is not a new object created by the 3rd line. – Amadan Dec 10 '14 at 05:01
  • @Amadan String is a class in Java. It is not a primitive type variable in Java. It IS an object. Refer to: https://docs.oracle.com/javase/tutorial/java/data/strings.html – gprathour Dec 10 '14 at 05:07
  • @GPRathour But the third line doesn't create anything. In the first line, first "nitesh" is created as a string literal, then that is passed in to the `String` constructor. Two objects have been created at this point. Later in the third line, `str3` is assigned the value of the string literal, but no objects are created. see the [difference between string object and string literal](http://stackoverflow.com/questions/3297867/difference-between-string-object-and-string-literal). – azurefrog Dec 10 '14 at 05:10
  • @GPRathour: `"nitesh"` is an object. `str3` is not, its contents is, and it is not created on line 3. – Amadan Dec 10 '14 at 05:10
  • @azurefrog I know this thing. Thanks. But I saw some misunderstanding arising here like if we write `String a = "Hello"` then no object will be created. However in this case a new object won't be created. – gprathour Dec 10 '14 at 05:15
  • @Amadan It even applies to `String str1 = new String("nitesh")` Here the string object is created with `new String("nitesh")` having value `"nitesh"` and `str1` is just a reference variable. It is also not an object. – gprathour Dec 10 '14 at 05:17
  • Yes. But in most cases it is just sloppy terminology, excusable as long as you're making otherwise sound claims. `new String("nitesh")` does indeed create a new object (and then assigns it to `str1`). No object creation is being performed on the 3rd line. – Amadan Dec 10 '14 at 05:18
-2

Actually 2 objects. str1 and str2 hold object references. While str3, str4 and str5 do not hold string objects but are string literals.

In your example,str1 and str2 point to different objects in the Java String Pool. These strings, if mutated, will still point to same memory locations where they pointed before getting mutated.
Though these string object cannot be mutated directly by using the = operator, as strings in java are immutable, but stringbuffer objects can be made using the string object and then that string buffer object can be mutated with the help of methods in java.lang.StringBuffer class.

But if str3, str4 and/or str5 are mutated, ie. if you do this somewhere later in the code:

str3="narendra modi";

A new memory location will be reserved in the java heap and not the java string pool, with the string "narendra modi" stored in it and str3 will point to it. While str4 and str5 will still be pointing to location where the string "nitesh" is stored.

Citation added: string buffers CAN be mutated...

https://icl.googleusercontent.com/?lite_url=https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html&ei=25w3utEc&lc=en-IN

Aditya Singh
  • 2,343
  • 1
  • 23
  • 42
  • Java Strings (objects) are **immutable**. Noting stops you from reassigning reference variables (unless declared as final). – PM 77-1 Dec 10 '14 at 05:10
  • Yes they are immutable. Thats what i meant by my answer. I clearly mentioned they can be mutated only by methods. And jot directly – Aditya Singh Dec 10 '14 at 05:12
  • String objects **cannot** be mutated. Period. – PM 77-1 Dec 10 '14 at 05:14
  • Read the answer properly. Thats what I said. – Aditya Singh Dec 10 '14 at 05:14
  • 1
    I read the answer properly too, and it's still wrong. `=` never changes an object, only a reference (except when reference is a part of a larger object). And methods will return new `String` objects, never change an existing one. – Amadan Dec 10 '14 at 05:15
  • You said: "*but can be mutated (as in, values can be changed within the same memory locations)*". Plain wrong. – PM 77-1 Dec 10 '14 at 05:16
  • Ahh man. Thats what I said. Strings cannot be mutated with an `=` operator. What are you trying to say? Ok. And what would happen if stringbuffer class methods are used on the object? Will it create a new object in the string pool? – Aditya Singh Dec 10 '14 at 05:20
  • @Aditya: I think you are confused about the difference between a variable and an object. You can't use `StringBuffer` methods on anything that is not a `StringBuffer`. If you do `str3="narendra mori"`, you changed a variable reference to point at a new `String` object; the original `"nitesh"` object has not been mutated, it is just refered to by one less variable. Also, your citation is irrelevant, since you claimed that `String` objects are mutable. `String` and `StringBuffer` are two different classes. – Amadan Dec 10 '14 at 05:26
  • Did you really read my answer? The second last line? Before the citation? Thats exactly what i said.`str4 and str5` still point to "nitesh". But `str3` points to a different location now. – Aditya Singh Dec 10 '14 at 05:28
  • And a stringbuffer can be created out of a string. Ofcourse at a new memory location. – Aditya Singh Dec 10 '14 at 05:29
  • And coffee can be made out of coffee beans, but most people don't drink coffee beans every day. They are different things. You cannot mutate Java `String` objects. You can make a `StringBuffer` object by passing its constructor a `String`, then you can mutate a `StringBuffer`. `String` objects cannot ever be mutated. They are immutable. No mutation is being done on `String` objects. You are arguing with us that `String` objects are mutable, but they are not. – Amadan Dec 10 '14 at 05:31
  • I read it: "strings in java are **immutable**, but can be mutated". Anything after is irrelevant but correct explanation to stubbornly justify a sentence that is wrong. Instead of adding a bunch of explanations, why not admit you're wrong and change the one sentence that is actually the problem? *smh* – Amadan Dec 10 '14 at 05:36
  • You mean you say, the reader wont read after "they can be mutated"? – Aditya Singh Dec 10 '14 at 05:37
  • Oh ok. I got what you said and i rectified my mistake. Thanks for spotting that out. – Aditya Singh Dec 10 '14 at 05:41
  • Thank you. However, there are other problems here: "do not hold string objects but are string literals" is also factually wrong (a literal is a feature of source code; during execution, the three variables indeed hold `String` objects, as you can check by `str3.class`, for example, or calling any methods on them). You still talk about "these strings, if mutated"... which cannot happen. And literals create `String` objects at compile time, constructors at execution time, but both are equally objects. And finally, the correct answer is "3 objects", as you can see from my answer and others. – Amadan Dec 10 '14 at 05:46