This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exceptions program not working as expected

 
Sami Devine
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi for the following program, when I run the program as java MyEx1 Tuna, I do not get the expected exception. Looks like the IF part of the code is not executed.

 
Paul Clapham
Sheriff
Pie
Posts: 20958
31
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I expect you mean "Looks like the IF part of the code evaluates to false", right?

Which it does. When you compare two objects with the == operator, it only evaluates to true if the two objects are the same object. It's possible for two different strings to contain the same sequence of characters, even they are different objects. If you want to test for that condition -- and you do -- you should use the equals() method to do that.
 
Jared Malcolm
Ranch Hand
Posts: 54
Java MySQL Database PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
your code is valid with the exception that you are not comparing strings properly....research that and your code should work fine.
 
Sami Devine
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul, Thanks. I changed the IF.



== compares references and equals() compares values. I should have remembered this for Strings. Thanks again
 
Sami Devine
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jared, fixed it now
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It might have been better to use the equalsIgnoreCase method.

It is not a good idea to put print statements inside a constructor, unless under the justification "I just wanted to see what happens if . . . "
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic