使用Java的条件语句if,可以有选择的执行程序的某一部分.Java的if语句与其他语言中的if语句非常相似.if语句最简单的形式如下:
- if(condition) statement;
此处,condition是一个boolean表达式.如果condition为真,则执行语句.如果condition为假,则跳过语句,下面是一个示例:
- if(10 < 11) System.out.println("10 is less than 11");
因为条件表达式为真,执行println显示”10 is less than 11″
- if(10 < 9) System.out.println("10 is less than 9");
因为条件表达式为假,所以不会显示文字
Java定义了可以在条件表达式使用的完整的关系运算符,如下表所示:
运算符
|
含义
|
<
|
小于
|
<=
|
小于等于
|
>
|
大于
|
>=
|
大于等于
|
==
|
等于
|
!=
|
不等于
|
例:
- public class test
- {
- // @param args
- public static void main(String args[])
- {
- int a,b,c;
- a = 2;
- b = 3;
- if(a < b) System.out.println("a is less than b");
- c = a - b;
- if(c >= 0)
- {
- System.out.println("c is non-negative");
- } else {
- System.out.println("c is negative");
- }
- }
- }
输出:
- a is less than b
- c is negative