• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

unable to understand the output

 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
int[] a = new int[2];
int n =0;
a[++n]= ++n;


System.out.println("the array contains "+ a[0] +a[1]);

output 0 2

can u explain what is logic behind output and if i change it to
a[n++]=++n;
then output is
output 2 0
 
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the first example "a[ ++n ]" the increment is performed BEFORE evaluating the value of n.
So, the expressions becomes "a[ 0+1 ] = ++n", that is: "a[ 1 ] = ++n".
n now has value of 1, and it is incremented on the left side of " = ":
"a[ 1 ] = 1+1", that is: "a[ 1 ] = 2"
a[ 0 ] remains with the default value of 0.

In the second example "a[ ++n ]" the increment is performed AFTER evaluating the value of n.
So, the expressions becomes "a[ 0 ] = ++n".
Only then n is assigned the value of 1, and it is incremented on the left side of " = ":
"a[ 0 ] = 1+1", that is: "a[ 0 ] = 2"
a[ 1 ] remains with the default value of 0.
 
nishant vats
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks for reply but i guess in assignment operator right hand evaluation is done before ..in that case ++n is evaluated first.. so can u nw explain the answer
 
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
nish vats, that seems like a reasonable assumption but it turns out to be incorrect. The left-hand operand is evaluated first in order to determine the variable that will receive the newly assigned value. The entire procedure is described in the JLS 15.26.1.
 
nishant vats
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks joe ...
 
reply
    Bookmark Topic Watch Topic
  • New Topic