Java Forums

Main Menu
Home
Today's Posts
FAQ
Search
Contact Us

Java Network
Linux Archive
Java Tips
Java Tips Blog

Sponsored Links





Welcome to the Java Forums.

You are currently viewing our boards as a guest which gives you limited access to view most discussions and access our other features. By joining our free community, you will:

  • have access to post topics
  • communicate privately with other members (PM)
  • not see advertisements between posts
  • have the possibility to earn one of our surprises if you are an active member
  • access many other special features that will be introduced later.

Registration is fast, simple and absolutely free so please, join our community today!

If you have any problems with the registration process or your account login, please contact us.

Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 04-27-2008, 11:42 PM
Member
 
Join Date: Apr 2008
Posts: 34
kewlgeye is on a distinguished road
Try Catch block issues
I have this code and this code isn't displaying properly. It compiles, and then it asks the first question but when I press enter it just displays a blank line. and then I press enter again and it displays my program ending statement. What is wrong with this code? My responses are suppose to be only "y" or "n" and anything else is suppose to throw an exception or error returning the user back to the original question. I haven't figured that out yet.
Here is the Code:

Code:
import java.io.*; class ModifiedTest { public static void main(String args[]) throws IOException { BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); BufferedReader dataIn1 = new BufferedReader(new InputStreamReader(System.in)); String strInput; String strInput1; String strInput2; int intInput = 0; int intInput1 = 0; try { System.out.println("Do you like Rock Music?:"); strInput = dataIn.readLine(); //reads data from console System.out.println(); if (strInput == "n") { throw new TheException(); //calls } else if (strInput == "y") System.out.println("Do you like Marilyn Manson?:"); strInput1 = dataIn1.readLine(); //reads data from console System.out.println(); if (strInput1 == "n") { throw new TheException(); //calls } else if (strInput1 == "y") System.out.println("You are a hardcore Rocker"); } catch (TheException e) { System.out.println("" + e); } System.out.println(); System.out.println("Program Ending!"); } } class TheException extends Exception { public String toString() { return "How could you not like Marilyn Manson?"; } }
Bookmark Post in Technorati
Reply With Quote
Sponsored Links
  #2 (permalink)  
Old 04-28-2008, 04:27 AM
danielstoner's Avatar
Senior Member
 
Join Date: Apr 2008
Location: Canada
Posts: 191
danielstoner is on a distinguished road
Hello,

This is not a try/catch block issue. I guess you are a beginner to Java and maybe a beginner to programming. There are lots of problems with the code you presented:

- In Java you almost never compare strings with "==". There are a few situations but only used by people who know what they are doing. When you compare with "==" like in strInput == "y" you will always get a false no matter what the value of StrInput is. This is because you actually compare the references to those strings and they are almost sure to be different. To compare strings you should do something like "y".equals(strInput). This will do what you want comparing the actual string values.
- You are using exceptions for flow control. This is a technique that is always wrong. You should use plain if statements. You throw an exception instead of treating the "n" case in a normal way. On the other hand you don't treat all the other situations. What happens if I type "w"?
- As I said before throwing an exception and catching it in the same function is a mistake. I guess it is just an attempt to do flow control. It is better to do it with if. Keep in mind it is always better to use all the language features in the spirit they way designed.

And because by this point you may think I am a meanie here is a piece of code that works:

Code:
import java.io.*; class ModifiedTest { public static void main(String args[]) throws IOException { BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); String strInput; System.out.println("Do you like Rock Music?:"); strInput = dataIn.readLine(); //reads data from console if ("y".equals(strInput)) { System.out.println("Do you like Marilyn Manson?:"); strInput = dataIn.readLine(); //reads data from console if ("y".equals(strInput)) { System.out.println("You are a hardcore Rocker"); } else if ("n".equals(strInput)) { System.out.println("How could you not like Marilyn Manson?"); } else { System.out.println("Illegal input: " + strInput); } } else if ("n".equals(strInput)) { System.out.println("Ok, bye rock hater!"); } else { System.out.println("Illegal input: " + strInput); } System.out.println(); System.out.println("Program Ending!"); } }
For such an example you don't need exceptions. If you actually want to learn more about exceptions you can read my tutorial at Exceptional Java - Thoughts on Java exceptions | Little Tutorials
Enjoy
__________________
Daniel @ [
To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts.
]
Language is froth on the surface of thought

Last edited by danielstoner : 04-28-2008 at 04:29 AM.
Bookmark Post in Technorati
Reply With Quote
  #3 (permalink)  
Old 04-28-2008, 06:14 AM
sukatoa's Avatar
Senior Member
 
Join Date: Jan 2008
Location: Cebu City, Philippines
Posts: 527
sukatoa is on a distinguished road
Send a message via Yahoo to sukatoa
Quote:
When you compare with "==" like in strInput == "y" you will always get a false no matter what the value of StrInput is. This is because you actually compare the references to those strings and they are almost sure to be different.
Are you sure?

How about this,
Code:
String t1 = "a"; String t2 = "e"; String t3 = "i"; String t4 = "o"; String t5 = "u"; if(t1 == "a"){ if(t4 == "o"){ if(t2 == "e"){ if(t5 == "u"){ if(t3 == "i"){ System.out.println("Comparison successful"); } } } } }
__________________
A specific, detailed, simple, well elaborated, and "tested before asking" question may gather more quick replies. hopefully
To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts.
Bookmark Post in Technorati
Reply With Quote
  #4 (permalink)  
Old 04-28-2008, 06:52 AM
Eranga's Avatar
Moderator
 
Join Date: Jul 2007
Location: Colombo, Sri Lanka
Posts: 4,376
Eranga has a spectacular aura aboutEranga has a spectacular aura about
Send a message via Yahoo to Eranga
Quote:
Originally Posted by sukatoa View Post
Are you sure?
I have a doubt too. See the following simple code.

Code:
String str1 = "aba"; String str2 = "aba"; if(str1 == str2) System.out.println("Yes"); else System.out.println("No");
Still you got the output 'Yes' on it. But, this is not legal(may be for me ). Illegal not points that it is incorrect. So, why it is illegal?

Here what I know. == operator check that both objects are exactly the same. So, two strings may be different object, in a rare case even they have exactly the same characters. Isn't it?
__________________
Use an appropriate Subject. "Help, urgent!" isn't one.
To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts.

Has someone helped you? Then you can
To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts.
their helpful post.

Want to make your IDE the best?
To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts.

To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts.

To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts.
Bookmark Post in Technorati
Reply With Quote
  #5 (permalink)  
Old 04-28-2008, 04:11 PM
danielstoner's Avatar
Senior Member
 
Join Date: Apr 2008
Location: Canada
Posts: 191
danielstoner is on a distinguished road
Eranga and Sukatoa,

Sorry for not giving a full explanation above but here it is with code examples. First my statement above is correct. You both get true from your comparisons in the samples you posted because the compiler looks at constants like "abc" and since they are immutable it optimizes them by storing them only once. So no matter how many times you declare a String like "abc" it will most likely be created only once by the compiler. But this is not guaranteed behavior. Most modern compilers do this but not all of them. So you should not base your code on this kind of behavior because for sure it will break sooner or later. Here is a code sample that shows on most compilers how this works:

Code:
import java.io.*; public class StrCmpTest { public static void main(String[] args) throws Exception { String strInput = "y"; if (strInput == "y") { System.out.println("Yes"); } else { System.out.println("No"); } } }
In this case with most compilers and modern JVMs you get "Yes". But this is by chance.

If we get our String from the console from example, introduced by the user then we can see how this behavior might trick us. Run the next piece of code:
Code:
import java.io.*; public class StrCmpTest { public static void main(String[] args) throws Exception { BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Type y or n: "); String strInput = dataIn.readLine(); if (strInput == "y") { System.out.println("Yes"); } else { System.out.println("No"); } } }
Type "y" at the console and you will see how you get a "No" on the screen. No matter what you type you will get a "No".

Now replace the if/else block in the above code with:

Code:
if ("y".equals(strInput)) { System.out.println("Yes"); } else { System.out.println("No"); }
When you type "y" now you will get the right answer "Yes".
__________________
Daniel @ [
To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts.
]
Language is froth on the surface of thought
Bookmark Post in Technorati
Reply With Quote
  #6 (permalink)  
Old 04-28-2008, 04:19 PM
sukatoa's Avatar
Senior Member
 
Join Date: Jan 2008
Location: Cebu City, Philippines
Posts: 527
sukatoa is on a distinguished road
Send a message via Yahoo to sukatoa
Absolutely....
__________________
A specific, detailed, simple, well elaborated, and "tested before asking" question may gather more quick replies. hopefully
To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts.
Bookmark Post in Technorati
Reply With Quote
  #7 (permalink)  
Old 04-28-2008, 04:37 PM
sanjeevtarar's Avatar
Senior Member
 
Join Date: Apr 2008
Location: Delhi(India)
Posts: 251
sanjeevtarar is on a distinguished road
Quote:
Originally Posted by danielstoner View Post
Eranga and Sukatoa,

Sorry for not giving a full explanation above but here it is with code examples. First my statement above is correct. You both get true from your comparisons in the samples you posted because the compiler looks at constants like "abc" and since they are immutable it optimizes them by storing them only once. So no matter how many times you declare a String like "abc" it will most likely be created only once by the compiler. But this is not guaranteed behavior. Most modern compilers do this but not all of them. So you should not base your code on this kind of behavior because for sure it will break sooner or later. Here is a code sample that shows on most compilers how this works:

Code:
import java.io.*; public class StrCmpTest { public static void main(String[] args) throws Exception { String strInput = "y"; if (strInput == "y") { System.out.println("Yes"); } else { System.out.println("No"); } } }
In this case with most compilers and modern JVMs you get "Yes". But this is by chance.

If we get our String from the console from example, introduced by the user then we can see how this behavior might trick us. Run the next piece of code:

Code:
import java.io.*; public class StrCmpTest { public static void main(String[] args) throws Exception { BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Type y or n: "); String strInput = dataIn.readLine(); if (strInput == "y") { System.out.println("Yes"); } else { System.out.println("No"); } } }
Type "y" at the console and you will see how you get a "No" on the screen. No matter what you type you will get a "No".

Now replace the if/else block in the above code with:

Code:
if ("y".equals(strInput)) { System.out.println("Yes"); } else { System.out.println("No"); }
When you type "y" now you will get the right answer "Yes".


Hello Danielstoner,

You are saying the above behavior is by chance.....Nothing is by chance in Java.

"==" : Check for Memory References of Objects.
"equals()" : Check for data of Objects.

When you create a String Variable like :
Code:
String str = "abc";
Compiler creates it into Heap for memory utilization.
Next time when you same String Object with same string ... JVM will look into heap and will point it to the existing If Exist.

Code:
String str2 = "abc";
So when you compare with "==" Operator it will give true. Because memory references are same.

But If you create String Object like this :
Code:
String str = new String("abc"); String str1 = new String("abc");
It will always create New memory for the object, no matter it exist in pool or not.
When you compare these two by "==" operator it will always give "false".Because memory references are different.

And Now if take a case of Console.

Code:
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
You are always using "new" Operator and it will always create new memory space. So "==" Operator will always give you "false" because memory references are always different.
And when you use "equals()" it will check for contents. So it will return "true"

The behavior is not tricky it is same.




__________________
sanjeev,संजीव

Last edited by sanjeevtarar : 04-28-2008 at 04:42 PM.
Bookmark Post in Technorati
Reply With Quote
  #8 (permalink)  
Old 04-28-2008, 06:01 PM
danielstoner's Avatar
Senior Member
 
Join Date: Apr 2008
Location: Canada
Posts: 191
danielstoner is on a distinguished road
Hello Sanjeev

I agree that nothing is by chance in Java... or almost nothing What I want to actually make clear is that while the Java behavior is not by chance, if you use "==" to compare String instances your program's behavior is left to chance. When you are calling an API method that returns a String instance you might not know how the String instance was created. It could be created with "new" or it could be a reference to a constant. So depending on what the API implementor did your code might function as expected or not. In my opinion doing a deep comparison with equals() is safer as long as the classes actually overrides equals().
In theory you can protect yourself by using on all the String instances received from APIs the String.intern() call:
String (Java Platform SE 6)
But this is a bit clumsy and not a mainstream programming practice in Java. I am not even sure how many programmers actually know this method exists. And on top of that the method is native:
Code:
public native String intern();
This means it is actually JVM dependent and we cannot know what its implementation is. In my opinion the Java specification mandates String literals to be reused for optimization purposes. On the other hand all String instances created at runtime are not added to the string literal pool.
As a conclusion, in my opinion, while you can control everything in small examples when you write all the code, in real world coding situations when you use third party APIs and you don't know the source of your string instance, you are safer with using equals() than "==".
__________________
Daniel @ [
To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts.
]
Language is froth on the surface of thought
Bookmark Post in Technorati
Reply With Quote
  #9 (permalink)  
Old 04-28-2008, 11:26 PM
Member
 
Join Date: Apr 2008
Posts: 34
kewlgeye is on a distinguished road
To All:
Thank you all who have contributed to this post. Your explanations about each others coding is helping me to better understand Java.

danielstone your code worked well for me, however, I was also trying to use Try Catch statements for anything other than "y" or "n" And your statements are only if else statements.

And believe me, I thought you explained quite well, and don't consider you a meanie. I thought your post was very professional.

Thanks
Bookmark Post in Technorati
Reply With Quote
  #10 (permalink)  
Old 04-29-2008, 06:48 AM
Member
 
Join Date: Apr 2008
Posts: 34
kewlgeye is on a distinguished road
Ok, With Catch and Try Statements
Ok, I need this code to have catch and try statements but I keep getting a compiler error telling me I can't have catch without try, or try without catch. I don't understand, but I need my code to have catch and try statements. What can I do?

Code:
import java.io.*; class ModifiedTest { public static void main(String args[]) throws IOException { BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); String strInput; System.out.println("Do you like Rock Music?:"); strInput = dataIn.readLine(); //reads data from console try { if ("y".equals(strInput)) { System.out.println("Do you like Marilyn Manson?:"); strInput = dataIn.readLine(); //reads data from console if ("y".equals(strInput)) { System.out.println("You are a hardcore Rocker"); } else if ("n".equals(strInput)) { System.out.println("How could you not like Marilyn Manson?"); } else { System.out.println("Illegal input: " + strInput); } } else if ("n".equals(strInput)) { System.out.println("Ok, bye rock hater!"); } else catch (TheException e) { System.out.println("" + e + " input: " + strInput); } System.out.println(); System.out.println("Program Ending!"); } } } class TheException extends Exception { public String toString() { return "Illegal"; } }
Bookmark Post in Technorati
Reply With Quote
  #11 (permalink)  
Old 04-29-2008, 06:53 AM
Eranga's Avatar
Moderator
 
Join Date: Jul 2007
Location: Colombo, Sri Lanka
Posts: 4,376
Eranga has a spectacular aura aboutEranga has a spectacular aura about
Send a message via Yahoo to Eranga
Yes you can't use just a try or a catch. It's a simple idea pal.

If you try to do something, there you have something to catch. Same for wiser versa.
__________________
Use an appropriate Subject. "Help, urgent!" isn't one.
To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts.

Has someone helped you? Then you can
To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts.
their helpful post.

Want to make your IDE the best?
To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts.

To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts.

To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts.
Bookmark Post in Technorati
Reply With Quote
  #12 (permalink)  
Old 04-29-2008, 09:10 AM
danielstoner's Avatar
Senior Member
 
Join Date: Apr 2008
Location: Canada
Posts: 191
danielstoner is on a distinguished road
I understand that YOU need some try/catch block, but unfortunately that piece of code doesn't need it Can you tell me why you need the try/catch thing? Maybe we can come up with something.
__________________
Daniel @ [
To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts.
]
Language is froth on the surface of thought
Bookmark Post in Technorati
Reply With Quote
Sponsored Links
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
try catch!? Joe2003 Advanced Java 2 01-28-2008 09:51 PM
Try Catch Renegade85 New To Java 4 12-03-2007 06:10 PM
when to use try...catch javaplus New To Java 2 11-18-2007 10:52 PM
try...catch block javaplus New To Java 3 11-06-2007 09:53 PM
Use try and catch zoe New To Java 2 07-25-2007 09:50 PM


All times are GMT +3. The time now is 11:18 AM.


VBulletin, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO ©2007, Crawlability, Inc.
Copyright ©2006 - 2007, www.java-forums.org