• Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem: String != String  RSS feed

 
Stefan Müllerheim
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why for god's sake i get a 'false' for that?



 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't use == for string comparison - use equals instead.
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Strings are Objects, and like any object you should use the .equals() method to compare equality:



The == operator compares identity = if the two Strings are the same Object, not if their contents are equal. Assuming a.getClass().getPackage().getName() is supposed to return "java.util" then you show the two Strings are not the same Object even if they have the same contents.
 
Stefan Müllerheim
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you for your quick answer!

your answer is in deed my solution.

but why is the answer of



output: class java.lang.String?

don't complain that 'a' is a String?

 
Guido Granobles
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This whole statment is returning a String object

Because of that you got that result.
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because when you print something it will call toString() on it. (And I don't know why it would complain that "a" is a string anyway; it wouldn't matter one way or the other, as long as it was an object.)
 
Gupta Tarun
Greenhorn
Posts: 22
Hibernate MyEclipse IDE Postgres Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Compare the output of following two statement :




Then read a little about String literal and String literal Pool.
here

I am almost sure you will get a good insight of why it is so.

Regards
Tarun
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!