Java Tutorial/Data Type/Boolean

Материал из Java эксперт
Перейти к: навигация, поиск

Autoboxing/unboxing a Boolean and Character.

   <source lang="java">

class AutoBox5 {

 public static void main(String args[]) {
   Boolean b = true;
   if (b)
     System.out.println("b is true");
   Character ch = "x"; // box a char
   char ch2 = ch; // unbox a char
   System.out.println("ch2 is " + ch2);
 }

}</source>





Boolean Data Type

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   boolean t = true;
   System.out.println("t is " + t);
   int x = 10;
   boolean y = (x > 15);
   System.out.println("y is " + y);
 }

}</source>





Boolean Literals

The boolean type has two values, represented by literals "true" and "false".

The following code declares a boolean variable includeSign and assigns it the value of true.



   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
   boolean includeSign = true;
   System.out.println(includeSign);
 }

}</source>





Boolean Variables

  1. Variables of type boolean can have only one of two values, true or false.
  2. The values "true" and "false" are boolean literals.



   <source lang="java">

public class MainClass{

 public static void main(String[] arg){
   boolean state = true;
   state = false;
   System.out.println(state);
 }

}</source>



false


Compare Two Java boolean Arrays Example

   <source lang="java">

import java.util.Arrays; public class Main {

 public static void main(String[] args) {
   boolean[] a1 = new boolean[] { true, false, true };
   boolean[] a2 = new boolean[] { true, false, true };
   System.out.println(Arrays.equals(a1, a2));
 }

}</source>





Convert boolean to integer

   <source lang="java">

public class Main {

 public static void main(String[] args) throws Exception {
   boolean b = true;
   int i = (b) ? 1 : 0;
 }

}</source>





Convert Boolean to String

   <source lang="java">

public class Main {


   public static void main(String[] args) {
       boolean theValue = true;
       
       //boolean to String conversion
       String theValueAsString = new Boolean(theValue).toString();
       
       System.out.println(theValueAsString);
   }

} //true</source>





Convert boolean value to Boolean

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   boolean b = true;
   Boolean bool = Boolean.valueOf(b);
   System.out.println("bool = " + bool);
   if (bool.equals(Boolean.TRUE)) {
     System.out.println("bool = " + bool);
   }
   String s = "false";
   Boolean bools = Boolean.valueOf(s);
   System.out.println("bools = " + bools);
   String f = "abc";
   Boolean abc = Boolean.valueOf(f);
   System.out.println("abc = " + abc);
 }

}</source>





Convert integer to boolean

   <source lang="java">

public class Main {

 public static void main(String[] args) throws Exception {
   int i=10;
   boolean b = (i != 0);
   System.out.println(b);
 }

} //true</source>





Convert Java boolean Primitive to Boolean object

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   boolean b = true;
   // using constructor
   Boolean blnObj1 = new Boolean(b);
   // using valueOf method of Boolean class. 
   Boolean blnObj2 = Boolean.valueOf(b);
 }

}</source>





Convert Java String Object to Boolean Object

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   String str = "false";
   // Convert using constructor
   Boolean blnObj1 = new Boolean(str);
   System.out.println(blnObj1);
   // Use valueOf method of Boolean class. This is a static method.
   Boolean blnObj2 = Boolean.valueOf(str);
   System.out.println(blnObj2);
 }

}</source>





Converts a boolean to a String returning "yes" or "no"

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**

* Operations on boolean primitives and Boolean objects.
*
* This class tries to handle null input gracefully.
* An exception will not be thrown for a null input.
* Each method documents its behaviour in more detail.
* 
* @author Stephen Colebourne
* @author Matthew Hawthorne
* @author Gary Gregory
* @since 2.0
* @version $Id: BooleanUtils.java 589050 2007-10-27 05:07:45Z bayard $
*/

public class Main {

 /**
  * Converts a boolean to a String returning "yes"
  * or "no".
  * 
*
   *   BooleanUtils.toStringYesNo(true)   = "yes"
   *   BooleanUtils.toStringYesNo(false)  = "no"
   * 
  *
  * @param bool  the Boolean to check
  * @return "yes", "no",
  *  or null
  */
 public static String toStringYesNo(boolean bool) {
     return toString(bool, "yes", "no");
 }
 
