Java-lang-boolean-compareto

提供:Dev Guides
移動先:案内検索

Java.lang.Boolean.compareTo()メソッド

説明

  • java.lang.Boolean.compareTo(Boolean b)*は、このブールインスタンスを別のインスタンスと比較します。

宣言

以下は* java.lang.Boolean.compareTo()*メソッドの宣言です

public int compareTo(Boolean b)

指定者

インターフェイスのcompareTo Comparable <Boolean>

パラメーター

*b* -比較されるブールインスタンス

戻り値

このメソッドは、

  • zero -このオブジェクトが引数と同じブール値を表す場合
  • 正の値-このオブジェクトがtrueを表し、引数がfalseを表す場合
  • 負の値-このオブジェクトが偽を表し、引数が真を表す場合。

例外

*NullPointerException* -引数がnullの場合

次の例は、lang.Boolean.compareTo()メソッドの使用方法を示しています。

package com.finddevguides;

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