You are on page 1of 14

OCA Exam Preparation

LOOPS – REVIEW
ABBREVIATIONS & ACRONYMS

actype – actual object’s type at run time AIOOBE – ArrayIndexOutOfBoundsException


assop – assignment operator CCE – ClassCastException
castype – data type specified inside the parens for an explicit cast ChE – checked exception
comperr – compilation error CSR – the Catch-or-Specify Requirement
ctor – constructor DTPE – DateTimeParseException
dim – dimension E – an exception (regardless of the type)
initer – initializer IAE – IllegalArgumentException
op – operator IOE – IOException
paramlist – list of formal parameters in a lambda expression IOOBE – IndexOutOfBoundsException
preditype – data type specified inside the angle brackets LDT – any of the new date/time classes in Java 8
reftype – reference type LOC – line of code
refvar – reference variable NFE – NumberFormatException
sout – any printing statement such as System.out.println(), etc. NPE – NullPointerException
stat – statement RTE – RuntimeException
ternop – ternary operator SIOOBE – StringIndexOutOfBoundsException
var – variable TCF – try-catch-finally construct

Igor Soudakevitch  2019 2


igor.soudakevitch@mail.ru
EXAM OBJECTIVE’S STRUCTURE

The 1Z0-808 topics within this group:


1. Create and use while loops;
2. Create and use for loops including the enhanced for loop;
3. Create and use do-while loops;
4. Compare loop constructs;
5. Use break and continue.

Source: Oracle Univ. 3


5.1 ÷ 5.5
while
for INCL. for-each
do-while
break AND continue
4
WORKING WITH LOOPS

 The standard for loop is the most basic and versatile loop of all; it can replace any other
loop construct.
 do-while executes at least once.
 The break statement breaks out of a loop ‛cleanly’, in other words, by fully abandoning
current iteration and any other remaining iterations of the loop. Control is transferred to
the first statement after the loop.
 When the loop for(i = 0; i < n; i++) terminates, the value of i is n and not n-1.
 Nested loops can appear intimidating but chances are the flow won’t even enter some of
those damned loops.

The weirder the loop the higher the chances the code is booby-trapped
somewhere else and, what’s more, on a pretty simple aspect.

5
WORKING WITH LOOPS, cont’d

 If your analysis shows that the flow does enter a loop, write down each
iteration with all its steps; cracking loops mentally at home is cool but probably
not a good idea on the exam.

 Vertical notation works better than writing the results of each iteration in rows
because it’s easier to correct values this way or start over from a particular
point if you lose concentration for a sec:

6
WORKING WITH LOOPS, cont’d

 The compiler treats for(;;) as for(;true;).


 EXTRA: Any section of the for loop can be moved to its body; what’s more, the ForInit
section accepts chained assignments (the vars must be of the same type, though):
int i, s, count = 10;
for (i = 0, s = 0; i < count; i++) { s+=i; }
–––––––––––––––––––––––––––––––––––––––––––––
int i, s, count = 10;
for(i = 0, s = 0; i < count; s+=i, i++);
–––––––––––––––––––––––––––––––––––––––––––––
int s = 0, count = 10;
for(int i=0; i < count; s+=i++);
–––––––––––––––––––––––––––––––––––––––––––––
int i=0, s=0, count=10;
for(; i< count; s+=i){ i++; }
–––––––––––––––––––––––––––––––––––––––––––––
int i=0, s=0, count=10;
for(; i < count; ){ s+=i; i++; }
–––––––––––––––––––––––––––––––––––––––––––––
int i=0, s=0, count=10;
for(; ;){ s+=i++; if (i>count) break; } 7
WORKING WITH LOOPS, cont’d

 An endless loop makes subsequent stat unreachable → comperr.

The rule sounds pretty obvious but endless loops are tricky: the code will throw
the "unreachable statement" comperr only if
1) the boolean expression can be evaluated at compile time, and
2) there’s no escape from the loop.

 The curly braces {} are NOT required for loops → be careful: the code’s
business logic can be in jeopardy.
 continue is valid only inside loops; ANY loop will do including for-each,
do-while and while. 8
WORKING WITH LOOPS, cont’d

 Labels:
 can be added to:
