Conditional Branching in Java

if <it's cold outside> then I will get my jacket
else I'm good with T-shirt
// 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!");
}
  • 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

  • == 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
in Main.java
in Main.java file
in Main.java

Logical Operators

in Main.java
in Main.java
  • && logical AND operator
  • || logical OR operator
  • ! logical NOT operator
boolean b = true;
boolean c = !b;
boolean d = !false;
System.out.println(b); // true
System.out.println(c); // false
System.out.println(d); // true
int money = 99;
if (!(money >= 100)) {
System.out.println("It's not enough");
}

Multibranch if-else

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");
}
}
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");
}
}
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");
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store