This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line! See this thread for details.
String s = new String("string"); //creats 2 String Objects, the string literal "string" and a new object String with also the valuse "string" String s = "string"; // only creats one String object "string" [b]IF[b] one doesn't already exist in the string pool HTH
Hi Richard- There are several posts on the site that speak to this in greater detail. Effectively a String literal is created when you define a new string. This goes into a pool of strings that the compiler maintains. If the string already appears in the pool, it doesn't create a new one by simply uses the existing String. Thus since Strings are objects, if you define a String that already exists in the pool, a reference to this existing object is returned. In your example,
If "Text" has already been defined then a reference to the existing literal ius returned. Otherwise "Text" is created.
does the same thing. Now if you were to put these two lines together with different variables
Then s1 and s2 would reference the same Object however
would reference two different objects since your second line tells the compiler to explicitly create a new String called "Text". Search the board for other discusison on this, it's where I learned it. Cheers, John
John Pritchard<br />If a JTree falls in the woods, is it Observable
Originally posted by Richard Teston: Hi, I just wanted to know what is the difference between String s = new String("Text"); and String s = "Text"; ?
Hi Rich, This is an important topic to get to know well. ......... String a = "java"; //allocated at compile time String b = "java"; //allocated at compile time String x = "ja"; // at compile time String y = "va"; // at compile time String c = x + y; // concatinating 2 Strings // at RUNTIME now a==b is true because a and b point to same string in memory. c==a or c==b is NOT true because the concatination operator results inthe creation of a NEW object (even though the contents are the same!). if you did c.equals(a); you'd get true. [ November 29, 2002: Message edited by: david eberhardt ]
Joined: Jul 02, 2002
According to "Mike Meyer's Certification Passport Java 2" - when you use String s = "java"; you are creating a String object using a String literal. This causes the compiler to search the "string constant pool" so that any existing strings that are exactly the same can be reused with the new reference s. If you use an explicit construction like String s = new String("java"); you get a totally new and distinct object, even IF one already existed in the string constant pool that matched.