Hi guys , please look here . Consider code segment

String a=new String("SMS Message");
String b=new String("SMS Message");
if(a==b)
System.out.println("they are equal");

i) why it does not generate an output ?
ii) how can we rewrite the program such that it will print the output ?

a and b are reference variables. The == operator for references tests if those two references are equal - ie that they both refer to the same object.

Read the API doc for the String class, specifically its equals method.

String a=new String("SMS Message");

this line means that you reserved a memory pointed by a and has the value "SMS Message". So when you say if(a==b), you are comparing the addres of the memory (like JamesCherrill said). But what you want to do is to compare the value of this memory so you use the "equals" method

a.equals(b);

hope this help.

Hi hannahaddad
There is nothing wrong with your post, but please be aware when answering Ermina. He/She has a history of posting homework questions and expecting someone to provide the answer, and doesn't seem to want to do any work (eg: didn't bother to follow up the API reference that I gave above).
Just providing complete answers isn't going to help him/her develop a constructive attitude to learning Java

Hi JamesCherrill

I was just trying to make it more clear to the poster. But you are certainly on right. It's like giving a fish instead of teach how to fishing. I will be careful for the next time.
regards.

rather, the value assigned to the variable.

??? the variables are reference variables, and their values are references, so the original comment about comparing the values that the references refer to seems right to me... or did you have something else in mind?

Edited 2 Years Ago by JamesCherrill

This question has already been answered. Start a new discussion instead.