Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

# Operators

Savio Mascarenhas
Ranch Hand

Joined: Nov 29, 2000
Posts: 108
1.int a=1;
2.int b=1;
3.a=a++;//Result is '1'
4.b=b++ +1;//Result is '3'
In line 3,a=a a=a+1 ie a=1 a=2.Assignment operator has right associativity so a=1.
In line 4,b=b b=b+1 +1 ie.b=1 b=3 so finally b is 1.However,here b is 3.
How is it evaluated ???

sasi dhulipala
Ranch Hand

Joined: Dec 28, 2000
Posts: 31
Hi,
I am getting b =2 ;
The evaluation of a = a++ I have explained in the earlier questions How ever again I am giving it below
a =1 ;
a = a ++;
operator '=' has least precedence so RHS is evaluated first
which is a++;
which first returns 1 ( a = 1 ) to be assigned to LHS a
and then increments a ( a++ postfix increment ) so a = 2 now
finally because of assignement a = 1 so the final val of a is 1
In the second case
b=b++ +1
evaluating RHS gives b++ + 1
> return 1 and increment b by 1 so b = 2 // here because of postfix increment of b ( b++)
> 1 + 1
> 2
assign this to b therefore b = 2;

HTH
sasi

[This message has been edited by sasi dhulipala (edited January 04, 2001).]
Tom Tang
Ranch Hand

Joined: Dec 24, 2000
Posts: 133
b=b++ +1 returns 3 instead of 2. Please refer to the following thread for exellent explanation.
http://www.javaranch.com/ubb/Forum24/HTML/000775.html

------------------------<BR>Sun Certified Java Programmer<BR>----------------------------------
oluwayomi adegoju
Greenhorn

Joined: Sep 22, 2000
Posts: 15
Tom,
While I am not against checking the site you refered to, I think Sasi is right because my compiler return b = 2 for line 4. The explanation Sasi gave is also consistent with line 3.
I think you should try out the code.
Oluwayomi
George Toronto
Ranch Hand

Joined: Dec 30, 2000
Posts: 78
Hi, Tom
Since you refer to MA's article, now let's calculate that expression by her easy method.
b= 1;
b=b++ +1;
b = 1(2) + 1;
So collect the non-braced digitals, we can obtain 1+1 = 2, since the final result should be the calculation result, no the ++ creates that results, so the final b = 2.
Let check another sample
c = 1;
c = ++c + c++ + ++c + c++ +c;
c = (2)2 + 2(3) +(4)4 + 4(5) +5;
so the result of c is 17, not the result of ++ (5)
The MA's method is good and easy.
regds
George
[This message has been edited by George Toronto (edited January 05, 2001).]

It is sorta covered in the JavaRanch Style Guide.

subject: Operators
Similar Threads
arrays equals() confusion
initialization sequence
surprise....boolean check
Incomparable types
Sierra Bates SCJP 6 Ch. 3 No. 3