• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

scjp chapter 5 q...5 page no 303

 
sapana jain
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Foozit {
public static void main(String[] args) {
Integer x = 0;
Integer y = 0;
for(Short z = 0; z < 5; z++)
if((++x > 2) || (++y > 2))
x++;
System.out.println(x + " " + y);
}
}
i think there is syntax error as they have not opened the curly brackets.....for for loop
please help me..............
 
P Ventura
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

If a for isn't followed by braces, it loops the statement that follows the for.
In this case "If" is the looped statement.
 
antonio ciambellari
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is the result x=4 and y=3?
 
al nik
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the output is x=8 y=2
the syntax

it's ok
the for cycle iterates 5 times
1st: x=1 , y=1
2nd: x=2 , y=2
3rd: x=4 , y=2
4th: x=6 , y=2
5th: x=8 , y=2

 
Manoj Macwan
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer of this question is 8 2.

As said in the earlier post - If a for isn't followed by braces, it loops the statement that follows the for.
In this case "If" is the looped statement.

Here we are looping 5 times and each time values of X and Y are:
x y
0 - 1 1
1 - 2 2
2 - 4 2 (As the first expr is evaluated as TRUE, second expr won't executed)
3 - 6 2 (As the first expr is evaluated as TRUE, second expr won't executed)
4 - 8 2 (As the first expr is evaluated as TRUE, second expr won't executed)
 
sapana jain
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by P Ventura:

If a for isn't followed by braces, it loops the statement that follows the for.
In this case "If" is the looped statement.


thanks a lot..........i am preparing for scjp and having many problems........so i just take chance to post my problem and in returned i got many mails and now my problem is solved.......
hope you will help me in future also.........
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic