0% found this document useful (0 votes)
12 views7 pages

Oopr Midterm Reviewer

Oopr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views7 pages

Oopr Midterm Reviewer

Oopr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Module 5 :JAVA CONTROL STATEMENTS –

CONDITIONAL STATEMENTS

Topics:
⊳ Understanding if statements
⊳ Complex conditionals The simple if statement has the following syntax:
⊳ The switch, case, and break statements
 if (<boolean expression>)
Java Statement <statement action>

 One or more lines of code ending with a semi-colon (;).


 Contains expressions (expressions have a value).

1. Simple Statement
 Basic building blocks of a program
 One or more lines terminated by a semicolon (;)

printf("Hello, World!");

2. Compound Statement or Block


 Organize simple statements into complex structures
 One or more statements enclosed by braces { }
 Recommended to indent blocks for readability
Every time Java encounters an if statement,
int main() {
System.out.println ("Hello, "); 1. It determines whether expression is true or false.
System.out.println ("World!"); 2. If expression is true, then Java executes statement.
}
3. If expression is false, then Java ignores or skips the
Control Structure remainder of the if statement and proceeds to the
 Allow to change the ordering of how the statements in next statement.
a program is executed
 Allows a programmer to select and execute specific If Structure: Example 1
blocks of code while skipping other sections.
▸ Suppose that the passing grade on an examination is 75
Types of control structures: (out of 100). Then the if statement may be written in Java as:
1. Decision control structures
▸ allow to select specific sections of code to be
executed
2. Repetition control structures
▸ allow to execute specific sections of the code a If Structure: Example 2
number of times
int grade = 68;
Include types such as: if (grade > 60)
▸ If
▸ If-Else
▸ If-Else-If
▸ Switch structure

1. IF STATEMENT
 executes a block of code only if the specified
expression is true.
 Making a decision involves choosing between two 2. IF-ELSE STATEMENT
alternative courses of action based on some value
within a program.  Extension of the if statement. if the statements in the if
statement fails, the statements in the else block are
executed.
 Making a decision involves choosing between two
alternative courses of action based on some value
within a program.
3. NESTED if STATEMENT
The simple if-else statement has the following syntax:

 If statement that is the target of another if or else.


 Means an if statement inside an if statement.
 Yes, java allows us to nest if statements within if
statements.

i.e, we can place an if statement inside another if


statement.

If-Else Structure: Example 1

Switch, case, and break statements


If-Else Structure: Example 2
1. switch case STATEMENT
 also called a case statement is a multi-way branch with
several choices.
 Easier to implement than a series of if/else statements.

If-Else Structure: Example 3


Topics:
⊳ For Loop
⊳ While Loop
⊳ Do…while Loop

LOOPING STATEMENTS

1. LOOP STATEMENT
 Execute a statement or group of statements multiple
times and following is the general form of a loop
statement in most of the programming languages.

Break statement
• defines the end of a case.

Default statement
CATEGORIES
• use in defining message to be displayed that is outside of
the given case.
1. FOR LOOP

 Execute a sequence of statements multiple times and


abbreviates the code that manages the loop variable.
 It is useful when you know how many times a task is to
be repeated.
 A repetition control structure that allows you to
efficiently write a loop that needs to be executed a
specific number of times.

FOR LOOP DEMO:

Module 6:JAVA CONTROL STATEMENTS :LOOPING


STATEMENTS
3. DO...WHILE LOOP

2. WHILE LOOP  Like a while statement, except that it tests the


condition at the end of the loop body.
 Repeats a statement or group of statements while a  A do...while loop is similar to a while loop, except that
given condition is true. It tests the condition before a do...while loop is guaranteed to execute at least one
executing the loop body. time.
 Repeatedly executes a target statement as long as a
given condition is true. do…while LOOP STATEMENT

while LOOP STATEMENT

DO…WHILE LOOP DEMO

Here, key point of the while loop is that the loop might
not ever run. When the expression is tested and the
result is false, the loop body will be skipped and the
first statement after the while loop will be executed.

WHILE LOOP DEMO:

Module 6: EXCEPTION HANDLING

Topics:
⊳ Exception Hierarchy  IOException – caused by general I/O failures, such as
⊳ Creating Exceptions inability to read from a file
⊳ Try, Catch, and Finally  NullPointerException – caused by referencing a null
object
1. EXCEPTION  NumberFormatException – caused when a
conversion between string and number fails
 An exception is an event, usually some form of error,  OutOfMemoryException – caused when there is not
which happens during the normal course of program enough memory to allocate a new object
execution. The object-oriented technique to manage  SecurityException – caused by a security violation
such errors comprises the group of methods known as such as when an applet tries to perform an action not
exception handling. allowed by the browser’s security setting
 StackOverflowException – caused when a program
Exception Hierarchy attempts to access a nonexistent character position in
a string

Creating Exceptions

GENERATING EXCEPTION

Method Calls
 If a method or constructor is declared to throw an
exception, then calling that method or constructor
may result in an exception of the declared class or a
subclass.

Types of Exceptions

1. ERROR 1. Runtime exceptions


 SERIOUS ERRORS IN THE JAVA RUNTIME SYSTEM
 Can occur even though the offending piece of code
2. EXCEPTION/ CHECKED does not declare that it throws such an exception.
 THE CLASSES WHICH DIRECTLY INHERIT THROWABLE Examples of these exceptions include:
CLASS EXCEPT
 RUNTIMEEXCEPTION AND ERROR ARE KNOWN AS NullPointerException,
CHECKED EXCEPTIONS NORMAL ERRORS THAT CAN ArrayIndexOutOfBoundsException, etc.
OCCUR DURING THE EXECUTION OF A PROGRAM
2. User exceptions
3. RUNTIME EXCEPTION/UNCHECKED
 ENCOMPASSES ALL EXCEPTIONS WHICH CAN  Manually thrown by the programmer using the throw
ORDINARILY HAPPEN AT RUNTIME statement. This statement takes a single argument
which must be an object that is a subclass of
COMMON EXCEPTIONS Throwable. You can either throw an existing exception
class or create your own.
 ArithmeticException – caused by math errors such  throw new Exception(“Problem”);
as division by zero
 ArrayIndexOutOfBoundsException – caused by a Try, Catch, andFinally
bad array index
 ArrayStoreException – caused when a program tries HANDLING EXCEPTION
to store the wrong type of data in an array
 FileNotFoundException – caused by an attempt to 1. Passing On Exceptions
access a nonexistent file
 Refers to letting the method’s caller catch the
exception. When a method declares that it can throw
an exception of a particular type. Within the method
body, it can perform actions which may cause that
type of exception to be thrown.

2. Catching Exceptions

 Refers to declaring that you can handle exceptions of


a particular class from a particular block of code.
 You specify the block of code and then provide
handlers for various classes of exception. If an
SYNTAX KEY ASPECTS
exception occurs then execution transfers to the
corresponding piece of handler code.  The block notation is mandatory.
 The catch blocks and finally blocks must always appear
in conjunction with the try block, and in the above
THE TRY BLOCK order.
 For each try block, there can be one or more catch
 When you create a segment of code in which
blocks, but at most only one
something might go wrong, you place the code in a
 finally block.
try block, which is a block of code you attempt to
 Each catch block defines an exception handle. The
execute while acknowledging that an exception might
header of the catch block takes exactly one argument,
occur. A try block consists of the following format:
which is the exception it will handle. The exception
must be of the Throwable class or one of its subclasses.
 A try block must be followed by finally block. at least
one catch block or one

1. Throws Clause

 Lists the types of exceptions that a method might


throw.
 This is necessary for all exceptions, except those of
THE CATCH BLOCK type Error and Runtime Exception, or any of their
subclasses.
 A catch block is a segment of code that can handle an  All other exceptions that a method can throw must be
exception that might be thrown by the try block that declared in the throws clause. If they are not, a
precedes it. A catch block has the following format: compile-time error will occur.

EXAMPLE:
finishes running. Unlike normal exception/error
handling, assertions are generally disabled at run-time.

Where to use Assertions


 Arguments to private methods. Private arguments are
provided by developer’s code only and developer may
want to check his/her assumptions about arguments.
 Conditional cases.
 Conditions at the beginning of any method.

Where not to use Assertions


ASSERTION IN JAVA  Assertions should not be used to replace error
messages
 Testing the correctness of any assumptionsthat have
 Assertions should not be used to check arguments in
been made in the program.
the public methods as they may be provided by user.
 Achieved using the assert statement in Java. Error handling should be used to handle errors
Whileexecuting assertion, it is believed to be true. If it provided by user.
fails, JVM throws an error named AssertionError. It is
 Assertions should not be used on command line
mainly used for testing purposes during development. arguments.
 Used with a Boolean expression and can be written in
two different ways.

Syntax

Why use Assertions?

▸ To make sure that an unreachable looking code is


actually unreachable.
▸ To make sure that assumptions written in commentsare
right. if else must be even {assert }
▸ To make sure default switch case is not reached.
▸ To check object’s state.
▸ In the beginning of the method
▸ After method invocation.

Assertion Vs Normal Exception Handling

 Mainly used to check logically impossible situations.


For example, they can be used to check the state a
code expects before it starts running or state after it

You might also like