java语言中if语句的用法

 if-else语句或许是控制程序流程最基本的形式。其中的else是可选的,所以可按下述两种形式来使用if:

if(布尔表达式)
语句

或者

if(布尔表达式)
语句
else
语句

条件必须产生一个布尔结果。“语句”要么是用分号结尾的一个简单语句,要么是一个复合语句——封闭在括号内的一组简单语句。在本书任何地方,只要提及“语句”这个词,就有可能包括简单或复合语句。
作为if-else的一个例子,下面这个test()方法可告诉我们猜测的一个数字位于目标数字之上、之下还是相等:
static int test(int testval) {
 int result = 0;
 if(testval > target)
    result = -1;
 else if(testval < target)
    result = +1;
 else
    result = 0; // match
 return result;
}

最好将流程控制语句缩进排列,使读者能方便地看出起点与终点。

1. return
return关键字有两方面的用途:指定一个方法返回什么值(假设它没有void返回值),并立即返回那个值。可据此改写上面的test()方法,使其利用这些特点:
static int test2(int testval) {
 if(testval > target)
    return -1;
 if(testval < target)
    return +1;
 return 0; // match
}
不必加上else,因为方法在遇到return后便不再继续。
也就是当满足第一个条件的时候,就return -1,if判断语句结束,下边都不在执行,自己的例子如下:

public class TestNull {
  public static void main(String[] args) {
  String strPro = null;
  String strName = null;
  if( strPro == null || strName == null ){
    return ;
  }
  if( !strPro.equals(strName) ){
    System.out.println("success");
  }
  String strPro1 = "";
  String strName1 = "1";
  if( strPro1 != null && strName1 != null && (!strPro1.equals(strName1)) ){
    System.out.println("success");
  }
  System.exit(0);
  }
}

两种结果一样,但是有一点就是如果这两个其中有一个为null的时候,就不会在执行下边的!strPro.equals(strName) 这个

如果文章对你有所帮助,希望施舍点包子钱,在下支付宝账号:

非常感谢

13718045310
 

原文地址:https://www.cnblogs.com/love-you-girl/p/3900367.html