Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why this ?

 
Mahtab Alam
Ranch Hand
Posts: 391
1
Java MySQL Database PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When i run this program with command Line argument A it prints false for third comparison.

class Why
{
public static void main(String args[])
{
String s="A";
System.out.println("A"=="A"); // true
System.out.println("A"==s); //true
System.out.println("A"==args[0]); //false
}
}
 
Matthew Brown
Bartender
Posts: 4565
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're using == to compare Strings, which you should never do. Sometimes it will behave as you expect because of various internal optimisations (which is what you're seeing on the first couple of lines), but not always. Use the equals() method instead.

There's more detail in our FAQ at AvoidTheEqualityOperator.
 
James X Peterson
Whizlabs Java Support
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Matthew Brown,

== operator will compare reference not the content.so if you want to compare the content you need to use equals() method.

Regards,
James.
 
Matthew Brown
Bartender
Posts: 4565
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
James Peterson wrote:Hi Matthew Brown,

== operator will compare reference not the content.so if you want to compare the content you need to use equals() method.
Yes, I know. I wasn't the one asking the question .
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic