Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Stack Help...  RSS feed

 
Kim Vue
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've push a string onto a stack. I want to pass the top element as a parameter. I use string = stack.peek() followed by a conditional statement if(string == "a") someMethod(string), but the conditional statement seems to always be false and the method call never gets executed. Your suggestions will be appreciated. Thank you. Kim
[ November 20, 2003: Message edited by: Kim Vue ]
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you probably want to use the .equals() method. this is a common error every java programmer has made.
If you want to see if your variable on the stack points to the same memory location (something you almost never want to do), then the "==" is correct. but you probably want to test if the string on the stack is the same set of characters.
so
 
Joe Ess
Bartender
Posts: 9428
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(aString == bString ) is not the same as (aString.equals(bString)). The first compares the object references and returns true only if aString and bString point to the same instance of data. The second returns true if aString and bString are different object but containing the same data. The following code is not good programming style, but illustrates the point:

However, if aString and bString point to the same instance of a String:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!