 /**
  * Converts a boolean to a String returning one of the input Strings.
  * 
*
   *   BooleanUtils.toString(true, "true", "false")   = "true"
   *   BooleanUtils.toString(false, "true", "false")  = "false"
   * 
  *
  * @param bool  the Boolean to check
  * @param trueString  the String to return if true,
  *  may be null
  * @param falseString  the String to return if false,
  *  may be null
  * @return one of the two input Strings
  */
 public static String toString(boolean bool, String trueString, String falseString) {
     return bool ? trueString : falseString;
 }

}</source>





Converts an Integer to a boolean specifying the conversion values.

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**

* Operations on boolean primitives and Boolean objects.
*
* This class tries to handle null input gracefully.
* An exception will not be thrown for a null input.
* Each method documents its behaviour in more detail.
* 
* @author Stephen Colebourne
* @author Matthew Hawthorne
* @author Gary Gregory
* @since 2.0
* @version $Id: BooleanUtils.java 589050 2007-10-27 05:07:45Z bayard $
*/

public class Main {

 /**
  * Converts an Integer to a boolean specifying the conversion values.
  * 
*
   *   BooleanUtils.toBoolean(new Integer(0), new Integer(1), new Integer(0)) = false
   *   BooleanUtils.toBoolean(new Integer(1), new Integer(1), new Integer(0)) = true
   *   BooleanUtils.toBoolean(new Integer(2), new Integer(1), new Integer(2)) = false
   *   BooleanUtils.toBoolean(new Integer(2), new Integer(2), new Integer(0)) = true
   *   BooleanUtils.toBoolean(null, null, new Integer(0))                     = true
   * 
  *
  * @param value  the Integer to convert
  * @param trueValue  the value to match for true,
  *  may be null
  * @param falseValue  the value to match for false,
  *  may be null
  * @return true or false
  * @throws IllegalArgumentException if no match
  */
 public static boolean toBoolean(Integer value, Integer trueValue, Integer falseValue) {
     if (value == null) {
         if (trueValue == null) {
             return true;
         } else if (falseValue == null) {
             return false;
         }
     } else if (value.equals(trueValue)) {
         return true;
     } else if (value.equals(falseValue)) {
         return false;
     }
     // no match
     throw new IllegalArgumentException("The Integer did not match either specified value");
 }

}</source>





Converts an int to a boolean specifying the conversion values.

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**

* Operations on boolean primitives and Boolean objects.
*
* This class tries to handle null input gracefully.
* An exception will not be thrown for a null input.
* Each method documents its behaviour in more detail.
* 
* @author Stephen Colebourne
* @author Matthew Hawthorne
* @author Gary Gregory
* @since 2.0
* @version $Id: BooleanUtils.java 589050 2007-10-27 05:07:45Z bayard $
*/

public class Main {

 /**
  * Converts an int to a boolean specifying the conversion values.
  * 
*
   *   BooleanUtils.toBoolean(0, 1, 0) = false
   *   BooleanUtils.toBoolean(1, 1, 0) = true
   *   BooleanUtils.toBoolean(2, 1, 2) = false
   *   BooleanUtils.toBoolean(2, 2, 0) = true
   * 
  *
  * @param value  the Integer to convert
  * @param trueValue  the value to match for true
  * @param falseValue  the value to match for false
  * @return true or false
  * @throws IllegalArgumentException if no match
  */
 public static boolean toBoolean(int value, int trueValue, int falseValue) {
     if (value == trueValue) {
         return true;
     } else if (value == falseValue) {
         return false;
     }
     // no match
     throw new IllegalArgumentException("The Integer did not match either specified value");
 }

}</source>





Converts a String to a Boolean.

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**