o a sub-block;
o any looping construct such as for, for-each, while, or do-while;
o conditional constructs such as if and switch;
o expressions and assignments;
o return stats;
o TCF constructs, and
o throw stat.
 cannot be added to declarations of variables.

Although labeled break is commonly used with loops, it is still valid outside them
(e.g., in the if constructs, etc.). Watch out, however, for its scope as it might lead to
the ‛unreachable statement’ comperr.

9
WORKING WITH LOOPS, cont’d

Labeled break needs a block or an if with at least a single break label; stat in it:
class Label {
String label(){
// label int a = 10; // INVALID
int a = 10;
// label: if (true) break; // INVALID
label: if (true) break label;
label: for (;true;) break label;
label: switch(a) {}
label: a = 42;
label: a++;
label: try{ label2: throw new NullPointerException(); }
catch(NullPointerException npe){ break label; }
label: return "Label!";
}
}

As labels bind to either loops or blocks, outside them they are out of scope →
comperr.
Corollary: If there's a labeled continue it must always be inside the loop the label is
declared for.
10
WORKING WITH LOOPS, cont’d

 The for-each loop is routinely used to iterate over Collections such as Lists.
However, it cannot be used to:
 initialize or modify the elements of an array;
 delete the elements of a Collection;
 iterate over multiple collections or arrays within the same loop.

 Nested loops – Rules of Engagement:


 use break to exit the inner loop;
 use continue to abandon the current iteration of the inner loop;
 use a labeled break to exit the outer loop;
 use a labeled continue to skip the iteration of the outer loop.

 EXTRA: It is not possible to break out of an if construct when it isn’t wrapped up


in a loop or switch UNLESS the break stat is labeled (already demonstrated):
// if(true) break; // INVALID
for(;true;) if(true) break;

11
WORKING WITH LOOPS, cont’d

 EXTRA: while expression accepts assignments:


int a = 0;
while( (a = a + 1) > 0) { // VALID
System.out.println("hello");
break; }
 EXTRA: while doesn’t accept var declarations; can use method invocation, though.
 EXTRA: The ForUpdate section of the standard for loop allows only the following:
– an assignment expression;
– pre/post incr/decr op;
– method invocation;
– class instance creation;
 EXTRA: while and regular for can’t have explicit false as their termination condition but
do-while can.
It is not that false isn’t allowed in principle, no; it’s simply about unreacheable stats. E.g.:
do { doStuff(); } while (false) // VALID as doStuff() is reachable

12
WORKING WITH LOOPS, cont’d

What’s more, while(!true) doesn’t compile – because !true is a straightforward constant


that can be evaluated at compile time – but while(!(x=true)) does compile. Same goes
for the standard for:
boolean x = false;
do { }
while (false); // VALID
// while(false)) { } // INVALID
// while(!true) { } // INVALID
while(!(x=true)) { } // VALID, doesn’t enter loop
// for (int i=0;false;i++){ } // INVALID
// for (int i=0;!true;i++){ } // INVALID
for (int i=0;!(x=true);i++){ } // VALID, doesn’t enter loop

Remark: if(false) is an exception to the rule (to make if(DEBUG) possible).


 EXTRA: Can’t use an existing/predefined var in the var declaration part of the enhanced
for loop. What’s interesting, this var (even of a primitive type!) can be final. In fact, this is
the only modifier that is allowed inside an enhanced for declaration:
int[] arr = {0, 1};
for (final int e : arr) { } // VALID
13
WORKING WITH LOOPS, cont’d

 EXTRA: Labels are ‛recyclable’ (because they go out of scope as soon as the block or
construct they bind to is over):
public static void main(String[] args){ // outputs 1234
label: {
System.out.print("1");
if (false) break label; System.out.print("2"); }
label:
if (1 > 0) {
System.out.print("3");
if (false) break label; System.out.print("4"); }}
 EXTRA: Booby-trapped patterns:
 i = i++; never increments. (See the discussion on Stack Overflow )
 a break-continue fork in ANY loop makes the next stat inside the loop unreachable:
for(int i = 0; i<10; i++){
if(i == 3){ break;
} else { continue; }
// System.out.println("!"); // unreachable stat → comperr
}
 for(...;...;<no update>){<no update>} creates a valid, endless loop. 14

You might also like