• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Why this ?

 
Ranch Hand
Posts: 391
1
MySQL Database PHP Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
}
}
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Whizlabs Java Support
Posts: 158
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 .
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic