aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why this ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Why this ?" Watch "Why this ?" New topic
Author

Why this ?

Mahtab Alam
Ranch Hand

Joined: Mar 28, 2012
Posts: 261

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
}
}


Oracle Java Programmer , Oracle SQL Expert , Oracle Java Web Component Developer
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4392
    
    8

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

Joined: Feb 26, 2013
Posts: 158
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

Joined: Apr 06, 2010
Posts: 4392
    
    8

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
 
subject: Why this ?