Java基础篇:if控制语句

138 阅读1分钟

Java中if控制语句与其他语言中的IF语句非常相似。并且,它与C/ C++语言中的if语句的语法完全相同。它的最简单形式如下:

if(condition) statement;

这里,条件condition是一个布尔型表达式。如果条件为真,那么执行语句statement;如果条件为假,则语句statement将被绕过而不被执行。下面是一个例子:

if(num < 100) println("num is less than 100");

在这个例子中,如果变量num的值小于100,那么条件表达式的值为真,方法 println ( )将被调用执行。如果变量num的值大于或等于100,那么方法println ( )被绕过而不被执行 。

注意,判断是否相等的关系运算符是两个等号“==”。下面的程序说明了if控制语句的用法:

/*

   Demonstrate the if.

   Call this file "IfSample.java".

   */

class IfSample {

   public static void main(String args[]) {

      int x,y;

      x = 10;

      y = 20;

      if(x < y) System.out.println("x is less than y");

      x = x * 2;

      if(x == y) System.out.println("x now equal to y");

      x = x * 2;

      if(x > y) System.out.println("x now greater than y");

      // this won't display anything

      if(x == y) System.out.println("you won't see this");
      }
      }

该程序产生的结果如下所示:

 x is less than y

x now equal to y

x now greater than y

这个程序中另一个需要注意的地方是:

int x ,y ;

该程序行使用逗号来分隔变量列表,定义了2个变量x和y。