ITec121 BSIT

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 46

ITec121

Object
Oriented
Programming

RICA MAE O. VICENTE


College of
Engineering and
Technology

Department of
Information Technology
ii

No copies temporary or permanent, in whole or part of this


IM shall be made without written permission from the
author/s.

Page ii of xlvii
Vision: A globally competitive university for science, technology, and environmental conservation.
Mission: Development of a highly competitive human resource, cutting-edge scientific knowledge TP-IMD-02
V0 07-15-2020
and innovative technologies for sustainable communities and environment.
No.
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

Vision

A globally competitive university for science, technology, and


environmental conservation

Mission

Development of a highly competitive human resource,


cutting-edge scientific knowledge and innovative
technologies for sustainable communities and environment.

Quality Policy

The Visayas State University (VSU) is a higher education institution created by


law to provide excellent instruction, conduct relevant research and foster
community engagement that produce highly competent graduates necessary
for the development of the country. Toward this end, we, at the Visayas State
University, commit to:
1. produce highly competent, quality and world-class manpower in
science and technology (S&T), especially for agriculture,
environmental management and industry who are proficient in
communication skills, critical thinking and analytical abilities,
2. generate and disseminate relevant knowledge and technology that
lead to improved productivity, profitability and sustainability in
agriculture, environment and industry,
3. satisfy the needs of the industry, the community and government
sector who are in need of quality graduates and technology ready for
commercialization through the establishment, operation, maintenance
ii

and continuous improvement of a Quality Management System which


is aligned with the requirements of ISO 9001:2015.
It shall be the policy of the university that the quality policies and procedures
are communicated to and understood by all faculties, staff, students and
other stakeholders and that the system shall be continually improved for their
relevance and effectiveness.
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

Learning Guide in

ITec121: Object Oriented


Programming
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

Foreword

The year 2020 has been challenging, not just here in the Philippines but in the
whole world. In an instant, the methods of teaching shifted dramatically to flexible
learning, and the word modules and online classes become part of our daily language.
From elementary to tertiary, both private and public institutions, these words are
often the major topic of discussion. As one of the higher institutions in the region,
Visayas State University took the challenge of adapting flexible learning instead of
having face-to-face classes for the first semester this school year.
The Faculties of the Department of Industrial Engineering of the Visayas
State University – Isabel took the challenge of producing learning guides, which will
help you learn at your own pace and time. Inside this guide are notes and discussions
of the courses, greatly designed to grasp the ideas, theories, and technical ability
needed in your respective fields.
As you experience learning your courses thru these learning guides, we are
extremely hopeful that you will enjoy learning and gain the knowledge and skills
necessary in your chosen field. As all of these are still very new to all of us, rest
assured that we, all of your instructors, are very much willing to help and guide you
in navigating this new normal education.

RICHARD C. ABALLE
College Dean
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

Acknowledgment

Object Oriented Programming is written to continue to give education to our


students despite of this pandemic.
With this, we want to give our thanks to all the people behind the creation of this
learning guide. This learning guide will not be in reality if not with the help of
computer technology, the authors of the book used, and the content creators.
Similarly, we convey our gratitude to those individuals who encourage us to write
and turn this learning guide into reality.
We also acknowledge our colleagues at the VSU-I, particularly in the College of
Engineering and Technology for giving us the support in writing this module.
Finally, yet the most important, we give honor and thanks to our Lord Almighty for
giving us strength in making this learning guide, guided us, and blessed us in so many
ways.
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

About the Compiler/s


RICA MAE O. VICENTE
A Part-Time Instructor at the Department of
Information and Technology who gained his
bachelor’s in Information Technology at
Visayas State University Isabel.
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

Table of Contents

Contents
Vision.......................................................................................................................i
Mission.....................................................................................................................i
Quality Policy..........................................................................................................i
Title Page.................................................................................................................i
Foreword................................................................................................................ii
Acknowledgment..................................................................................................iii
About the Compiler/s............................................................................................iv
Table of Contents...................................................................................................v

Module 1: Introduction and Overview of Java Programming.......1


Module Pretest.....................................................................................................1
Lesson 1.1: Introduction to Java...........................................................................3
Discussion............................................................................................................3
Lesson 1.2: Java Variables and Identifiers..........................................................7
Discussion............................................................................................................7
Lesson 1.3: Java Data Types...............................................................................13
Discussion..........................................................................................................13
Lesson 1.4 Java Operators..................................................................................21
Module Posttest.................................................................................................24
References and Additional Resources................................................................25
Answers to Pretest and Posttest..........................................................................25

Module 2: Conditionals and Control Flow..................................26


Module Pretest...................................................................................................26
Lesson 2.1: Java Conditions and If Statements.................................................27
Discussion.........................................................................................................28
Lesson 2.2: Java Switch Statements...................................................................34
Discussion..........................................................................................................34
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

Module 1: Introduction and


Overview of Java Programming
Module Overview
Java is basically object-oriented. These days, Java is often the choice
for scientific applications, including natural language processing. The main
point for this is because it is safe, portable, maintainable and comes with better
high-level concurrency tools than any other languages. This module introduces
the java programming language and how it is implemented in the program.

Motivation Question

What is the essence of studying Java Programming Language?

Module Pretest
IDENTIFICATION: Write your answers before each number
_______________ 1. general-purpose, class-based, object-oriented
programming language designed for having lesser implementation
dependencies.
_______________ 2. Java variables must be identified with unique names.

_______________ 3. Java variables that stores integers (whole numbers),


without decimals, such as 123 or -123

_______________ 4. Containers for storing data values.


_______________ 5. It is a popular programming language, created in 1995.
_______________ 6. Java variable that stores values with two states: true or
false

Page 1 of 47
Vision: A globally competitive university for science, technology, and environmental conservation.
Mission: Development of a highly competitive human resource, cutting-edge scientific knowledge TP-IMD-02
V0 07-15-2020
and innovative technologies for sustainable communities and environment.
No.
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

________________ 7. Java variable that stores single characters, such as 'a' or 'B'.
Char values are surrounded by single quotes
________________ 8. defined as specifiers that allocate different sizes and
types of values that can be stored in the variable or an identifier.
________________ 9. Data type that includes integer, character, boolean, and
float
________________ 10. Data type that includes classes, arrays and interfaces.

Lesson 1.1: Introduction to


Java
Lesson Summary
Java is a general-purpose, class-based, object-oriented programming language
designed for having lesser implementation dependencies. It is a computing
platform for application development. Java is fast, secure, and reliable,
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

therefore. It is widely used for developing Java applications in laptops, data


centers, game consoles, scientific supercomputers, cell phones, etc.

Learning Outcomes
At the end of the lesson, you are expected to:
1. Define what is java and what it is used for.
2. Install and set-up java.
3. Print “Hello world” in java.

Why Java is widely used for developing a program?

Discussion

Programming languages enable humans to write instructions that a computer


can perform. With precise instructions, computers coordinate applications and
systems that run the modern world.

Sun Microsystems released the Java programming language in 1995. Java is


known for being simple, portable, secure, and robust. Though it was released
over twenty years ago, Java remains one of the most popular programming
languages today.

One reason people love Java is the Java Virtual Machine, which ensures the
same Java code can be run on different operating systems and platforms. Sun
Microsystems’ slogan for Java was “write once, run everywhere”.
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

Figure 1. Java Program


https://www.codecademy.com/courses/learn-java/lessons/hello-world-java/exercises/introduction-to-java

It is owned by Oracle, and more than 3 billion devices run Java.

It is used for:

 Mobile applications (specially Android apps)


 Desktop applications
 Web applications
 Web servers and application servers
 Games
 Database connection
 And much, much more!
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

Why Use Java?

 Java works on different platforms (Windows, Mac, Linux, Raspberry


Pi, etc.)
 It is one of the most popular programming language in the world
 It is easy to learn and simple to use
 It is open-source and free
 It is secure, fast and powerful
 It has a huge community support (tens of millions of developers)
 Java is an object oriented language which gives a clear structure to
programs and allows code to be reused, lowering development costs
 As Java is close to C++ and C#, it makes it easy for programmers to
switch to Java or vice versa

Install Java on Windows


Install Java on Smartphone

Java Syntax
The main Method

The main() method is required and you will see it in every Java program:

public static void main(String[] args)

Any code inside the main() method will be executed. You don't have to


understand the keywords before and after main. You will get to know them bit
by bit while reading this tutorial.

For now, just remember that every Java program has a class name which must
match the filename, and that every program must contain the main() method.

System.out.println()

Inside the main() method, we can use the println() method to print a line of


text to the screen:

public static void main(String[] args) {

System.out.println("Hello World");

}
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

In the previous chapter, we created a Java file called Main.java, and we used


the following code to print "Hello World" to the screen:

Assessment
1. Print “Hello I’m ________(your name)” in java.

Instruction on how to submit student output

Lesson 1.2: Java Variables and


Identifiers
Lesson Summary
This lesson contains discussion about different java variables and identifiers.

Learning Outcomes
At the end of this lesson, you are expected to:
1. Identify and apply the different type of variables and identifiers.

Motivation Question
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

What is the use of variables in programming?

Discussion

What is Variable in Java?


Variable in Java is a data container that stores the data values during
Java program execution. Every variable is assigned data type which
designates the type and quantity of value it can hold. Variable is a
memory location name of the data.

In Java, there are different types of variables, for example:

 String - stores text, such as "Hello". String values are surrounded by


double quotes
 int - stores integers (whole numbers), without decimals, such as 123 or
-123
 float - stores floating point numbers, with decimals, such as 19.99 or
-19.99
 char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
 boolean - stores values with two states: true or false

In order to use a variable in a program you to need to perform 2 steps

1. Variable Declaration
2. Variable Initialization

Variable Declaration

To declare a variable, you must specify the data type & give
the variable a unique name.
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

Figure 2. Java declaration


https://www.guru99.com/java-variables.html

Examples of other Valid Declarations are


int a,b,c;

float pi;

double d;

char a;

Variable Initialization:
To initialize a variable, you must assign it a valid value.

Figure 3. Java Container


https://www.guru99.com/java-variables.html
Example of other Valid Initializations are
pi =3.14f;

do =20.22d;

a=’v’;
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

You can combine variable declaration and initialization.

Example :
int a=2,b=4,c=6;

float pi=3.14f;

double do=20.22d;

char a=’v’;

Display Variables

The println() method is often used to display variables.

To combine both text and a variable, use the + character:

Example (Try it Yourself)


String name = "John";

System.out.println("Hello " + name);

You can also use the + character to add a variable to another


variable:

Example
String firstName = "John ";

String lastName = "Doe";

String fullName = firstName + lastName;

System.out.println(fullName);
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

For numeric values, the + character works as a mathematical operator (notice that


we use int (integer) variables here):

Example
int x = 5;

int y = 6;

System.out.println(x + y); // Print the value of x + y

From the example above, you can expect:

 x stores the value 5


 y stores the value 6
 Then we use the println() method to display the value of x + y, which is 11

Declare Many Variables


To declare more than one variable of the same type, use a comma-separated list:

Example
int x = 5, y = 6, z = 50;

System.out.println(x + y + z);

Java Identifiers

All Java variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).

Note: It is recommended to use descriptive names in order to create


understandable and maintainable code:

Example
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

// Good

int minutesPerHour = 60;

// OK, but not so easy to understand what m actually is

int m = 60;

The general rules for constructing names for variables (unique identifiers) are:

 Names can contain letters, digits, underscores, and dollar signs


 Names must begin with a letter
 Names should start with a lowercase letter and it cannot contain
whitespace
 Names can also begin with $ and _ (but we will not use it in this tutorial)
 Names are case sensitive ("myVar" and "myvar" are different variables)
 Reserved words (like Java keywords, such as int or boolean) cannot be
used as names

Assessment
1. Create Variable “carName” and assign “Volvo” to it.
2. Create and add three (3) integer type variables.
Instruction on how to submit student output
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

Lesson 1.3: Java Data Types


