• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java Strings

 
ganesh pol
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is difference betwn
String st1="st";
and
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
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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.

Thanks
 
Edwin Keeton
Ranch Hand
Posts: 214
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic