wood burning stoves 2.0*
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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: 18541
    
    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: 38039
    
  22
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 . . . "
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Exceptions program not working as expected
 
Similar Threads
illegal start of expression when declaring method that throws an exception
Try,Catch
Exception not being caught
Stuck on exercise 5.4 from Sierra/Bates book, please help
NetBeans passing entry parameter for main