Lesson Summary
Variables are nothing but reserved memory locations to store values.
This means that when you create a variable you reserve some space
in the memory. Based on the data type of a variable, the operating
system allocates memory and decides what can be stored in the
reserved memory. Therefore, by assigning different data types to
variables, you can store integers, decimals, or characters in these
variables.
Learning Outcomes
At the end of the discussion, you are expected to:
1. Differentiate the two parts of data type
2. Apply the correct data type in the variables into the code
Motivational Question

What is Java Data Type?

Discussion

Data Types in Java are defined as specifiers that allocate different


sizes and types of values that can be stored in the variable or an
identifier. Java has a rich set of data types. Data types in Java can be
divided into two parts :

1. Primitive Data Types :- which include integer, character,


boolean, and float
2. Non-primitive Data Types :- which include classes, arrays
and interfaces.
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

Figure 3. Data Type


https://www.guru99.com/java-variables.html

Primitive Data Types

A primitive data type specifies the size and type of variable values, and it has
no additional methods.

There are eight primitive data types in Java:


For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

Table 1. Eight Primitive Data Types


https://www.w3schools.com/java/java_data_types.asp

Numbers

Primitive number types are divided into two groups:

Integer types stores whole numbers, positive or negative (such as 123 or


-456), without decimals. Valid types are byte, short, int and long. Which type
you should use, depends on the numeric value.

Floating point types represents numbers with a fractional part, containing one


or more decimals. There are two types: float and double.

Integer Types
Byte

The byte data type can store whole numbers from -128 to 127. This can be
used instead of int or other integer types to save memory when you are certain
that the value will be within -128 and 127:

Example (Try it yourself)

byte myNum = 100;

System.out.println(myNum);

Short

The short data type can store whole numbers from -32768 to 32767:

Example

short myNum = 5000;

System.out.println(myNum);

Int

The int data type can store whole numbers from -2147483648 to


2147483647. In general, and in our tutorial, the int data type is the preferred
data type when we create variables with a numeric value.

Example

int myNum = 100000;

System.out.println(myNum);
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

Long

The long data type can store whole numbers from -9223372036854775808 to


9223372036854775807. This is used when int is not large enough to store the
value. Note that you should end the value with an "L":

Example

long myNum = 15000000000L;

System.out.println(myNum);

Floating Point Types

You should use a floating point type whenever you need a number with a
decimal, such as 9.99 or 3.14515.

Float

The float data type can store fractional numbers from 3.4e−038 to 3.4e+038.


Note that you should end the value with an "f":

Example

float myNum = 5.75f;

System.out.println(myNum);

Double

The double data type can store fractional numbers from 1.7e−308 to 1.7e+308.


Note that you should end the value with a "d":

Example

double myNum = 19.99d;

System.out.println(myNum);

Scientific Numbers

A floating point number can also be a scientific number with an "e" to indicate
the power of 10:

Example

float f1 = 35e3f;
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

double d1 = 12E4d;

System.out.println(f1);

System.out.println(d1);

Booleans

A boolean data type is declared with the boolean keyword and can only take
the values true or false:

Example

boolean isJavaFun = true;

boolean isFishTasty = false;

System.out.println(isJavaFun); // Outputs true

System.out.println(isFishTasty); // Outputs false

Characters

The char data type is used to store a single character. The character must be


surrounded by single quotes, like 'A' or 'c':

Example

char myGrade = 'B';

System.out.println(myGrade);

Strings

The String data type is used to store a sequence of characters (text). String


values must be surrounded by double quotes:

Example

String greeting = "Hello World";

System.out.println(greeting);

Non-Primitive Data Types

Non-primitive data types are called reference types because they refer to


objects.

The main difference between primitive and non-primitive data types are:


For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

 Primitive types are predefined (already defined) in Java. Non-primitive


types are created by the programmer and is not defined by Java (except
for String).
 Non-primitive types can be used to call methods to perform certain
operations, while primitive types cannot.
 A primitive type has always a value, while non-primitive types can
be null.
 A primitive type starts with a lowercase letter, while non-primitive
