1. What is the purpose of an 'if' statement in Java?
Answer:
Explanation:
An 'if' statement in Java is used to specify a block of code that should be executed if a specified condition is true.
2. How does Java compare two values for equality in an 'if' statement?
Answer:
Explanation:
In Java, '==' is used to compare two values for equality within an 'if' statement.
3. What will be the output of the following code?
int x = 10;
if (x > 5) {
System.out.println("Greater than 5");
}
Answer:
Explanation:
Since x is 10, which is greater than 5, the code inside the 'if' statement will execute, printing "Greater than 5".
4. Which statement is used with 'if' to execute a block of code when the 'if' condition is false?
Answer:
Explanation:
The 'else' statement is used alongside 'if' to specify a block of code that should be executed if the 'if' condition is false.
5. In an 'if' statement, what is the correct way to check if a variable 'a' is not equal to 10?
Answer:
Explanation:
The '!=' operator is used to check for inequality in an 'if' statement.
6. How do you specify multiple conditions in an 'if' statement?
Answer:
Explanation:
Multiple conditions in an 'if' statement can be specified using logical operators like '&&' (and) and '||' (or).
7. Which statement is used to specify a new condition to test if the 'if' condition is false?
Answer:
Explanation:
The 'else if' statement is used to specify a new condition to be tested if the initial 'if' condition is false.
8. What is the correct syntax for an 'if' statement in Java?
Answer:
Explanation:
The correct syntax for an 'if' statement in Java includes the condition within parentheses followed by a block of code enclosed in curly braces.
9. What does the following code output?
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
Answer:
Explanation:
Since the value of 'time' (20) is not less than 18, the 'else' block will execute, outputting "Good evening.".
10. If 'a' is 5, what will be the output of the following code?
if (a == 10) {
System.out.println("Ten");
} else if (a < 10) {
System.out.println("Less than Ten");
} else {
System.out.println("More than Ten");
}
Answer:
Explanation:
Since 'a' is 5, which is less than 10, the 'else if' block will execute, printing "Less than Ten".
11. Which operator checks if two values are not equal in an 'if' statement?
Answer:
Explanation:
In an 'if' statement, the '!=' operator is used to check if two values are not equal.
12. How is the 'else if' statement used in Java?
Answer:
Explanation:
The 'else if' statement is used to specify a new condition that will be tested if the initial 'if' condition evaluates to false.