Conditional branching is a logical part of the program. Based on the specific condition we can tell to program which way the program should go.
if <it's cold outside> then I will get my jacket
else I'm good with T-shirt
The above example shows a simple version of conditional branching in plain language. <it's cold outside>
this is a logical condition and it can be true or false. If it’s true then we will perform some action and if it’s false we can perform another action.
The logical condition can be stored in boolean
type variable and can be used as part of the conditional branching statements(if-esle, ternary operator).
// class and main method is not displayed
boolean b = true;
if (b) {
System.out.println("Java is great!");
}else {
System.out.println("Python is great!");
}
in above the snippet we can see the simple if-else statement.
- The output of this program is
Java is great!
- The if statement always takes boolean datatype as its condition, between the parenthesis. If the condition is true, if’s body will be executed and if it is false else’s body will be executed.
- This code will always print
Java is great!
because we hardcoded the value of our boolean as true. Usually, we get boolean from some conditions (comparison, event, etc.).
Comparison Operators
Let’s talk about how we can get a logical boolean. One way to get it is by using comparison operators.
==
equal to operator. We can use this operator to compare primitive data types on equality. For objects, it will compare if two references are pointing to the same object or not(we will talk more in the future).!=
not equal to operator. Exactly the same as equal, but works in reverse.>
greater than operator. To compare if one number is greater than another.>=
greater than or equal to operator. To compare if one number is greater or equal to another number.<
less than<=
less than or equal to
Using ==
to compare numbers on equality.
The output from the above program is Samsung
. The not equal operator is the exact opposite of equal to operator. If numbers are not equal it will return true and if they are equal it will return false.
The greater than and less than operators are very straightforward. if you want to also check greater/less or equal you need to add =
after the operator. Like >=
and <=
Logical Operators
Write a method that will accept one number argument. If number within a range 10–20 inclusive print
Java
otherwise, printPython
.
Even though, above code works well for our requirements, it’s not the best way of achieving it. For this simple condition, we used two if-else statements. Now let’s see code using a logical operator.
Here we used the logical AND(&&) operator. The logical operators are super useful to connect boolean conditions into one. They help us to make our conditions clean and short. When using AND operator all conditions should be true then only the whole condition will be true.
&&
logical AND operator||
logical OR operator!
logical NOT operator
Write a mathod that will accept one number as an argument.
Assume numbers 7, 13, 99 are lucky numbers. If the number is lucky, printJackpot!
otherwise, printNot today!
.
With the OR operator if at least one part is true then the whole condition is true.
Logical NOT operator will reverse value of boolean.
boolean b = true;
boolean c = !b;
boolean d = !false;
System.out.println(b); // true
System.out.println(c); // false
System.out.println(d); // trueint money = 99;
if (!(money >= 100)) {
System.out.println("It's not enough");
}
We can use logical NOT just in front of the boolean condition and it will reverse its value. Notice how we use parentheses. Parentheses clarify the meaning of a boolean expression. Also, they are useful when many conditions are used together to clarify and separate.
Multibranch if-else
Write a method that will accept one double number and will print a message based on this number:
- if the number within a range of 13.5–15.5 inclusive, printnormal pressure
- if the number is less than 13.5 exclusives, printlow pressure
- otherwise, printhigh pressure
public void printPressureMsg(double pressure) {
if (pressure >= 13.5 && pressure <= 15.5) {
System.out.println("normal pressure");
}else if (pressure < 13.5) {
System.out.println("low pressure");
}else {
System.out.println("high pressure");
}
}
As you can see here we can connect if statements into one statement. Only one of them will be executed and if all do not match else statement will be executed. Else part is optional. It’s always better to have multibranch if-else than having multiple if statements separately.
write a method that accepts one number and will print a message based on
- if the number is even printFizz
- if the number is odd printBuzz
- if the number is odd and divisible by 5 evenly printFizzBuzz
public void fizzBuzz(int num) {
if (num % 2 == 0) {
System.out.println("Fizz");
} else if (num % 2 == 1) {
System.out.println("Buzz");
} else if (num % 2 == 1 && num % 5 == 0) {
System.out.println("FizzBuzz");
}
}
It seems like a correct method but there is a defect in the code. For most of the numbers it will work fine but for example, for 15
it will print Buzz
but it should print FizzBuzz
.
Order of the if/else if is very important. We discussed that only one statement will be executed even though a few of them can be true. So in our case num % 2 == 1
is true and num % 2 == 1 && num % 5 == 0
is also true. And correct one is the second one but the first one is first by order so it will always catch this condition and get executed.
public void fizzBuzz(int num) {
if (num % 2 == 0) {
System.out.println("Fizz");
} else if (num % 2 == 1 && num % 5 == 0) {
System.out.println("FizzBuzz");
} else if (num % 2 == 1) {
System.out.println("Buzz");
}
}
This is the correct version.
Please take my Java Course for video lectures.This article is part of the series of articles to learn Java programming language from Tech Lead Academy:Introduction to programming
OS, File, and File System
Working with terminal
Welcome to Java Programming Language
Variables and Primitives in Java
Convert String to numeric data type
Input from the terminal in Java
Methods with Java
Java Math Operators and special operators
Conditional branching in Java
Switch statement in Java
Ternary operator in Java
Enum in Java
String class and its methods in Java
Loops in Java
Access modifiers in Java
Static keyword in Java
The final keyword in Java
Class and Object in Java
Object-Oriented Programming in Java
OOP: Encapsulation in Java
OOP: Inheritance in Java
OOP: Abstraction in Java
OOP: Polymorphism in Java
The method Overriding vs Overloading in Java
Array in Java
Data Structures with Java
Collection framework in Java
ArrayList in Java
Set in Java
Map in Java
Date and Time in Java
Exception in Java
How to work with files in Java
Design Patterns
Generics in Java
Multithreading in java
Annotations in Java
Reflection in Java
Reflection & Annotations - The Powerful Combination
Run terminal commands from Java
Lambda in Java
Unit Testing in Java
Big O Notation for coding interviews
Top Java coding interview questions for SDET