The if-then
is the most basic control flow statement. It will execute the block of statement only if the test expression evaluated equals to true
. Let’s see the example below:
package org.kodejava.basic;
public class IfThenDemo {
public static void main(String[] args) {
int a = 10;
int b = 5;
// If the evaluation of a > b is true, the if block will be
// executed. In the block below we just print that the value
// of "a" is bigger than "b".
if (a > b) {
System.out.printf("A(%d) is bigger than B(%d)%n", a, b);
}
// When we have only a single command inside a block we can
// remove the opening and closing braces for the block ({..}).
// But it is a good practice to always enclose the block with
// braces, so that we know the block of code to be executed.
if (b < a)
System.out.printf("B(%d) is smaller that A(%d)%n", b, a);
}
}
The result of the above program is:
A(10) is bigger than B(5)
B(5) is smaller that A(10)
Latest posts by Wayan (see all)
- How do I add an object to the beginning of Stream? - February 7, 2025
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024