Click to See Complete Forum and Search --> : a=a++;


samli
October 22nd, 2004, 05:10 PM
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);
}

}

cjard
October 22nd, 2004, 06:50 PM
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

cjard
October 22nd, 2004, 06:56 PM
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

dlorde
October 23rd, 2004, 08:10 PM
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... :eek:

samli
October 25th, 2004, 06:27 PM
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.

_uj
October 26th, 2004, 01:31 AM
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. :D

cjard
October 27th, 2004, 06:03 AM
if only i'd been allowed a copy of the JLS in my biology exam.. ;)