Title here
Summary here
Our first program will demonstrate conditional statements using if/else. Here’s the full source code:
public class IfElseExample {
public static void main(String[] args) {
// Here's a basic example.
if (7 % 2 == 0) {
System.out.println("7 is even");
} else {
System.out.println("7 is odd");
}
// You can have an if statement without an else.
if (8 % 4 == 0) {
System.out.println("8 is divisible by 4");
}
// Logical operators like && and || are often useful in conditions.
if (8 % 2 == 0 || 7 % 2 == 0) {
System.out.println("either 8 or 7 are even");
}
// A statement can precede conditionals; any variables
// declared in this statement are available in the current
// and all subsequent branches.
int num = 9;
if (num < 0) {
System.out.println(num + " is negative");
} else if (num < 10) {
System.out.println(num + " has 1 digit");
} else {
System.out.println(num + " has multiple digits");
}
}
}
To run the program, compile it and then use java
to execute:
$ javac IfElseExample.java
$ java IfElseExample
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit
Note that in Java, you need parentheses around conditions, and the braces are required for multi-line blocks but optional for single-line blocks.
Java does have a ternary operator (?:
) which can be used for simple conditional expressions, unlike some other languages. For example:
String result = (x > y) ? "x is greater" : "y is greater or equal";
This can be useful for simple conditions, but for more complex logic, full if
/else
statements are preferred for readability.