This week's book giveaway is in the Kotlin forum.We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# need help on precedence of operators

betzi kuriakose
Greenhorn
Posts: 12

the above code will
show the value of i as 0
and the array elements will be displayed as
3
0
0
0
0

Please explain why the output is so? I couldnt figure out...

regards
betzi
[ July 03, 2005: Message edited by: Barry Gaunt ]

Barry Gaunt
Ranch Hand
Posts: 7729
"betzi", your displayed name is still not correct. Please use two names in one of the two formats <first name><space><family name> or <initials of first name><space><family name>.

Thanks
-Barry
[ July 03, 2005: Message edited by: Barry Gaunt ]

janki tangeda
Ranch Hand
Posts: 54
The output is correct.
In the first expression i=i++ the value of i is substituted on RHS as it is i.e i=0.Now since the ++ operator has higher precedence than assignment operator(=).i is incremented by 1.So i becomes 1.But Note:Although i is incremented by 1 the value substituted on RHS was 0.Now in the end, the assignment operator is applied and this 0 is assigned to i.Same thing happens in all the three i=i++ expressions.

Thus the program prints i as 0 after those expressions.

int index = 0;
array[index]=index=3

In the above expression [] operator has higher precedence than '=' operator.Therefore its evaluated as below:

array[0] = index = 3
array[0] = (index = 3) //assignment operator is right associative
array[0] = 3

Since it is an integer array..all other uninitialized elements of array will take the default value for int i.e 0

Barry Gaunt
Ranch Hand
Posts: 7729
1. Great name change, betzi!
[ July 03, 2005: Message edited by: Barry Gaunt ]

bhavesh bhanushali
Ranch Hand
Posts: 55
take a look at the following code snipet does the exact opposite of the earlier code

public class IncrementTest
{
public static void main(String[] args)
{
int i = 0 ;
i = ++i;
System.out.println(" The value of i is " +i );
i = ++i ;
System.out.println(" The value of i is " +i );
i = ++i ;
System.out.println(" The value of i is " +i );
}
}

o/p is :
---------- java ----------
The value of i is 1
The value of i is 2
The value of i is 3

thanks and regards ,
bhavesh