aspose file tools*
The moose likes Java in General and the fly likes Using the String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Using the String" Watch "Using the String" New topic
Author

Using the String

Rakesh Mehra
Ranch Hand

Joined: Nov 20, 2007
Posts: 31
What is the diference between a String Literal and String Object?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14273
    
  21

A string literal is text enclosed in double quotes in your source code.
A String object is an object of type String.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Rakesh Mehra
Ranch Hand

Joined: Nov 20, 2007
Posts: 31
Originally posted by Jesper Young:
A string literal is text enclosed in double quotes in your source code.
A String object is an object of type String.



Ok i too visualize same(as stated by u).But then

String s = new String("abcdef");.......(A) // creates a string object.
String s = "abcdef";....................(B) //string literal.

why is it said that both (A) and (B) create a new String object, with a
value of �abcdef �, and assign it to a reference variable s.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39436
    
  28
Strings are peculiar in Java. They are immutable, and they have another strange bit of behaviour.

You have actually created two String objects in that bit of code. A String literal is a String object too.

This has a String whose value is "abcdef". This is a String object, and because you have written out its value in full, it is called a String literal. Then, you use the new operator to create a new object, which is another String. It happens to have the same value. So at this point your memory contains two String objects

The next bit of code uses a String literal with the value abcdef. You have declared the same variable twice, so that bit won't compile. Let's change it to readNow, the compiler or the JVM goes through the code and sees abcdef. It thinks to itself, "I have seen that before," and lo and behold, there is "abcdef" in memory. So it uses that abcdef again. So what it does is to add a reference s2 to "abcdef". Now you have this situation:Two String objects, both with the value abcdef.

Try this little class. When you get == it shows that the two references point to the same object.That will show you which references are "equal" to each other, and which are duplicate references to the same object. You don't need s1 == s2 AND s2 == s1 because they give exactly the same result.

[edit]Added s4 as a field[/edit]
[ December 21, 2007: Message edited by: Campbell Ritchie ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Using the String