File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why this ?

 
Mahtab Alam
Ranch Hand
Posts: 391
1
Java MySQL Database PHP
  • 0
  • 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: 4549
8
Java Netbeans IDE Scala
  • 0
  • 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
  • 0
  • 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: 4549
8
Java Netbeans IDE Scala
  • 0
  • 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 .
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic