7

When creating a String in Java, what is the difference between these two:

String test = new String();
test = "foo";

and

String test = "foo";

When do I need to use the keyword new? Or are these two basically the same and they both create a new String object?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
itoilet
  • 71
  • 1
  • 4
    String test = new String(); -> creates a new instance of String, which you 'll never use again, since you reassign your variable test to "foo", meaning the '= new String()' assigning is pointless – Stultuske Apr 11 '19 at 06:11
  • 2
    @ernest_k it's not really a duplicate of that thread. He's doing two seperate assignings in his one example, not one assigning using an overloaded constructor of String – Stultuske Apr 11 '19 at 06:12
  • @Stultuske Right. I've reopened. – ernest_k Apr 11 '19 at 06:37
  • Check out https://stackoverflow.com/questions/14757978/new-string-vs-literal-string-performance/14758013 or http://www.java67.com/2014/08/difference-between-string-literal-and-new-String-object-Java.html – eol Apr 11 '19 at 06:40
  • @eol they show the difference between myString = "text"; and myString = new String("text"); which is not the same as the question – Stultuske Apr 11 '19 at 06:43
  • 1
    Don't check out stackoverflow first if you're a beginner. Check out the Java Tutorials of Oracle: https://docs.oracle.com/javase/tutorial/java/data/strings.html – the hand of NOD Apr 11 '19 at 06:44
  • @Stultuske: Yeah, you're right thx. – eol Apr 11 '19 at 06:53
  • 1
    Questions like this always brush up your fundamentals :) – Vishwa Ratna Apr 11 '19 at 06:59
  • Possible duplicate of [What is the Java string pool and how is "s" different from new String("s")?](https://stackoverflow.com/questions/2486191/what-is-the-java-string-pool-and-how-is-s-different-from-new-strings) –  Apr 11 '19 at 11:28

3 Answers3

4

In the first snippet, you create a new empty string, and then immediately overwrite it with a string literal. The new string you created is lost, and will eventually be garbage-collected.
Creating it is pointless, and you should just use the second snippet.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

new String() will create a new instance of the object string with an own identity hash code. When creating a string like this String string = "myString"; Java will try to reuse the string by searching the already created string, for that exact string. If found, it will return the same identity hash code of this string. This will cause, that if you create e.g. a identity hash code of the string, you will get the same value.

Example:

public class Stringtest {
   public static void main(String[] args) {
      final String s = "myString";
      final String s2 = "myString";
      final String otherS = new String("myString");

      //S and s2 have the same values
      System.out.println("s: " + System.identityHashCode(s));
      System.out.println("s2: " + System.identityHashCode(s2));

      //The varaible otherS gets a new identity hash code
      System.out.println("otherS: " + System.identityHashCode(otherS));
   }
}

In most cases you don't need to create a new object of a string, cause you don't have static values when working with e.g. HashMaps or similar things.

So, only create new strings with new String when really needed. Mostly use String yourString = "...";.

Marvin Klar
  • 1,869
  • 3
  • 14
  • 32
0

Here's a sample program to help you understand how strings work in Java.

import java.util.Objects;

public class TestStrings {

    public static void main(String[] args) {
        String test = new String();
        System.out.println("For var test value is '"+ test+ "' and object identity is "+ System.identityHashCode(test));
        test = "foo";
        System.out.println("For var test after reassignment value is '"+ test+ "' and object identity is "+ System.identityHashCode(test));
        String test2 = "foo";
        System.out.println("For var test2 value is '"+ test2+ "' and object identity is "+ System.identityHashCode(test2));
        String test3 = new String("foo");

        System.out.println("For var test3 value is '"+ test3+ "' and object identity is "+ System.identityHashCode(test3));
    }
}

Run this to see what happens for the identity Hash code printed for variables test, test2 and test3.

Basically Java tries to optimize how strings are created when they are created as literals. Java tries to maintain a pool of strings and if you use the same literal again it uses the same object from this pool of strings. This can be done because Strings in java are immutable.

You can read further on this at this question What is Java String interning?

Yogesh_D
  • 17,656
  • 10
  • 41
  • 55