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.

I dont understand

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.

But what you want to do is to compare the value of this memory

rather, the value assigned to the variable.

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?

merely a remark that the description of "the memory" was pretty vague :)

answer: simply add an else clause to your if statement to print something if the two are not equal ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.