Using loop constructs Flashcards
Which of the following code snippets will compile without any errors? (Assume that the statement int x = 0; exists prior to the statements below.)
- while (false) { x=3; }
- if (false) { x=3; }
- do{ x = 3; } while(false);
- for( int i = 0; i
2, 3, 4
- 1. is a compile-time error because the statement x=3; is not reachable.
True/false: while and do while constructs takes an expression that returns a boolean
True
- otherwise compile time error
True/false: the following is valid inside a method:
int i = 20;
for (int i = 0; i < 10; i++) System.out.print(i + “ “); //1
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.
True/false: The following labeled for loop is valid:
for : for(int i = 0; i< 10; i++){ }
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!