hi..can anyone explain to me?? i am very confused abt this two..

for example;

iint m [] = { 3, 2, 5, 2 };
int k = 0;

System.out.println("(a)" + m[ k++ ];
System.out.println("(a)" + m[ ++k ];
*i compiled..but i dun understand why is the result 3 and 5 respectively???


hopefully u guys can give me more examples and detailed explanation...very confused on the post increment part..thanks a million...

* struggling here..revising for my java exam ..:'(

Read the comments

int m [] = { 3, 2, 5, 2 };
int k = 0;

// k has value 0 so it returns 3. THEN k is increased because the ++ is after the variable
System.out.println("(a)" + m[ k++ ];

// k has now value 1

// ++k. The ++ is before the variable so the increase will happen FIRST. So k will become 2. THEN k will "return" its value which is 2
// m[2] = 5
System.out.println("(a)" + m[ ++k ];


// it compiled..but i dun understand why is the result 3 and 5 respectively???

Try running this:

int k = 0;
// first prints then increases
System.out.println("K before the increase: "+ (k++) );
System.out.println("K now: "+ k );

k = 0;
// first increases then prints
System.out.println("K after the increase: "+ (++k) );
System.out.println("K now: "+ k );

Edited 7 Years Ago by javaAddict: n/a

one more qn.. what is the difference between

System.out.println("(a)" + (1 + m[k]) );

and

System.out.println("(a)" + 1 + m[k] ) ;

i realised that the output is different..it's 3 and 12 respectively...

what difference does it make because of the additional bracket??

First it will calculate what is inside the parenthesis and return it. Then it will concatenate it with the rest: 
System.out.println("(a)" + [B]([/B]1 + m[k][B])[/B] );

// "(a)" + (1 + m[k]) --> "(a)" + (1+2) --> "(a)" + 3 --> (a)3
and 

// no parenthesis. Things will be calculated with the order they appear
System.out.println("(a)" + 1 + m[k] ) ;

//                     [U]String + int[/U]   --> [U]String[/U]       
// "(a)" + 1 + m[k] --> [U]"(a)" + 1[/U] + 2 --> [U]"(a)1"[/U] + 2 --> (a)12

In math they teach us first to calculate the parenthesis.

Edited 7 Years Ago by javaAddict: n/a

This article has been dead for over six months. Start a new discussion instead.