Unlock the Power of Java: Mastering Conditional Statements
Understanding the Basics
To grasp the concepts in this article, you should be familiar with Java programming topics such as the if…else statement and the Scanner class.
Checking for Even or Odd Numbers
Imagine you want to create a program that determines whether a number is even or odd. How would you do it? One way is by using the if…else statement in Java.
Example 1: If…Else Statement
Let’s create a program that checks whether a number is even or odd using the if…else statement. Here’s the code:
“`java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print(“Enter a number: “);
int num = reader.nextInt();
if (num % 2 == 0) {
System.out.println(num + ” is even.”);
} else {
System.out.println(num + ” is odd.”);
}
}
}
“`
In this program, we create a Scanner
object to read a number from the user’s keyboard. We then store the entered number in a variable num
. To check whether num
is even or odd, we calculate its remainder using the %
operator and check if it’s divisible by 2 or not. If num
is divisible by 2, we print “num is even.” Otherwise, we print “num is odd.”
A More Concise Approach
But what if we want to make our code more concise? That’s where the ternary operator comes in.
Example 2: Ternary Operator
Here’s the same program, but this time using the ternary operator:
“`java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print(“Enter a number: “);
int num = reader.nextInt();
String evenOdd = (num % 2 == 0)? “even” : “odd”;
System.out.println(num + ” is ” + evenOdd + “.”);
}
}
“`
In this program, we’ve replaced the if…else statement with the ternary operator (? :
). If num
is divisible by 2, “even” is returned. Otherwise, “odd” is returned. The returned value is saved in a string variable evenOdd
. Then, the result is printed on the screen using string concatenation.
Further Exploration
Want to learn more about conditional statements in Java? Check out these related articles:
- Java Program to Check Whether a Number is Positive or Negative
- Java Program to Check Whether a Number is Prime or Not