CS 211
OBJECT-ORIENTED
Programming
LEARNING MODULE
Prepared by:
Ms. FATIMA MARIE P. AGDON
Mr. JANCYRILL L. MENDOZA
JavaM OConditionals
DULE TWO
In this module, students will be able to learn control flow statements using Java if and
if...else statements, including compound conditions and logical operators.
If Statements
Let us go back to the kilometer-meter program in the previous module. What if the user
entered a value less than 1? This clearly shows a complete disregard to the instruc-
tions set. Well, that doesn’t seem right.
Perhaps, there might be a way to skip the conversion process when the input hap-
pens to be less than 1, since the instructions specify a positive integer.
The statement above is called a conditional statement. The “if conditional state-
ment” was implemented in the example. It was aptly named because it needs a con-
ditional statement to work with the aid of the relational operators.
These relational operators return a Boolean value (either true or false), entirely
depending on the truthfulness of the conditional statement. The following are
the different relational operators in Java:
Symbol Name Symbol Name
> Greater than <= Less than or equal
< Less than >= Greater than or equal
== Equal != Not equal
Looking back at our code, it still has issues. When the user enters a value less than 1,
the program still prints the equivalence statement in Line 10. What we want to do is
to skip that as well, since there was no conversion at all.
Look at the codes now below:
What happened was, the statement was enclosed in a pair of curly braces. That
means, if the user inputs a value for km that is less than 1, then it will not convert the
value to meters. Hence, line 8 will not be executed.
Here’s a tip. When multiple statements are to be executed given a conditional
statement evaluating to true (circumstance), enclose them in a pair of curly
braces. We can even include the declaration of the variable m in the if statement as
we only need m inside that scope (meaning, we only use the variable m inside the if
statement).
If-Else Statements
When we want to execute some statements when the conditions in the if evaluate to
a false statement, we use the if-else statement, exactly like the one below:
You can even nest them. Like an if-statement within an if statement.
What if you want to check whether the character you entered is a digit? How are you
going to do it? Are you going to create a set of else-ifs, and check every condition
from zero to nine, like the code below:
Oof! We know that there are 10 digits and they go from '0' to '9'. For every condition
we have, it gives us the same thing (at least for the 10 of them). By looking on how
our code looks like makes me want to cringe. Is there a way to improve the solution?
Also, you may notice that there is no nextChar() method for the Scanner. Instead,
the next() method was used, which takes in a word - a string with no spaces in
it. next() will return a string. Using the method charAt(0) gives us the character at in-
dex 0, the first character of the word, specifically, the character we need since the us-
er is expected to enter just a character.
Let’s switch things up. What if we ask the user to enter a character and check if it is a
letter from the English alphabet? We have 26 letters to deal with—and two sets of
these because there are uppercase and lowercase letters, making it 32 things to deal
with.
Going back to Lesson 1, we find that characters are 16 bits long and that is why we
can assign numbers to them. The American Standard Code for Information Inter-
change, also known as ASCII codes was the first character set (encoding standard)
used between computers on the Internet. (Additional reading: ASCII https://
www.w3schools.com/CHARSETS/ref_html_ascii.asp)
The ASCII Codes for the digits go from 48 to 57. The uppercase letters go from 65
to 90 and the lowercase letters from 97 to 122. You can then use this information.
Now, take a look at this code:
As you may have noticed, the conditions are nested all the way to three levels, when
they just simply check a range of 65 to 90 and 97 to 122. You might be thinking of an
easier way to write this code. Well, this is where it brings us to our next topic in this
module.
Compound Conditions and Logical Operators
To combine multiple conditions depending on your desired results, logical operators
are the ones that make it possible. In Java, there are three logical operators such as
NOT(!), AND (&&), and OR (||). These operators take in Boolean values as opera-
tors.
The NOT Operator
The NOT operator, symbolized by ! is a unary logical operator and simply negates its
value as shown below:
Inputs Application of NOT
TRUE FALSE
FALSE TRUE
The OR Operator
The OR operator, symbolized by || is a binary logical operator that returns true if at
least one of the operands is true, otherwise it will return false.
Inputs Application of OR
TRUE TRUE FALSE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE
The AND Operator
The AND operator, symbolized by && is a binary logical operator that returns true
if all of the operands is true, otherwise it will return false.
Inputs Application of AND
TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE FALSE
Now that you are aware with the logical operators, let us apply them in our previous
examples (digit and uppercase and lowercase letters), to make it look better.
First, let us have the digits:
Well, that’s a lot of OR operators. It will give you the expected output, but you can al-
so try this solution, which I think is much better:
We applied the ASCII Code of the digits, 48 to 57. 0 is equivalent to 48, and 9 is equiv-
alent to 57.
Now, let’s try it on the uppercase and lowercase letters:
If you are not familiar with the ASCII Codes, you may use the characters themselves.
Because they are 16-bit values, which means that they are numbers. Check the solu-
tion below for the digits example:
For the uppercase-lowercase letters example:
And if you were simply checking whether ch is a letter, check this one below:
The solution above, as you notice mixes the logical operators. Here, we can see that
&& has higher precedence than ||. Parentheses can be used to group conditions
just like this one: if((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
The meaning of the previous version was not changed, but the usage of parentheses
should be implemented if you wish to group compound conditions, and let the OR
operators be executed first, like this one: if((ch == 'A' || ch == 'a') && (digit == '4' ||
digit <= '8')). The ||s will be checked first and the resulting Boolean values will
be ANDed.
The switch Statement
The switch statement is used in selecting one of many code blocks to be executed.
It works by evaluating the switch expression once. Then, the value of the expression
is compared with the values of each case. If it matches the case, the associated
block of code will be executed. The break and default keywords are optional. In
the example code below, it uses the weekday number to get the weekday name.
The example will give an output of “Thursday” because the variable day has an initial-
ized value of 4, thus, when the flow reaches case 4, the associated block of code will
be executed.
The break Statement
If a break keyword is reached, it breaks out of the switch block. This stops the execu-
tion of more code, and case testing in the block. If a match is found, the break cuts it,
and stops checking the next cases. It can save a lot of execution time because it
"ignores" the execution of all the rest of the code in the switch block.
The default Keyword
If there is no case match, the codes to be run are specified in the default block. A
break is no longer needed in this statement, because it is the last statement in the
switch block.
Review Questions
Answer the following questions:
1. Differentiate relational and logical operators.
2. Why is it important to enclose the statements in curly braces?
3. Why can we use the character itself if we are not familiar with ASCII Codes?
4. Differentiate the logical operators in Java.
5. Suppose the value of ch is ‘B’, and the value of digit is 7. What will be the re-
sult, given the condition: if((ch == 'A' || ch == 'a') && (digit == '4' || digit <=
'8'))?
6. Differentiate switch and if statements.
References
CodeChum. https://codechum.com
Programiz. https://programiz.com
W3Schools. https://www.w3schools.com/java/java_intro.asp
Object-Oriented Programming in Java – A Beginner's Guide. https://www.freecodecamp.org/
news/object-oriented-programming-concepts-java/