java中if是掌握分支构造的,意义是假如前提建立的话,实行某段代码。
if语句
一个if语句包括一个布尔表达式和一条或多条语句。
语法
If语句的用语法以下:
if(布尔表达式) { //假如布尔表达式为true将实行的语句 }
假如布尔表达式的值为true,则实行if语句中的代码块。不然实行If语句块背面的代码。
public class Test { public static void main(String args[]){ int x = 10; if( x < 20 ){ System.out.print("这是 if 语句"); } } }
以上代码编译运转效果以下:
这是 if 语句
if...else语句
if语句背面能够跟else语句,当if语句的布尔表达式值为false时,else语句块会被实行。
语法
if…else的用法以下:
if(布尔表达式){ //假如布尔表达式的值为true }else{ //假如布尔表达式的值为false }
实例
public class Test { public static void main(String args[]){ int x = 30; if( x < 20 ){ System.out.print("这是 if 语句"); }else{ System.out.print("这是 else 语句"); } } }
以上代码编译运转效果以下:
这是 else 语句
if...else if...else语句
if语句背面能够跟elseif…else语句,这类语句能够检测到多种能够的状况。
运用if,else if,else语句的时刻,须要注重下面几点:
(1)if语句最多有1个else语句,else语句在所有的elseif语句以后。
(2)If语句能够有若干个elseif语句,它们必须在else语句之前。
(3)一旦个中一个else if语句检测为true,其他的else if以及else语句都将跳过实行。
语法
if...else语法花样以下:
if(布尔表达式 1){ //假如布尔表达式 1的值为true实行代码 }else if(布尔表达式 2){ //假如布尔表达式 2的值为true实行代码 }else if(布尔表达式 3){ //假如布尔表达式 3的值为true实行代码 }else { //假如以上布尔表达式都不为true实行代码 }
实例
public class Test { public static void main(String args[]){ int x = 30; if( x == 10 ){ System.out.print("Value of X is 10"); }else if( x == 20 ){ System.out.print("Value of X is 20"); }else if( x == 30 ){ System.out.print("Value of X is 30"); }else{ System.out.print("This is else statement"); } } }
以上代码编译运转效果以下:
Value of X is 30
ki4网,大批的免费Java入门教程,迎接在线进修!
以上就是if在java中是什么意义的细致内容,更多请关注ki4网别的相干文章!