aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes please explain Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "please explain" Watch "please explain" New topic
Author

please explain

ketki kalkar
Ranch Hand

Joined: May 09, 2007
Posts: 36
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

Joined: Jun 06, 2007
Posts: 38
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

Joined: Dec 29, 2004
Posts: 30
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 ]

SCJP aspirant<br />SCWCD aspirant
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: please explain