Flow Control and Exception Handling

5) Write code using the if and switch statements and Identify legal argument types for these statements.

if : General decision making

if (x < y) System.out.println("x is smaller than y");

An optional else keyword provides the alternative statement to execute if the test is false:
if (x < y)

System.out.println("x is smaller than y");
else System.out.println("x is bigger");

if you want to do more than just one thing, you can enclose those statements inside a block:
  if (x < y )

System.out.println("x is smaller");
else {
System.out.println("y is smaller");
if (y < z)
System.out.println("y is smaller");
else System.out.println("z is smaller");
}

expression ? op1 : op2

The ?: operator evaluates expression and returns op1 if it's true and op2 if it's false.

switch: selection from a list of alternatives.

The if/else construct can be cumbersome when you have to deal with multiple selections with many alternatives.
switch (expression) {

case value1: statement(s) ; break;
case value2: statement(s) ; break;
default: statement(s);
}

int x=2;

switch(x) {
case 1: System.out.println("1");
case 2:
case 3: System.out.println("3");
case 4: System.out.println("4");
}
ouput :
3
4
char myChar = 'c';

switch(myChar) {
default :
case 'a': System.out.println("I am in case a"); break;
case 'b': System.out.println("I am in case b"); break;

output :
I am in case a



6) Write code using all forms of loops including labeled and unlabeled use of break and continue and state the values taken by loop counter variables during and after loop execution.

Loops are of two forms. They are "Indeterminate loops" and "Determinate loops"

Indeterminate loops:
while:
This executes the body of the loop while a condition is true. It may never execute it if the condition is false.
while(x<10) {

System.out.println(x);
x++;
}

A while loop tests at the top. Therefore, the code in the block may never be executed.

do:
If you want the block to be executed at least once, you have to use the do version of the while loop
do {

System.out.println(x);
} while(false);

Determinate loop:
for:
The for loop, repeats a statement or block of statements until a condition is matched. for loops are frequently used for simple iterations in which you repeat a block of statements a certain number of times and then stop.
for (int i = 1; i <= 10; i++) {

System.out.println(i);
}

for loop statement has three parts:

A comma separated for loop is allowed in the initial and increment sections, so that you can string together several initializations or increments

for(i=0, j=0; i<10; i++, j++) {.....}
eg,
public class Test {

public static void main(String arg[]) {
int tot = 0;
for(int i =0, j=10; tot >30; ++i, --j) {
System.out.println("i=" + i +"j=" + j);
tot +=(i+j);
}
System.out.println("Total : " tot);
}
}

ouput :
Total : 0

It won't enter the loop at all because the condition says do the for loop when tot > 30, when tot = 0

An infinite loop will look like


for (;;) {....}

break :

The break keyword, when used with a loop halts execution of the current loop. If you've nested loops within loops, the break statement causes the control to pass to the next outer loop; otherwise, the program merely continues executing the next statement after the loop.

break (labeled):
 out: for (int i = 1; i <= 5; i++)

for (int j = 1; j <= 3; j++) {
System.out.println("i is " + i + ", j is " + j);
if (( i + j) > 4)
break out; -----------------------
} System.out.println("end") ; |
} System.out.println("the end");<----

output:

i is 1, j is 1
i is 1, j is 2
i is 1, j is 3
end
i is 2, j is 1
i is 2, j is 2
i is 2, j is 3
the end

break (unlabeled):
int a=0;

int b=0;
int c=0;

while (c < 10) {
a = a + b;
System.out.println("a is " + a + ",c is" + c);
if ( a > c) break; ---------------------
b++; |
c++; |
} |
System.out.println("the end") ;<----

output :
a is 0, c is 0
a is 1, c is 1
a is 3, c is 2
the end

continue :

continue (labeled) :
 -------> months: for(int m=1;m<4;m++) {

| for(int d=1;d<3;d++) {
------------------ if(m==2 && d==1) continue months;
System.out.println("m: " + m + ", d: " + d);
}
}

output :

m: 1, d: 1
m: 1, d: 2
m: 3, d: 1
m: 3, d: 2

continue (unlabeled) :
int c1=0;

int c2=0;
while(c1 < 3) { <-------------------------------------------------
c2++; |
System.out.println("c1: " + c1 + ", c2: " + c2); |
if(c2==2) continue; ---------------------------------------
c1++;
}

output :

c1: 0, c2: 1
c1: 1, c2: 2
c1: 1, c2: 3
c1: 2, c2: 4

Remember :In all the loops (for, while, and do), the loop ends when the condition you're testing for is met. If you want to exit the loop earlier than that, you can use the break and continue keywords.



7) Write code that makes proper use of exceptions and exception handling clauses (try catch finally) and declares methods and overriding methods that throw exceptions.
RuntimeException such as ArrayIndexOutofBounds, SecurityException, or NullPointerException.
Other exceptions such as EOFException and MalformedURLException.

Checked vs. Unchecked Exception :

  • A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.
  • Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method
  • Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked.
  • With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method
  • Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.
  • There are two choices to handle exceptions,

    You protect the code that contains the method that might throw an exception inside a try block.
    You test for and deal with an exception inside a catch block.
    try{
    
    System.out.println("Before an Exception");
    mightThrow();
    System.out.println("After throwing Exception");
    }
    catch (IOException e) {
    System.out.println("Exception thrown");
    }
    finally {
    System.out.println("finally");
    }

    output :

    Before an Exception
    After throwing Exception
    finally Before an Exception
    Exception thrown
    finally Before an Exception
    finally
    <>

    Remember: finally method gets executed:

  • finally() will be executed under any circumstances
  • Specific exception should come first and the common exception should come at the end otherwise you will get a compiler error
  • Using throws clause : Instead of handling errors at the point where they are likely to occur, the error can be passed up the call stack by use of the throws clause when declaring a method. The throws keyword is used to identify the list of possible exceptions that a method might throw.

    eg,
        public class factorial {
    
    static long[] table=new long[21];
    static {table[0]=1;}
    static int last=0;
    public static long method(int x) throws IllegalArgumentException {
    if (x>=table.length) throw new IllegalArgumentException("overflow; xis too large");
    if(x<0) throw new IllegalArgumentException("x must be non-negative");
    while(last table[last+1]=table[last] * (last+1);
    last++;
    }
    return table[x];
    }
    public static void main(String arg[]) {
    // method(25);//This method will throw "overflow" exception
    // method(-5);//This method will throw "must be non-negative" exception
    }
    }
    }

    Exception Heirarchy :


    Object
    |
    |
    Throwable
    |
    |
    Exception-->ClassNotFoundException, ClassNotSupportedException, IllegalAccessException, InstantiationException, IterruptedException, NoSuchMethodException, RuntimeException, AWTException, IOException

    RuntimeException-->EmptyStackException, NoSuchElementException, ArithmeticException, ArrayStoreException, ClassCastException, IllegalArgumentException, IllegalMonitorStateException, IndexOutOfBoundsException, NegativeArraySizeException, NullPointerException, SecurityException.

    IllegalArgumentException-->IllegalThreadStateException, NumberFormatException

    IndexOutOfBoundsException-->ArrayIndexOutOfBoundsException, StringIndexOutOfBoundsException

    IOException-->EOFException, FileNotFoundException, InterruptedIOException, UTFDataFormatException, MalformedURLException, ProtocolException, SockException, UnknownHostException, UnknownServiceException.

    Remember :

  • Unchecked exceptions
  • Checked exceptions
  • There are no rules even for Checked exceptions when overloading.


    Copyright © 1999-2000, Jyothi Krishnan
    All Rights Reserved.