Using loop constructs Flashcards

1
Q

Which of the following code snippets will compile without any errors? (Assume that the statement int x = 0; exists prior to the statements below.)

  1. while (false) { x=3; }
  2. if (false) { x=3; }
  3. do{ x = 3; } while(false);
  4. for( int i = 0; i
A

2, 3, 4

- 1. is a compile-time error because the statement x=3; is not reachable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

True/false: while and do while constructs takes an expression that returns a boolean

A

True

- otherwise compile time error

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

True/false: the following is valid inside a method:
int i = 20;
for (int i = 0; i < 10; i++) System.out.print(i + “ “); //1

A

False.
- The scope of a local variable declared in ‘for’ statement is the rest of the ‘for’ statement, including its own initializer. So, when line 3 is placed before line 1, there is a redeclaration of i in the first for() which is not legal.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

True/false: The following labeled for loop is valid:

for : for(int i = 0; i< 10; i++){ }

A

False
- Note: that for is a keyword and so cannot be used as a label. But you can use any other identifier as a label. e.g.
String String = “”; //is valid.
String : for(int i = 0; i< 10; i++) //is valid!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly