You are on page 1of 120

OUR LADY OF FATIMA UNIVERSITY

COLLEGE OF COMPUTER STUDIES


OOPR211
OBJECT-ORIENTED
PROGRAMMING I
MIDTERM ROADMAP
CONDITIONAL LOOPING EXCEPTION
STATEMENTS STATEMENTS HANDLING
7 9 11

8 10 12

CONDITIONAL LOOPING MIDTERM


STATEMENTS STATEMENTS EXAMINATION
5
Module : JAVA CONTROL STATEMENTS –
CONDITIONAL
STATEMENTS
Module Objectives:

1 2

Define what is a Practice problem


control structure and solving solution using
differentiate the types a different approach
of conditional like conditionals
statements. statement.
Topics:

⊳ Understanding if statements
⊳ Complex conditionals
⊳ The switch, case, and break statements
Java Statement

In Java, a statement is one or more lines


of code ending with a semi-colon (;).

It generally contains expressions


(expressions have a value).
Java Statement

⊳ Simple Statement ⊳ Compound Statement or


Block
▸ Basic building blocks of a
program ▸ Used to organize simple
▸ One or more lines terminated statements into complex
by a semicolon (;) structures
▸ One or more statements
printf(Hello, World!”);
enclosed by braces { }
▸ Recommended to indent
int main() { blocks for readability
System.out.println (“Hello, ”);
System.out.println (“World!”);
}
Control Structure

⊳ Control structures allow to change the ordering of


how the statements in a program is executed
⊳ Types of control structures:
▸ Decision control structures

▸ allow to select specific sections of code to be


executed
▸ Repetition control structures
▸ allow to execute specific sections of the code a
number of times
Control Structure

⊳ Java statements that allows a programmer to select


and execute specific blocks of code while skipping
other sections.
⊳ Include types such as:
▸ If

▸ If-Else

▸ If-Else-If

▸ Switch structure
Understanding
1 if statements
THE if STATEMENT

The simple if statement has the following syntax:


if (<boolean expression>)
<statement action>

THE IF STATEMENT EXECUTES A BLOCK OF CODE


ONLY IF THE SPECIFIED EXPRESSION IS TRUE.
THE if STATEMENT
THE if STATEMENT
Every time Java encounters an if statement,
1. It determines whether expression is true or
false.
2. If expression is true, then Java executes
statement.
3. If expression is false, then Java ignores or skips
the remainder of the if statement and proceeds
to the next statement.
THE if STATEMENT
Making a decision involves choosing between two alternative
courses of action based on some value within a program.

NO YES
Boolean
expression
THE if STATEMENT

If Structure: Example 1

▸ Suppose that the passing grade on an examination is 75 (out


of 100). Then the if statement may be written in Java as:

if (grade >= 75)


System.out.println(“You Passed!”);
THE if STATEMENT

If Structure: Example 2

int grade = 68;


if (grade > 60)
{
System.out.println(“Congratulations!”);
System.out.println(“You Passed!”);
}
EXERCISES:

1. Test if the value of the variable count is greater than 10. If the
answer is yes, print “Count is greater than 10”.

2. Test if the value of the variable number is an odd number. If the


answer is yes, print “This number is not an even number.”

3. Test if the value of the variable age is greater than 18 and less than
or equal to 40. If the answer is yes, print “You’re not getting old!”
18
2 Complex
conditionals
THE if-else STATEMENT
The simple if-else statement has the following
syntax:
if (<boolean expression>)
<statement 1>
else
<statement 2>
THE IF/ELSE STATEMENT IS AN EXTENSION OF THE IF
STATEMENT. IF THE STATEMENTS IN THE IF STATEMENT FAILS,
THE STATEMENTS IN THE ELSE BLOCK ARE EXECUTED.
THE if-else STATEMENT
THE if-else STATEMENT

⊳ Making a decision involves


choosing between two
alternative courses of NO YES
Boolean
action based on some value expression
within a program.
THE if-else STATEMENT

If-Else Structure: Example 1


int grade = 68;
if (grade > 60)
System.out.println(“Congratulations!”);
else
System.out.println(“Sorry you failed!”);
THE if-else STATEMENT
If-Else Structure: Example 2
int grade = 68;
if (grade > 60) {
System.out.println(“Congratulations!”);
System.out.println(“You Passed!”);
}
else {
System.out.println(“Sorry you failed!”);
}
THE if-else STATEMENT
If-Else Structure: Example 3
int choice = 0;
if (choice == 1)
{
num = 1;
num2 = 10;
}
else
{
num = 2;
num2 = 20;
}
EXERCISES:

1. Test if the value of the variable count is greater than 10. If it is,
print “Count is greater than 10”, otherwise, print “Count is less
than 10”.
2. Test if the value of the variable number is an odd number. If it is,
print “This number is not an even number” otherwise, print “This
number is an odd number.”
3. Test if the value of the variable age is greater than 18 and less
than or equal to 40. If it is, print “You’re not getting old!”
otherwise, print “You’re not getting younger.”
26
NESTED if STATEMENT
NESTED if STATEMENT

⊳ A nested if is an if statement that if (condition1)


is the target of another if or else. {
Nested if statements means an if // Executes when
statement inside an if statement. condition1 is true
Yes, java allows us to nest if if (condition2)
statements within if statements. {
i.e, we can place an if statement
// Executes when
inside another if statement.
condition2 is true
}
}
3 The switch, case,
and break
statements
switch case STATEMENT

ALSO CALLED A CASE STATEMENT IS A


MULTI-WAY BRANCH WITH SEVERAL
CHOICES.
A SWITCH IS EASIER TO IMPLEMENT THAN A SERIES OF
IF/ELSE STATEMENTS.
switch case STATEMENT
switch case STATEMENT

break statement
• defines the end of a case.
switch case STATEMENT

default statement
• use in defining message to be displayed
that is outside of the given case.
switch case
int grade = 92;

switch case
switch (grade) {
case 100:
System.out.println(“Excellent!”);
break;
case 90:
System.out.println(“Good!”);
break;
case 80:
System.out.println(“Study Harder!”);
break;
default:
System.out.println(“You failed!”);
}
Write a program to output summation of a
set of numbers.
Example Output:
Please input how many numbers you
would like to add: 4
Check your Please enter a value: 3
Please enter a value: 1
Understanding Please enter a value: 2
Please enter a value: 3
The sum of the 4 values is 9
Write a program which
should be able to reproduce
the following example
Check your output:

Understanding
QUESTIONS?
Thank you!
Credits

Special thanks to all the people who made and released


these awesome resources for free:
⊳ Presentation template by SlidesCarnival
⊳ Photographs by Unsplash
Additional References:

⊳ https://www.edureka.co/blog/what-is-java/
⊳ http://ecomputernotes.com/java/what-is-java-
language/types-of-java-programs
⊳ https://app.codechum.com/teacher/classes/504/tim
eline/lessons/java-conditionals/if-statement
OUR LADY OF FATIMA UNIVERSITY
COLLEGE OF COMPUTER STUDIES
OUR LADY OF FATIMA UNIVERSITY
COLLEGE OF COMPUTER STUDIES
OOPR211
OBJECT-ORIENTED
PROGRAMMING I
MIDTERM ROADMAP
CONDITIONAL LOOPING EXCEPTION
STATEMENTS STATEMENTS HANDLING
7 9 11

8 10 12

CONDITIONAL LOOPING MIDTERM


STATEMENTS STATEMENTS EXAMINATION
6
Module : JAVA CONTROL STATEMENTS –
LOOPING
STATEMENTS
Module Objectives:

1 2

Know the syntax of the Practice Problem


repetition structure. solving solution using
a different approach
like looping statement.
Topics:

⊳ For Loop
⊳ While Loop
⊳ Do…while Loop
LOOPING STATEMENTS

LOOP STATEMENT
ALLOWS US TO 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.
CATEGORIES
• Execute a sequence of statements multiple
for loop times and abbreviates the code that manages
the loop variable.

while • Repeats a statement or group of statements


while a given condition is true. It tests the
loop condition before executing the loop body.

do...while • Like a while statement, except that it tests the


condition at the end of the loop body.
loop
Understanding
1 for loop
IT IS USEFUL WHEN YOU KNOW
HOW MANY TIMES A TASK IS TO
BE REPEATED.

for LOOP
A REPETITION CONTROL STRUCTURE THAT
ALLOWS YOU TO EFFICIENTLY WRITE A LOOP
THAT NEEDS TO BE EXECUTED A SPECIFIC
NUMBER OF TIMES.
for LOOP STATEMENT

for(initialization; Boolean_expression; update) {


// Statements
}
for LOOP DEMO
OUTPUT
Understanding
2 while loop
while LOOP
A WHILE LOOP STATEMENT IN JAVA
PROGRAMMING LANGUAGE REPEATEDLY
EXECUTES A TARGET STATEMENT AS LONG AS
A GIVEN CONDITION IS TRUE.
while LOOP STATEMENT

while(Boolean_expression) {
// Statements
}
while
• 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
OUTPUT
Understanding
3 do…while loop
do…while LOOP
A DO...WHILE LOOP IS SIMILAR TO A WHILE
LOOP, EXCEPT THAT A DO...WHILE LOOP IS
GUARANTEED TO EXECUTE AT LEAST ONE
TIME.
do…while LOOP STATEMENT