types starts with an uppercase letter.
 The size of a primitive type depends on the data type, while non-
primitive types have all the same size.

Java Type Casting

Type casting is when you assign a value of one primitive data


type to another type.

In Java, there are two types of casting:

 Widening Casting (automatically) - converting a smaller


type to a larger type size
byte -> short -> char -> int -> long -> float -> double

 Narrowing Casting (manually) - converting a larger type


to a smaller size type
double -> float -> long -> int -> char -> short -> byte

Widening Casting

Widening casting is done automatically when passing a smaller


size type to a larger size type:

Example
public class Main {

public static void main(String[] args) {

int myInt = 9;

double myDouble = myInt; // Automatic casting: int to


double
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

System.out.println(myInt); // Outputs 9

System.out.println(myDouble); // Outputs 9.0

Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses in front of the
value:

Example

public class Main {

public static void main(String[] args) {

double myDouble = 9.78d;

int myInt = (int) myDouble; // Manual casting: double


to int

System.out.println(myDouble); // Outputs 9.78

System.out.println(myInt); // Outputs 9

Learning Task/Activities

Directions: Fill in the Box the correct data type for the following
variables:

myNum = 9;
myFloatNum = 8.99f;
myLetter = 'A';
myBool = false;
myText = "Hello World";
Fname = “Dela Cruz”;
myAge = 22;
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

MyGrade = 'A+’;
javaIsfun = true;
myNum = 20.05D;

Assessment

1. Create a program that display your name, age, birthdate, Course


and year using the data types.

Instructions on how to submit student output


For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

Lesson 1.4 Java Operators


Lesson Summary

This lesson contains discussions about java operators such as arithmetic


operators, comparison operators, assignment operators and logical operators.

Learning Outcomes

At the end of discussion, you are expected to:

1. Identify the different kinds of operators


2. Apply the operators to the code.

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Example
int x = 100 + 50;

Although the + operator is often used to add together two values, like in the
example above, it can also be used to add together a variable and a value, or a
variable and another variable:

Example
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)

Java divides the operators into the following groups:


Arithmetic operators
Assignment operators
Comparison operators
Logical operators
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

Table 2. Arithmetic operators


https://www.w3schools.com/java/java_operators.asp

Java Assignment Operators


Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:

Example
int x = 10;

The addition assignment operator (+=) adds a value to a variable:

Example
int x = 10;

x += 5;

A list of all assignment operators:


For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

Table 3. Assignment operators


https://www.w3schools.com/java/java_operators.asp

Java Comparison Operators

Comparison operators are used to compare two values:

Table 4. Comparison Operators


https://www.w3schools.com/java/java_operators.asp
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

Java Logical Operators

Logical operators are used to determine the logic between variables or values:

Table 5,. Logical operators


https://www.w3schools.com/java/java_operators.asp

Assessment
1. Write a Java program to print the result of the following
operations.
a. 5 + 8 * 6
b. 20 + 3*5 / 8

Instruction on how to submit student output

Module Posttest

IDENTIFICATION: Write your answers before each number


_______________ 1. general-purpose, class-based, object-oriented
programming language designed for having lesser implementation
dependencies.
_______________ 2. Java variables must be identified with unique names.

_______________ 3. Java variables that stores integers (whole numbers),


without decimals, such as 123 or -123

_______________ 4. Containers for storing data values.


_______________ 5. It is a popular programming language, created in 1995.
_______________ 6. Java variable that stores values with two states: true or
false
________________ 7. Java variable that stores single characters, such as 'a' or 'B'.
Char values are surrounded by single quotes
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

________________ 8. defined as specifiers that allocate different sizes and


types of values that can be stored in the variable or an identifier.
________________ 9. Data type that includes integer, character, boolean, and
float
________________ 10. Data type that includes classes, arrays and interfaces.

References and Additional Resources

1. Java Data Types


https://www.tutorialspoint.com/java/java_basic_datatypes.htm
2. Java Tutorial for Beginners: Learn Core Java Programming
https://www.guru99.com/java-tutorial.html
3. Java Tutorial
https://www.w3schools.com/java/default.asp
4. Introduction to Java, 2019.

Answers to Pretest and Posttest

To be posted
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

Module 2: Conditionals and


Control Flow
Module Overview
Decision making structures have one or more conditions to be evaluated or
tested by the program, along with a statement or statements that are to be
executed if the condition is determined to be true, and optionally, other
statements to be executed if the condition is determined to be false.
Once a program code is compiled and executed, the control flows from start
of the code in a top-down manner. Program instructions are executed in the
order they are encountered. However, often times there is a need to deviate
from such strict top-down execution order and such deviations are
accomplished through the use of control flow statements
Motivation Question

What conditional statement is used to specify a block of Java code to


be executed if a condition is true?

Module Pretest

Identification: Write your answers before each number.

_______________ 1. Use to specify a block of code to be executed,


if the same condition is false.

____________ 2. Use to specify a block of code to be executed,


if a specified condition is true.

____________ 3. Use to specify a new condition to test, if the


first condition is false.

____________ 4. Use to specify many alternative blocks of code


to be executed
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

____________ 5. It can be used to replace multiple lines of code


with a single line. It is often used to replace simple if else
statements

____________ 6. This will stop the execution of more code and


case testing inside the block.

____________ 7. keyword specifies some code to run if there is


no case match:

____________ 8. The value of the expression is compared with


the values of each ______.

Lesson 2.1: Java Conditions and If


Statements
Lesson Summary
Decision Making in Java helps to write decision driven statements and
execute a particular set of code based on certain conditions.
The Java if statement is the most simple decision-making statement. It is
used to decide whether a certain statement or block of statements will be
executed or not i.e if a certain condition is true then a block of statement is
executed otherwise not.

Learning Outcomes

At the end of the lesson, you are expected to:


1. Discuss and differentiate the different conditions of java
2. Apply the different conditional statements

Motivation Question

What kind of conditional statement used in this code?

if (condition) {

// block of code to be executed if the condition is true }


For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

Discussion

Java If ... Else


The Java if statement is the most simple decision-making statement.
It is used to decide whether a certain statement or block of statements
will be executed or not i.e if a certain condition is true then a block of
statement is executed otherwise not.
Figure 4. If statement

https://www.w3schools.com/java/java_conditions.asp

Java supports the usual logical conditions from mathematics:

 Less than: a < b


 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
 Equal to a == b
 Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

Java has the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition is


true
 Use else to specify a block of code to be executed, if the same condition is
false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

The if Statement

Use the if statement to specify a block of Java code to be executed if a condition


is true.

Syntax

if (condition) {

// block of code to be executed if the condition is true

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an
error.

 the example below, we test two values to find out if 20 is greater than 18. If the
condition is true, print some text:

Example

if (20 > 18) {

System.out.println("20 is greater than 18");

We can also test variables:

Example (Try it Yourself!)

int x = 20;

int y = 18;

if (x > y) {
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

System.out.println("x is greater than y");

Example explained

In the example above we use two variables, x and y, to test whether x is greater


than y (using the > operator). As x is 20, and y is 18, and we know that 20 is
greater than 18, we print to the screen that "x is greater than y".

The else Statement


Use the else statement to specify a block of code to be executed if the condition
is false.
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example

int time = 20;

if (time < 18) {

System.out.println("Good day.");

} else {

System.out.println("Good evening.");

// Outputs "Good evening."

Example explained
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

In the example above, time (20) is greater than 18, so the condition is false.
Because of this, we move on to the else condition and print to the screen "Good
evening". If the time was less than 18, the program would print "Good day".

The else if Statement


Use the else if statement to specify a new condition if the first condition is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Example
int time = 22;
if (time < 10) {
System.out.println("Good morning.");
} else if (time < 20) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}

// Outputs "Good evening."

Example explained

In the example above, time (22) is greater than 10, so the first condition is false.
The next condition, in the else if statement, is also false, so we move on to
the else condition since condition1 and condition2 is both false - and print to the
screen "Good evening".

However, if the time was 14, our program would print "Good day."

Short Hand If...Else (Ternary Operator)


For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

There is also a short-hand if else, which is known as the ternary


operator because it consists of three operands. It can be used to replace multiple
lines of code with a single line. It is often used to replace simple if else
statements:
Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Instead of writing:
Example
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
You can simply write:
Example
int time = 20;
String result = (time < 18) ? "Good day." : "Good evening.";
System.out.println(result);

Learning Tasks/Activities
1.  Write a Java program to get a number from the user and print
whether it is positive or negative.

Assessment
1. To be given in our laboratory session
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

Lesson 2.2: Java Switch Statements


Learning Summary
The body of a switch is referred to as switch-block. A switch block typically
has multiple statements, each representing a unique case. Each case within the
switch block consists of - a case statement and an optional break statement.
However, there may be multiple statements that need to be executed within a
case before break is executed. 

Learning Outcomes
1. Apply the switch statement to executes all statements matching the
corresponding case

Motivation Question

What is switch case in java?

Discussion

Java Switch Statements


Use the switch statement to select one of many code blocks to be executed.

Syntax

switch(expression) {

case x:

// code block

break;

case y:

// code block

break;
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

default:

// code block

This is how it works:

 The switch expression is evaluated once.


 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 The break and default keywords are optional, and will be described
later in this chapter

The example below uses the weekday number to calculate the weekday name:

Example (Try it Yourself)

int day = 4;

switch (day) {

case 1:

System.out.println("Monday");

break;

case 2:

System.out.println("Tuesday");

break;

case 3:

System.out.println("Wednesday");

break;

case 4:

System.out.println("Thursday");

break;

case 5:

System.out.println("Friday");

break;
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

case 6:

System.out.println("Saturday");

break;

case 7:

System.out.println("Sunday");

break;

// Outputs "Thursday" (day 4)

The break Keyword


When Java reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no need
for more testing.
A break can save a lot of execution time because it "ignores" the execution of all
the rest of the code in the switch block.

What if you do not provide a break?


In case the break is not provided, it will execute the matching conditions as
well as the default condition. Your logic will go haywire if that occurs.

I will leave it to the users to experiment without using a break.

The default Keyword


The default keyword specifies some code to run if there is no case match:
Example

int day = 4;

switch (day) {

case 6:

System.out.println("Today is Saturday");

break;
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

case 7:

System.out.println("Today is Sunday");

break;

default:

System.out.println("Looking forward to the Weekend");

// Outputs "Looking forward to the Weekend"

Note that if the default statement is used as the last statement in a switch block, it


does not need a break.

Learning Task/Activities
1. Write a Java program that takes the user to provide a
single character from the alphabet. Print Vowel or
Consonant, depending on the input. If the input is not a
letter (between a and z or A and Z), or is a string of length
> 1, print an error message. 
Assessment
1. To be given in out laboratory session.

Module Posttest

Identification: Write your answers before each number.

_______________ 1. Use to specify a block of code to be executed,


if the same condition is false.

____________ 2. Use to specify a block of code to be executed,


if a specified condition is true.

____________ 3. Use to specify a new condition to test, if the


first condition is false.

____________ 4. Use to specify many alternative blocks of code


to be executed
For Instructional Purposes only ITec121 : Object Oriented Programming
1st Semester SY 2021-2022

____________ 5. It can be used to replace multiple lines of code


with a single line. It is often used to replace simple if else
statements

____________ 6. This will stop the execution of more code and


case testing inside the block.

____________ 7. keyword specifies some code to run if there is


no case match:

____________ 8. The value of the expression is compared with


the values of each ______.

References and Additional Resources

1. Practical Application for Java: Using Switch Statements


https://study.com/academy/lesson/practical-application-for-java-
using-switch-statements.html
2. Java if statement with Examples
https://www.geeksforgeeks.org/java-if-statement-with-examples/
3. Java Decision Making
https://www.tutorialspoint.com/java/java_decision_making.htm
4. Java Switch
https://www.w3schools.com/java/java_switch.asp

Answers to the Pretest and Posttest


To be posted in our E-learning site

You might also like