CSE 11 – Intro to Programming, Expedited Week 2 - Monday
Note 6 – break, continue, nested for
1. Loop recaps
1. initialization exp evaluated first
2. loop condition evaluated; if false goto next statement after loop block
3. execute loop body
4. execute loop exp; goto 2.
Nested For Loops
public class MultiplicationTables {
 public static void main( String[] args ) { Output:
 1 x 1 = 1
 //complete me
 1 x 2 = 2
 1 x 3 = 3
 1 x 4 = 4
 1 x 5 = 5
 1 x 6 = 6
 1 x 7 = 7
 1 x 8 = 8
 1 x 9 = 9
 1 x 10 = 10
 }
 ------------
}
 2 x 1 = 2
 .
 .
 .
For loop variants
 ------------
for (i = 0, j = 10; i < j; i++, j--) {
 statements;
}
for ( ; k-- > j; ) { for ( ; ; ) { while ( true ) {
 statements; statements; statements;
} } }
 - this is a good candidate for a while loop - forever loop - forever loop
 int n = 4; A. 4
 int x = 0;
 while(n > 0) {
 B. 6
 for(int i = 0; i < n; ++i) { C. 7
 ++x; D. 8
 } E. This will cause a compile error
 n /= 2;
 }
 //value of x?
 1
 CSE 11 – Intro to Programming, Expedited Week 2 - Monday
2. break and continue
break and continue statements allow us to alter the normal flow of a loop
 • break: when executed, the inner-most loop that contains the break statement will be exited immediately.
 • continue: when executed, the remainder of the current iteration will be skipped.
 for (int i = 0; i < 10; i++){ How many times is continue statement
 if (i++%3==0) { executed?
 continue;
 }
 A. 0
 if (--i%2==0){ B. 1
 break; C. 2
 } D. 5
 System.out.println(i); E. 10
 }
3. String in Java (https://docs.oracle.com/javase/10/docs/api/java/lang/String.html)
String is a data type in Java that is used to store a sequence of characters. It is an Object type, not a primitive
- string concatenation operator ( + )
- only object type with which Java provides literals "Hello World"
- equals() [vs. ==], length(), charAt(), and many more
 What is the output of the following code snippet?
 String name = "Hazel";
 System.out.println("name = " + name);
 System.out.println("length = " + name.length());
 //substring is left inclusive, right exclusive
 System.out.println(“substring = “ + name.substring(2, 4));
 System.out.println("name starts with = " + name.charAt(0));
 System.out.println(“loc for a = “ + name.indexOf(‘a’));
 System.out.println("name ends with = " + name.charAt(name.length() - 1));
StringBuilder: Another type to represent string information but it is mutable.
public class Tester{
 public static void main(String[] args){
 //Code A: What does the code print?
 StringBuilder b=new StringBuilder(“hello”);
 b.append(“ there!”);
 System.out.println(b.toString());
 A. Both print hello there!
 //Code B B. Both print hello
 String s=new String(“hello”); C. A prints hello and B prints hello there!
 s.concat(“ there!”); D. A prints hello there! and B prints hello
 System.out.println(s); E. Compiler error for A as we need to import
 }
} StringBuilder