Daryl Lee
Posts: 1
Nickname: radlyeel
Registered: Aug, 2008
|
|
Re: a beginner's question
|
Posted: Nov 5, 2008 8:27 AM
|
|
The first problem (a = a++) actually exposes a huge difference between C++ and Java.
Here's what happens in C/C++, step by step: 1. The address of a's storage location is loaded into a register. 2. The value of a is read and copied into a using the register pointer. (At this point, a is 0.) 3. a is incremented using the register pointer. So a now equals 1.
Here's what happens in Java, step by step: 1. The value of a is read into a register. 2. The value is copied into a's storage location. a is still 0. 2. The value is incremented, but the copy has already been done so the new value is thrown away. a is still 0.
The distinction is that in C/C++, variables have addresses and those addresses are used for accessing the variables. In Java, variables have references, not addresses. This is how Java afficionados can trumpet "no pointers in Java."
I'd also mention that "a = a++" is bad usage in either language. As readers of the program, we want it to mean "let a = a + 1". But your demo has shown that's not reliable. If you want "a = a + 1", write "a++;" (not a = a++;) in both languages and you get the same results.
As to your b = b + 2 question, alas, you have run afoul of one of Java's interesting "why did they do it this way" situations. The best explanation I've found is at http://www.jguru.com/faq/view.jsp?EID=13647.
|
|