2

Suppose we create a String s as below

String s = new String("Java");

so this above declaration will create a new object as the new operator is encountered.

Suppose in the same program if we declare a new String s1 as below :

String s1 = "Java";

Will this create a new object or will it point to the old object with Java as it is already created with new operator above.

Buntylm
  • 7,345
  • 1
  • 31
  • 51
Bhargav
  • 43
  • 1
  • 2
  • 13
  • This question appears to be off-topic because it is about lack of self testing. – Hanky Panky Oct 19 '13 at 08:08
  • 1
    @Hanky웃Panky: I disagree. Testing could have shown that the variables had different values - but it would have been harder to see that the second statement *doesn't* actually create a new object. – Jon Skeet Oct 19 '13 at 08:25

5 Answers5

8

Well, the second line won't create a new object, because you've already used the same string constant in the first line - but s1 and s will still refer to different objects.

The reason the second line won't create a new object is that string constant are pooled - if you use the same string constant multiple times, they're all resolved to the same string. There still has to be a String object allocated at some point, of course - but there'll only be one object for all uses. For example, consider this code:

int x = 0;
for (int i = 0; i < 1000000; i++) {
    String text = "Foo";
    x += text.length();
}

This will not create a million strings - the value of text will be the same on every iteration of the loop, referring to the same object each time.

But if you deliberately create a new String, that will definitely create a new object - just based on the data in the existing one. So for example:

String a = new String("test");
String b = new String("test");
String x = "test";
String y = "test";
// Deliberately using == rather than equals, to check reference equality
System.out.println(a == b); // false
System.out.println(a == x); // false
System.out.println(x == y); // true

Or to put it another way, the first four lines above are broadly equivalent to:

String literal = "test";
String a = new String(literal);
String b = new String(literal);
String x = literal;
String y = literal;
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • If `String myString = "Java";` doesn't create a new object then am I free to define infinite references, `String s1 = "Java1";` `String s2 = "Java2";` etc., to String literals without having created any objects? – iamreptar Oct 19 '13 at 08:17
  • @iamreptar: No, it only doesn't create a new object because of the previous statement which already referred to the same string. I'll edit that in. – Jon Skeet Oct 19 '13 at 08:17
  • I have one additional question: When writing test code for this thread, my first approach was comparing the string literal's hashcode to the string object's hashcode (s1="Java", s2=new String("Java")) and s1.hashcode()==s2.hashcode() results in "true". That puzzles me. I expected it to be false. – Thomas Junk Oct 19 '13 at 08:21
  • 1
    @Lilith2k3: Why? The hash code is based on the *content* of the string, and those two strings have the same content. Look at the documentation for `String.hashCode` for details of how it's computed. – Jon Skeet Oct 19 '13 at 08:22
  • Okay, creating many references to the same string literal doesn't create new objects but what about references to unique string literals? If I create a reference to a different string literal then is the new string literal added to the pool? or was it taken from a pool that existed regardless of whether or not I use string literals in my program? – iamreptar Oct 19 '13 at 08:23
  • @iamreptar: No, there'd have to be an infinite number of such constants. If you use different constants, you'll end up with that many different strings in the string pool. – Jon Skeet Oct 19 '13 at 08:24
  • Therefore, `String myString = "Jerry";` **creates** a new object (which is a singleton). – iamreptar Oct 19 '13 at 08:26
  • Ah. Okay. My fault. I thought it to be some kind of unique identifier (never used it as that, but now I know that I never should :]). Thanks a lot! – Thomas Junk Oct 19 '13 at 08:27
  • 2
    @iamreptar: It *only* creates a string if that's the first time that constant has been used in the program so far. I think it would be clearer to say that it requires that string exists, and creates it if necessary. You can't point at that statement in the middle of a program and say "That statement creates a new object" in the same way that you could with `Object x = new Object();` – Jon Skeet Oct 19 '13 at 08:31
  • @JonSkeet String a = new String("test"); String b = new String("test"); String x = "test"; String y = "test"; to which object does x or y point to? Is it the one created by a or b? Or is it just random? – Bhargav Oct 19 '13 at 08:43
  • @user2131178: The values of `x` and `y` are references to the string in the constant pool - the same reference that was passed into the constructor used when initializing `a` and `b`. – Jon Skeet Oct 19 '13 at 08:55
  • @JonSkeet so for a and b two new objects are not created? – Bhargav Oct 20 '13 at 08:59
  • @JavaFan: Yes, for `a` and `b` they are because they're calling the constructor. – Jon Skeet Oct 20 '13 at 13:07
1
String myString = new String("Java");

creates two objects.

String myString = "Java";

creates one object.

iamreptar
  • 1,461
  • 16
  • 29
  • 1
    The latter statement doesn't in itself create an object. In particular, if you put that statement into a loop which runs a million times, there'll still only be a single object. – Jon Skeet Oct 19 '13 at 08:18
0

In order to create a new object we use new keyword, Object cannot be created without using new.

As per the declaration in the first instance a new Object is created but in the second instance you are only declaring a variable with a value.

So its not an Object.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
ammu
  • 9
  • 1
  • 1
    Various constructs create new objects without a `new` statement - autoboxing for example, and execution-time string concatenation. If you're suggesting that the string used in the second statement is "not an object" then that's *definitely* incorrect. (The value assigned to `s1` is a reference to a `String` object.) This answer is at best misleading, and potentially outright wrong depending on the meaning of your final sentence. – Jon Skeet Oct 19 '13 at 08:57
0

String s1="foo"; literal will be created in StringPool.

String s2="foo"; this time it will check "foo" literal is already available in StringPool or not as now it exist so s2 will refer the same literal as s1.

String s3=new String("foo"); "foo" literal will be created in StringPool first then through string arg constructor String Object will be created i.e "foo" in the heap due to object creation through new operator then s3 will refer it.

Vikas
  • 490
  • 4
  • 10
0

When you create a String with literal (e.g. String str = "Hello";) the Object is not created in Heap it will be available in StringPool only, however when you create a String using 'new' operator (e.g. String str = new String("Hello")) then the Object in StringPool is created along with one more object in Heap. So we are creating two objects unnecessarily. So string creating with literal is preferred way.

Vishal Akkalkote
  • 1,151
  • 12
  • 16