* Operations on boolean primitives and Boolean objects.
*
* This class tries to handle null input gracefully.
* An exception will not be thrown for a null input.
* Each method documents its behaviour in more detail.
* 
* @author Stephen Colebourne
* @author Matthew Hawthorne
* @author Gary Gregory
* @since 2.0
* @version $Id: BooleanUtils.java 589050 2007-10-27 05:07:45Z bayard $
*/

public class Main {

 /**
  * Converts a String to a Boolean.
  * 
  * "true", "on" or "yes"
  * (case insensitive) will return true.
  * "false", "off" or "no"
  * (case insensitive) will return false.
  * Otherwise, null is returned.</p>
  *
*
   *   BooleanUtils.toBooleanObject(null)    = null
   *   BooleanUtils.toBooleanObject("true")  = Boolean.TRUE
   *   BooleanUtils.toBooleanObject("false") = Boolean.FALSE
   *   BooleanUtils.toBooleanObject("on")    = Boolean.TRUE
   *   BooleanUtils.toBooleanObject("ON")    = Boolean.TRUE
   *   BooleanUtils.toBooleanObject("off")   = Boolean.FALSE
   *   BooleanUtils.toBooleanObject("oFf")   = Boolean.FALSE
   *   BooleanUtils.toBooleanObject("blue")  = null
   * 
  *
  * @param str  the String to check
  * @return the Boolean value of the string,
  *  null if no match or null input
  */
 public static Boolean toBooleanObject(String str) {
     if ("true".equalsIgnoreCase(str)) {
         return Boolean.TRUE;
     } else if ("false".equalsIgnoreCase(str)) {
         return Boolean.FALSE;
     } else if ("on".equalsIgnoreCase(str)) {
         return Boolean.TRUE;
     } else if ("off".equalsIgnoreCase(str)) {
         return Boolean.FALSE;
     } else if ("yes".equalsIgnoreCase(str)) {
         return Boolean.TRUE;
     } else if ("no".equalsIgnoreCase(str)) {
         return Boolean.FALSE;
     }
     // no match
     return null;
 }

}</source>





Convert String to Boolean

   <source lang="java">

public class Main {

   public static void main(String[] args) {
       String strBoolean = "true";
       
       //String to boolean conversion
       boolean theValue = Boolean.parseBoolean(strBoolean);
       
       System.out.println(theValue);
   }

} //true</source>





Create a boolean variable from string

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   // Parsing string "true" will result boolean true
   boolean boolA = Boolean.parseBoolean("true");
   System.out.println("boolA = " + boolA);
   // Parsing string "TRUE" also resutl boolean true
   boolean boolB = Boolean.parseBoolean("TRUE");
   System.out.println("boolB = " + boolB);
 }

}</source>





Create an Boolean object from boolean value

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   Boolean blnObj1 = new Boolean(true);
   Boolean blnObj2 = new Boolean("false");
   System.out.println(blnObj1);
   System.out.println(blnObj2);
 }

} /* true false

  • /</source>





Java boolean value

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   boolean b1 = true;
   boolean b2 = false;
   boolean b3 = (10 > 2) ? true : false;
   System.out.println("Value of boolean variable b1 is :" + b1);
   System.out.println("Value of boolean variable b2 is :" + b2);
   System.out.println("Value of boolean variable b3 is :" + b3);
 }

} /* Value of boolean variable b1 is :true Value of boolean variable b2 is :false Value of boolean variable b3 is :true

  • /</source>





java.lang.Boolean

The java.lang.Boolean class wraps a boolean. You can construct a Boolean object from a boolean or a String, using one of these constructors.



   <source lang="java">

public Boolean (boolean value)

    public Boolean (String value)</source>
   
  
 
  
false
true


Performs an xor on a set of booleans.

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**

* Operations on boolean primitives and Boolean objects.
*
* This class tries to handle null input gracefully.
* An exception will not be thrown for a null input.
* Each method documents its behaviour in more detail.
* 
* @author Stephen Colebourne
* @author Matthew Hawthorne
* @author Gary Gregory
* @since 2.0
* @version $Id: BooleanUtils.java 589050 2007-10-27 05:07:45Z bayard $
*/

public class Main {

 /**
  * Performs an xor on a set of booleans.
  *
*
   *   BooleanUtils.xor(new boolean[] { true, true })   = false
   *   BooleanUtils.xor(new boolean[] { false, false }) = false
   *   BooleanUtils.xor(new boolean[] { true, false })  = true
   * 
  *
  * @param array  an array of boolean<code>s
  * @return <code>true if the xor is successful.
  * @throws IllegalArgumentException if array is null
  * @throws IllegalArgumentException if array is empty.
  */
 public static boolean xor(boolean[] array) {
     // Validates input
     if (array == null) {
         throw new IllegalArgumentException("The Array must not be null");
     } else if (array.length == 0) {
         throw new IllegalArgumentException("Array is empty");
     }
     // Loops through array, comparing each item
     int trueCount = 0;
     for (int i = 0; i < array.length; i++) {
         // If item is true, and trueCount is < 1, increments count
         // Else, xor fails
         if (array[i]) {
             if (trueCount < 1) {
                 trueCount++;
             } else {
                 return false;
             }
         }
     }
     // Returns true if there was exactly 1 true item
     return trueCount == 1;
 }
 /**
  * Performs an xor on an array of Booleans.
  * 
*
   *   BooleanUtils.xor(new Boolean[] { Boolean.TRUE, Boolean.TRUE })   = Boolean.FALSE
   *   BooleanUtils.xor(new Boolean[] { Boolean.FALSE, Boolean.FALSE }) = Boolean.FALSE
   *   BooleanUtils.xor(new Boolean[] { Boolean.TRUE, Boolean.FALSE })  = Boolean.TRUE
   * 
  *
  * @param array  an array of Boolean<code>s
  * @return <code>true if the xor is successful.
  * @throws IllegalArgumentException if array is null
  * @throws IllegalArgumentException if array is empty.
  * @throws IllegalArgumentException if array contains a null
  */
 public static Boolean xor(Boolean[] array) {
     if (array == null) {
         throw new IllegalArgumentException("The Array must not be null");
     } else if (array.length == 0) {
         throw new IllegalArgumentException("Array is empty");
     }
     boolean[] primitive = null;
     try {
         primitive = toPrimitive(array);
     } catch (NullPointerException ex) {
         throw new IllegalArgumentException("The array must not contain any null elements");
     }
     return xor(primitive) ? Boolean.TRUE : Boolean.FALSE;
 }
 /**
  * Converts an array of object Booleans to primitives.
  *
  * This method returns null for a null input array.
  * 
  * @param array  a Boolean array, may be null
  * @return a boolean array, null if null array input
  * @throws NullPointerException if array content is null
  */
 public static boolean[] toPrimitive(Boolean[] array) {
     if (array == null) {
         return null;
     } else if (array.length == 0) {
         return new boolean[0];
     }
     final boolean[] result = new boolean[array.length];
     for (int i = 0; i < array.length; i++) {
         result[i] = array[i].booleanValue();
     }
     return result;
 }

}</source>





toString(): return the string representation of a boolean

The static method toString() returns the string representation of a boolean: public static String toString (boolean boolean)



   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
   Boolean b = Boolean.valueOf("true");
   System.out.println(b.toString());
 }

}</source>



true


Using the boolean type

   <source lang="java">

public class MainClass {

 public static void main(String args[]) {
   boolean b;
  
   b = false;
   System.out.println("b is " + b);
   b = true;
   System.out.println("b is " + b);
  
   // a boolean value can control the if statement
   if(b) System.out.println("This is executed.");
  
   b = false;
   if(b) System.out.println("This is not executed.");
  
   // outcome of a relational operator is a boolean value
   System.out.println("10 > 9 is " + (10 > 9));
 }

}</source>



b is false
b is true
This is executed.
10 > 9 is true


valueOf(): parse a String to a Boolean object

The static method valueOf parses a String to a Boolean object: public static Boolean valueOf (String string)



   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
   Boolean b = Boolean.valueOf("true");
   System.out.println(b);
 }

}</source>



true