In this session you will learn:
Flow Control
Exceptions
Assertions
For more information, visit this link: https://www.mindsmapped.com/courses/software-development/online-java-training-for-beginners/
3. Page 2Classification: Restricted
Objective
• Write code using if and switch statements and identify legal argument
types for these statements.
• 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.
4. Page 3Classification: Restricted
if – else statements
• The if statement takes a boolean argument, and if the argument is true,
the body of the statement is executed
Eg:
if(x==5) {} // compiles, executes body if x is equal to 5
if(x=0) {} //does not compile, because non-boolean
if(x=true) {} //compiles, but always body is executed
• In the case of nested if-else statements, each else clause belongs to the
closest preceding if statement which does not have an else
5. Page 4Classification: Restricted
switch statements
• The argument passed to the switch and case statements should be int,
short, char or byte.The argument passed to the case statement should be
a literal or a final variable
• If no case matches, the default statement is executed
• When a break statement is encountered, the control moves out of the
switch statement. If no break statement, all the case statements are
executed till a break is encountered or the switch statement ends
eg: int x=1;
switch(x) {
case 1: System.out.println(“one”);
case 2: System.out.println(“two”);
} // both one and two are printed
6. Page 5Classification: Restricted
while and do-while loops
• Syntax of while loop is
while(expression) {}
where expression is a boolean expression
• The body of the while loop may not be executed even once
Eg: while(false) {} // body never executed
Eg : while(1) {} // will not compile, not a boolean
• Syntax of do-while loop is
do { } while(expression);
• The body of the do-while loop is executed at least once
7. Page 6Classification: Restricted
for loop
• The syntax is
for(expr1; expr2; expr3) { body }
where expr1 is for initialization, expr2 is the conditional test and expr3 is
the iteration expression
• Any of these 3 sections can be omitted, still it is legal
Eg: for( ; ; ) {} // an endless loop
• There can be more than one initialization expressions, more than one
iteration expressions, but only one test expression
8. Page 7Classification: Restricted
break and continue
• break statement is used to exit from a loop or a switch statement
• continue statement is used to stop just the current iteration
• If it is a nested loop, the break statement exits from the innermost loop
only
• If a break keyword is combined with a label, a break statement will exit
out of the labeled loop
eg: outer: for (int i=0;i<10;i++) {
while(y>0){ break outer; }
} // breaks from the for loop if y>0
9. Page 8Classification: Restricted
Extra points to remember…
• Watch out for boolean assignments(=) that can be mistaken for boolean
equality(==)test:
boolean x=false;
If (x=true) { } // an assignment, so x will always be true
• Switch statements can evaluate only the byte, short, int, and char data
types. You can’t say
long s=30; switch(s) { }
• The default block can be located anywhere in the switch block, so if no
case matches, the default block will be entered, and if the default does
not contain a break, then code will continue to execute (fall-through) to
the end of the switch or until the break statement is encounted.
10. Page 9Classification: Restricted
Objective
• Write code that makes proper use of exceptions and exception handling
clauses (try, catch, finally) and declares methods and overriding methods
that throw exceptions.
• Recognize the effect of an exception arising at a specified point in a code
fragment. Note: The exception may be a runtime exception, a checked
exception, or an error (the code may include try, catch, or finally clauses
in any legitimate combination).
11. Page 10Classification: Restricted
Exceptions
• Exceptions in Java are objects, all exceptions are derived from
Throwable class in the java.lang package
• Error, RuntimeException and their subclasses, are unchecked
exceptions. The rest are checked exceptions
• You can create your own exceptions by extending the appropriate
exception class
• Any method that might throw a checked exception must either declare
the exception using the throws keyword, or handle the exception using
a try/catch block
13. Page 12Classification: Restricted
try and catch
• The try block contains the code which might throw an exception, one or
more catch clauses can be provided to handle different exception types
• Eg: try {
// code which might throw exceptions
}
catch(Exception e)
{ //code to handle the exception }
• If an exception is thrown from the try block, the control moves to the catch
block. If there is a matching catch clause, it is executed, else it propagates
through the call stack
14. Page 13Classification: Restricted
Example
• Eg:
class Test{
public static void main(String args[]) {
try
{
if(x>y)
throw new MyException();
}
catch(Exception e)
{ System.out.println(“caught”+e); }
} }
15. Page 14Classification: Restricted
Finally
• The finally block is always executed at some point after the try block,
whether an exception is thrown or not
• If no exceptions are thrown from the try block, the finally block is
executed after the try block completes. If an exception is thrown, any
matching catch clauses are executed, after which control comes to the
finally block
• Usage:
try { // code which throws exceptions
}
catch(Exception e){//handle exception}
finally{//clean up code}
16. Page 15Classification: Restricted
Throws and throw
• The checked exceptions that a method can throw must be declared using
the ‘throws’ keyword
• To throw an exception explicitly from code, use the ‘throw’ keyword
• Eg: /* Assuming MyException is a subclass of Exception*/
void f() throws MyException
{
if(x > y) throw new MyException();
}
• You can also rethrow the same exception which you caught eg:
catch(IOException e) { throw e; }
17. Page 16Classification: Restricted
Extra points to remember…
• If you throw a checked exception from a catch clause, you must also
declare that exception
• Any method which calls a method which throws a checked exception also
has to declare the exception or handle it
• Unchecked exceptions do not have to be specified or handled using
try/catch
• finally block is executed in all cases except when System.exit() is invoked
• A try block should have either a catch block or a finally block, but its not
compulsory to have both
• All catch blocks must be ordered from the most specific exception to the
most general one
18. Page 17Classification: Restricted
Objectives
• Write code that makes proper use of assertions, and distinguish
appropriate from inappropriate uses of assertions.
• Identify correct statements about the assertion mechanism.
19. Page 18Classification: Restricted
Assertions
• An assertion is a statement containing a boolean expression that the
programmer believes to be true at the time the statement is executed.
• Assertions are typically enabled during testing, but disabled during
implementation
• The system executes the assertion by evaluating the boolean expression
and reporting an AssertionError if the expression evaluates to false.
• Eg:
assert(x>0); // throws an AssertionError if x<=0
20. Page 19Classification: Restricted
Using Assertions
• Assertions can be in two forms
1. assert Expression1 ;
2. assert Expression1 : Expression2 ;
Expression1 should always result in a boolean value
Expression2 can be anything which results in a value. The value is
used to generate a String message that displays more debugging
information
22. Page 21Classification: Restricted
Enabling and disabling Assertions
• Assertions are disabled by default
• Enable assertions at compile time using the –source 1.4 flag
eg: javac – source 1.4 TestClass.java
• Enable assertions at runtime using the flag –enableassertions or –ea.
• For selective disabling of assertions at runtime, use the –da or –
disableassertions flag
• For enabling assertions in the system classes, use the –esa or –dsa flags
• Assertions can be enabled or disabled on a package basis also, and
subpackages are automatically included
23. Page 22Classification: Restricted
When to use Assertions
• Postcondition checks are best implemented via assertions, whether or not
they are in public methods.
• Assertions can be used for precondition checks on nonpublic methods
• Use assertions, even in public methods to check for cases that you know
are never, ever supposed to happen
Eg:
switch(x) {
case 1: z=1;
case 2: z=4;
default: assert false; // Control should never reach
}
24. Page 23Classification: Restricted
When not to use Assertions
• Do not use assertions to validate arguments to a public method
• Do not use assertions to validate command line arguments
• Do not use assert expressions that will cause side effects
eg:
public void func() {
assert (x++==y); /* Should not be done */
}
This means that an assert expression should leave the program in the
same state it was in before the expression
25. Page 24Classification: Restricted
Extra points to remember…
• Assertions can be enabled/disabled programmatically or using command
line switches
• Command Line Examples
eg:
java –ea:com.whiz.Test
// Enables assertions in class com.whiz.Test
java –ea –dsa
// Enable assertions, but disable only in system classes
java -ea:com.wombat.fruitbat...
// Enable assertions in com.wombat.fruitbat package and its
subpackages
26. Page 25Classification: Restricted
Extra points to Remember…
• Curly braces are optional if there is only one statement in the body of if
statement
• The default block can be located anywhere in the switch block, it will be
entered if no case matches
• A variable declared within the for loop declaration cannot be accessed
outside the loop
• The break statement can be used only inside a loop or switch statement,
the continue statement can be used only within a loop
• In a switch case statement, more than one case label using the same
value is not allowed