If Else
Here’s the translation of the Go code example and explanation into Java, formatted in Markdown suitable for Hugo:
public class IfElse {
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");
}
}
}
Branching with if
and else
in Java is straightforward.
Here’s a basic example demonstrating the use of if
and else
statements in Java. The syntax is similar to many other programming languages.
You can have an if
statement without an else
. This is useful when you only need to execute code under a specific condition.
Logical operators like &&
(AND) and ||
(OR) are often useful in conditions. They allow you to combine multiple conditions in a single if
statement.
In Java, you can declare variables before the if
statement and use them within the conditional blocks. However, unlike Go, Java doesn’t support declaring variables directly in the if
statement condition.
To run this Java program:
$ javac IfElse.java
$ java IfElse
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 (though it’s generally recommended to always use braces for clarity).
Java does have a ternary operator (?:
), which can be used for simple conditional expressions. For example: int result = (a > b) ? a : b;
. This can be useful for assigning values based on a condition, but for more complex logic, full if-else
statements are preferred.