what is the output of this
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   megala_raghavan
Posted On:   Monday, November 25, 2002 12:33 AM

hi

what is the output of the following.
for i it has to print 3 is not it?. but it is printting 1 only. why pl. explain

--

class test
{
public static void main(String args[])
{
int i,j,k,l=0;
k = l++;
j = ++k;
i = j++;

System.out.println("k IS : "+k);
System.out.println("j IS : "+j);
System.out.println("i IS : "+i);
}
}

Re: what is the output of this

Posted By:   Lasse_Koskela  
Posted On:   Monday, November 25, 2002 06:42 AM

The point is the difference between "variable++" and "++variable"; is the increase (+1) calculated before or after other statements.


For example


x = y++;

is the same as

x = y;
y = y + 1;

while on the other hand

x = ++y;

is the same as

y = y + 1;
x = y;


Here's a commented version of your code:


public class test {
public static void main(String args[])
{
int i, j, k, l = 0;
// i = j = k = l = 0

k = l++; // 'l' is increased AFTER the assignment
// i = 0
// j = 0
// k = 0
// l = 1

j = ++k; // 'k' is increased BEFORE the assignment
// i = 0
// j = 1
// k = 1
// l = 1

i = j++; // 'j' is increased AFTER the assignment
// i = 1
// j = 2
// k = 1
// l = 1


System.out.println("k IS : " + k); // prints "1"
System.out.println("j IS : " + j); // prints "2"
System.out.println("i IS : " + i); // prints "1"
}
}
About | Sitemap | Contact