Java Reference
In-Depth Information
if Statements and boolean Expressions
The expression in parentheses of an if statement must evaluate to a boolean
expression. The following code does not compile:
int y = 12;
if(y) {
//This does not work
}
The following compiler error occurs:
If Then.java:11: incompatible types
found : int
required: boolean
if(y) {
In other languages like C and C++ that do not have primitive Boolean types, any
non-zero value is considered true and any zero value is false. This concept does not
translate in Java. All the control structures that we discuss in this chapter require
boolean expressions that evaluate to either true or false .
An if-then-else statement can contain any number of else if blocks. For example,
study the following code and see if you can determine its output:
1. public class Grades {
2. public static void showGrade(int grade) {
3. if(grade >= 90) {
4. System.out.print(“A”);
5. } else if(grade >= 80) {
6. System.out.print(“B”);
7. } else if(grade >= 70) {
8. System.out.print(“C”);
9. } else if(grade >= 60) {
10. System.out.print(“D”);
11. } else {
12. System.out.print(“F”);
13. }
14. System.out.println(“ is your grade”);
15. }
16.
Search WWH ::




Custom Search