• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

please explain

 
ketki kalkar
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What gets printed when the following program is compiled and run. Select the one correct answer.

1.class test {
public static void main(String args[]) {
int i,j,k,l=0;
k = l++;
j = ++k;
i = j++;
System.out.println(i);
}
}


0
1
2
answer is 1.

2.public class test {
public static void main(String args[]) {
int i, j;
int k = 0;
j = 2;
k = j = i = 1;
System.out.println(k);
}
}


The program does not compile as k is being read without being initialized.
The program does not compile because of the statement k = j = i = 1;
The program compiles and runs printing 0.
The program compiles and runs printing 1.
The program compiles and runs printing 2.

answer is it prints 2.
 
sravani jetty
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ketki,
++ operator changes the outcome of an expression depending on whether the operator is placed before or after the operand. At line, where k=l++ the value of l is first assigned to k and then the value of l is incremented so k=0. And in the next line the value of k is incremented and then it is assigned to j so j=1. At last the value of j is assigned to i and j is incremented so i=1.


For the second question the output is one not two
 
suresh koutam
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the answer for the first question is 1...
intially all the values are 0...
i=0, j =0, k=0, l=0
k=l++ >>>>> k = l which is 0(and then increment l by 1)
so k=0 and l =1

j=++k >>>>> j = (k+1) which is 1 (and remember k value is now 1)

i=j++ >>>>> i= j which is 1 ( and then increment j by 1)

so when you print i its value is 1



for the second question the answer is it prints 1....

because its intializing from right to left
[ June 12, 2007: Message edited by: suresh koutam ]
[ June 12, 2007: Message edited by: suresh koutam ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic