|
-
October 22nd, 2004, 05:10 PM
#1
a=a++;
I am surprised by the output of the following Java code. Normally, I would not do "a=a++;". But I just could not explain why the "a=" would yield a wrong result.
Please help.
=============================================
import java.io.*;
public class Test {
public static void main (String args[]) {
int a = 1;
System.out.println(a);
a=a++;
System.out.println(a);
}
}
-
October 22nd, 2004, 06:50 PM
#2
Re: a=a++;
this topic is often a cause for confusion in newcomers to java. it has been discussed in depth and entirety before, and a good, clear explanation may be found here:
http://www.codeguru.com/forum/showthread.php?t=270776
-
October 22nd, 2004, 06:56 PM
#3
Re: a=a++;
incidentally, writing a=a++ is very poor coding style, for obvious reasons, and is to be avoided in all situations. a similar thing could be said of:
String s;
while(s = input.readLine() != null)
this is better written as:
for(String s = in.readLine(); s!=null; s= in.readLine())
in programming, like in english.. one sentence one point. one statement one purpose. avoiding combining assignment with other operations is the best option in all cases.
"everything should be as simple as possible, but no simpler.." - Einstein
-
October 23rd, 2004, 08:10 PM
#4
Re: a=a++;
 Originally Posted by samli
I am surprised by the output of the following Java code. Normally, I would not do "a=a++;". But I just could not explain why the "a=" would yield a wrong result.
You may be surprised by it, but that doesn't mean it's wrong. The result is, in fact, exactly as the Java Language Specification requires.
I don't understand it, therefore it's wrong...
Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.
-
October 25th, 2004, 06:27 PM
#5
Re: a=a++;
Thank you all for the explanation, which helps me understand the code.
I also enjoy the comment dlorde made. I really should keep that I mind when I troubleshoot my code in the future.
Thanks again.
-
October 26th, 2004, 01:31 AM
#6
Re: a=a++;
 Originally Posted by samli
I also enjoy the comment dlorde made. I really should keep that I mind when I troubleshoot my code in the future.
You mean to consult the Java language specification and check the facts rather than guess? My god is that allowed! I thought it was considered cheating.
-
October 27th, 2004, 06:03 AM
#7
Re: a=a++;
if only i'd been allowed a copy of the JLS in my biology exam..
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|