File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Java Strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Java Strings" Watch "Java Strings" New topic

Java Strings

ganesh pol
Ranch Hand

Joined: Apr 29, 2005
Posts: 151
what is difference betwn
String st1="st";
String st2=new("st");
i was try to compare with ==
but st1==st2 do not point to same object
what is mean by string object created at runtime and compile time
Henrik Engert
Ranch Hand

Joined: Apr 26, 2005
Posts: 70

I think by using String t = new String("Test") it does the following: "the newly created string is a copy of the argument string"

So therefore you can't compare the follwing by using the == operator:

String t1 = new String("Test");
String t2 = new String("Test");

They are pointing to two different Objects so therefore you need to use the String.compareTo() method.

By using String t = "Test" and String t2 = "Test" you will be able to say:

if(t == t2)
return true;

I am not an expert on this, so I am still learning.

Somebody else should be able to explain it in more detail I hope, or correct me if I am wrong.


Edwin Keeton
Ranch Hand

Joined: Jul 10, 2002
Posts: 214

If you only want to know if two strings are the same, use String.equals(), which returns a boolean. String.compareTo() does a lexigraphical comparison ( which is more costly) and returns an int signifying the lexical ordering (which is zero when the compared strings are equal according to the String.equals() method)

Use the '==' comparison operator when you want to know if two reference variables "point" to the same object.

String literals are created at compile time (in a special area of memory) so that the same literal strings point to the same String object.

is true.

Using the new operator creates a new String object at runtime (on the heap) which is not the same object as the same sequence of characters created at compile time.

Here "same object" generally speaking means a reference to the same location in memory.

Henrique Sousa
Ranch Hand

Joined: Apr 29, 2004
Posts: 92
(explaining in a different way and adding the intern() method)
There is a String pool in the VM which stores every literal String used in the program. So, let's say you have

literal and reference are two different object handlers, so the == operator will return false. But there is the intern() method, which returns a reference to the String pool, so

Check String.intern() javadoc for further explanation.
[ April 29, 2005: Message edited by: Henrique Sousa ]

Henrique Sousa<br />SCJP 1.4<br /> <br />All men die, not all men really live - Braveheart, 1995
I agree. Here's the link:
subject: Java Strings
It's not a secret anymore!