do {
// Statements
}while(Boolean_expression);
do-while
do…while LOOP DEMO
OUTPUT
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
EXERCISES:

1. Test if the value of the variable count is greater than 10. If it is,
print “Count is greater than 10”, otherwise, print “Count is less
than 10”.
2. Test if the value of the variable number is an odd number. If it is,
print “This number is not an even number” otherwise, print “This
number is an odd number.”
3. Test if the value of the variable age is greater than 18 and less
than or equal to 40. If it is, print “You’re not getting old!”
otherwise, print “You’re not getting younger.”
27
Write a program to output summation of a
set of numbers.
Example Output:
Please input how many numbers you
would like to add: 4
Check your Please enter a value: 3
Please enter a value: 1
Understanding Please enter a value: 2
Please enter a value: 3
The sum of the 4 values is 9
Write a program which
should be able to reproduce
the following example
Check your output:

Understanding
QUESTIONS?
Thank you!
Credits

Special thanks to all the people who made and released


these awesome resources for free:
⊳ Presentation template by SlidesCarnival
⊳ Photographs by Unsplash
Additional References:

⊳ https://www.edureka.co/blog/what-is-java/
⊳ http://ecomputernotes.com/java/what-is-java-
language/types-of-java-programs
⊳ https://app.codechum.com/teacher/classes/504/tim
eline/lessons/java-loops/for-loop/

33
OUR LADY OF FATIMA UNIVERSITY
COLLEGE OF COMPUTER STUDIES
OUR LADY OF FATIMA UNIVERSITY
COLLEGE OF COMPUTER STUDIES
OOPR211
OBJECT-ORIENTED
PROGRAMMING I
MIDTERM ROADMAP
CONDITIONAL LOOPING EXCEPTION
STATEMENTS STATEMENTS HANDLING
7 9 11

8 10 12

CONDITIONAL LOOPING MIDTERM


STATEMENTS STATEMENTS EXAMINATION
7
Module :
EXCEPTION
HANDLING
Module Objectives:

1 2

Understand the usage Utilize the use of


of Exception handling Exception handling in
in Java creating Java program
Topics:

⊳ Exception Hierarchy
⊳ Creating Exceptions
⊳ Try, Catch, and Finally
What is
EXCEPTION?
Exception

⊳ An exception is an event, usually some form of error,


which happens during the normal course of program
execution. The object-oriented technique to manage
such errors comprises the group of methods known
as exception handling.
1 Exception
Hierarchy
Types of Exceptions

ERROR
SERIOUS ERRORS IN THE JAVA RUNTIME
SYSTEM
Types of Exceptions

EXCEPTION/ CHECKED
THE CLASSES WHICH DIRECTLY INHERIT
THROWABLE CLASS EXCEPT
RUNTIMEEXCEPTION AND ERROR ARE KNOWN
AS CHECKED EXCEPTIONS NORMAL ERRORS
THAT CAN OCCUR DURING THE EXECUTION
OF A PROGRAM
Types of Exceptions
RUNTIME
EXCEPTION/UNCHECKED
ENCOMPASSES ALL EXCEPTIONS WHICH CAN
ORDINARILY HAPPEN AT RUNTIME
COMMON EXCEPTIONS
⊳ ArithmeticException – caused by ⊳ IOException – caused by general I/O
math errors such as division by zero failures, such as inability to read from
⊳ ArrayIndexOutOfBoundsException – a file
caused by a bad array index ⊳ NullPointerException – caused by
⊳ ArrayStoreException – caused when referencing a null object
a program tries to store the wrong ⊳ NumberFormatException – caused
type of data in an array when a conversion between string
⊳ FileNotFoundException – caused by and number fails
an attempt to access a nonexistent
file
COMMON EXCEPTIONS
⊳ OutOfMemoryException – caused when there is not
enough memory to allocate a new object
⊳ SecurityException – caused by a security violation
such as when an applet tries to perform an action
not allowed by the browser’s security setting
⊳ StackOverflowException – caused when a program
attempts to access a nonexistent character position
in a string
2 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.
int method() throws IOException {
...
}

method(); // this can throw an IOException


GENERATING EXCEPTION
⊳ Runtime exceptions
⊳ These exceptions can occur even though the
offending piece of code does not declare that it
throws such an exception. Examples of these
exceptions include:
NullPointerException,
ArrayIndexOutOfBoundsException, etc.
GENERATING EXCEPTION
⊳ User exceptions
⊳ These are exceptions that are manually thrown by
the programmer using the throw statement. This
statement takes a single argument which must be an
object that is a subclass of Throwable. You can either
throw an existing exception class or create your
own.
⊳ throw new Exception(“Problem”);
3 Try, Catch, and
Finally
HANDLING EXCEPTION
⊳ Passing On Exceptions
⊳ Passing on an exception 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.
HANDLING EXCEPTION
⊳ Catching Exceptions
⊳ Catching an exception 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
exception occurs then execution transfers to the
corresponding piece of handler code.
The try Block
When you create a segment of code in which something might go wrong, you place the code
in a try block, which is a block of code you attempt to execute while acknowledging that an
exception might occur. A try block consists of the following format:

