java.lang.Boolean.compareTo()方法範例


java.lang.Boolean.compareTo(Boolean b) 此Boolean範例與另一個進行比較。

宣告

以下是java.lang.Boolean.compareTo()方法的宣告

public int compareTo(Boolean b)

指定以下介面

compareTo介面 Comparable<Boolean>

引數

  • b - 布林範例進行比較

返回值

方法返回

  • 0 - 如果該物件表示相同的布林值作為引數

  • 一個正數值 - 如果該物件表示true,引數表示false

  • 一個負數值 - 如果該物件表示false,引數表示true。

異常

  • NullPointerException - 如果該引數為null

例子

下面的例子顯示lang.Boolean.compareTo()方法的使用。

package com.yiibai;

import java.lang.*;

public class BooleanDemo {

   public static void main(String[] args) {

      // create 2 Boolean objects b1, b2
      Boolean b1, b2;

      // assign values to b1, b2
      b1 = new Boolean(true);
      b2 = new Boolean(false);

      // create an int res
      int res;

      // compare b1 with b2
      res = b1.compareTo(b2);

      String str1 = "Both values are equal ";
      String str2 = "Object value is true";
      String str3 = "Argument value is true";

      if( res == 0 ){
      	 System.out.println( str1 );
      }
      else if( res > 0 ){
      	 System.out.println( str2 );
      }
      else if( res < 0 ){
      	 System.out.println( str3 );
      }
   }
}

讓我們來編譯和執行上面的程式,這將產生以下結果:

Object value is true