wood burning stoves*
The moose likes Beginning Java and the fly likes Exceptions program not working as expected Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Exceptions program not working as expected" Watch "Exceptions program not working as expected" New topic
Author

Exceptions program not working as expected

Sami Devine
Ranch Hand

Joined: Jan 30, 2011
Posts: 44
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
Bartender

Joined: Oct 14, 2005
Posts: 18993
    
    8

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

Joined: May 02, 2011
Posts: 54

your code is valid with the exception that you are not comparing strings properly....research that and your code should work fine.


SCJA 6 (Studying for SCJP 6)
Sami Devine
Ranch Hand

Joined: Jan 30, 2011
Posts: 44
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

Joined: Jan 30, 2011
Posts: 44
Thanks Jared, fixed it now
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40064
    
  28
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 . . . "
 
Don't get me started about those stupid light bulbs.
 
subject: Exceptions program not working as expected