try {
//statements that can generate an exception
//here
}
catch and finally blocks…
The catch Block

A catch block is a segment of code that can handle an exception that might be thrown by the
try block that precedes it. A catch block has the following format:

try {
}
catch (ExceptionType name) {
//action your program will do if an exception
//of a certain type occurs
}
finally blocks…
EXAMPLE:

public class TryCatchDemo1 {


public static void main(String[] args) {
int num, denom, result;
try {
result = num / denom;
}
catch(ArithmeticException mistake)
{ System.out.println(″Attempt to divide by zero″);
}}} 25
EXAMPLE:
public class TryCatchDemo2 {
public static void main(String[] args) {
int num[] = {4, 0, 0};
int i, j;
try {
num[2] = num[0] / num[i];
num[2] = num[j] / num[0]; }
catch(ArithmeticException e) { System.out.println(″Arithmetic error″);
}
catch(IndexOutOfBoundsException e) {
26
System.out.println(″Out of bounds error″); }}}
SYNTAX KEY ASPECTS

The catch blocks and finally


For each try block, there can be
blocks must always appear in
The block notation is mandatory. one or more catch blocks, but at
conjunction with the try block,
most only one finally block.
and in the above order.

Each catch block defines an


exception handle. The header of
the catch block takes exactly one
A try block must be followed by
finally block. argument, which is the exception
at least one catch block or one
it will handle. The exception must
be of the Throwable class or one
of its subclasses.
Throws Clause
⊳ A throws clause lists the types of exceptions that a
method might throw. This is necessary for all
exceptions, except those of type Error and Runtime
Exception, or any of their subclasses.
⊳ All other exceptions that a method can throw must
be declared in the throws clause. If they are not, a
compile-time error will occur.
Throws Clause

<return type> <method name>(<parameter list>)


throws
<exception list> {
//body of method
}
Throws Clause
Example 1:
public void SampleDemo(String destinationFile) throws
IOException {
//code here…
}
Throws Clause
Example 2: illustrating more than one exception.

public void SampleDemo() throws IOException,


ArrayIndexOutOfBoundsException {
//code here…
}
Assertion In Java
⊳ An assertion allows testing the correctness of any assumptions
that have been made in the program.
⊳ Assertion is achieved using the assert statement in Java. While
executing assertion, it is believed to be true. If it fails, JVM
throws an error named AssertionError. It is mainly used for
testing purposes during development.
⊳ The assert statement is used with a Boolean expression and
can be written in two different ways.
Assertion In Java
⊳ Syntax

First way :
assert expression;

Second way :
assert expression1 : expression2;
Assertion In Java
import java.util.Scanner;

class Test
{
public static void main( String args[] )
{
int value = 15;
assert value >= 20 : " Underweight";
System.out.println("value is "+value);
}
}
Why use Assertions?
▸ To make sure that an unreachable looking code is
actually unreachable.
▸ To make sure that assumptions written in comments
are right. if ((x & 1) == 1) { } else // x must be even
{ assert (x % 2 == 0); }
▸ To make sure default switch case is not reached.
▸ To check object’s state.
▸ In the beginning of the method
▸ After method invocation.
Assertion In Java
Assertion Vs Normal Exception Handling

⊳ Assertions are 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 finishes running. Unlike
normal exception/error handling, assertions are
generally disabled at run-time.
Assertion In Java
Assertion Vs Normal Exception Handling

⊳ Assertions are 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 finishes running. Unlike
normal exception/error handling, assertions are
generally disabled at run-time.
Assertion In Java
⊳ 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.


Assertion In Java
⊳ Where not to use Assertions
▸ Assertions should not be used to replace error

messages
▸ Assertions should not be used to check

arguments in the public methods as they may be


provided by user. Error handling should be used
to handle errors provided by user.
▸ Assertions should not be used on command line

arguments.
QUESTIONS?
Thank you!
Credits

Special thanks to all the people who made and released


these awesome resources for free:
⊳ Presentation template by SlidesCarnival
⊳ Photographs by Unsplash
Additional References:

⊳ https://www.edureka.co/blog/what-is-java/
⊳ http://ecomputernotes.com/java/what-is-java-
language/types-of-java-programs
OUR LADY OF FATIMA UNIVERSITY
COLLEGE OF COMPUTER STUDIES

You might also like