Java Tutorial/Data Type/Boolean
Содержание
- 1 Autoboxing/unboxing a Boolean and Character.
- 2 Boolean Data Type
- 3 Boolean Literals
- 4 Boolean Variables
- 5 Compare Two Java boolean Arrays Example
- 6 Convert boolean to integer
- 7 Convert Boolean to String
- 8 Convert boolean value to Boolean
- 9 Convert integer to boolean
- 10 Convert Java boolean Primitive to Boolean object
- 11 Convert Java String Object to Boolean Object
- 12 Converts a boolean to a String returning "yes" or "no"
- 13 Converts an Integer to a boolean specifying the conversion values.
- 14 Converts an int to a boolean specifying the conversion values.
- 15 Converts a String to a Boolean.
- 16 Convert String to Boolean
- 17 Create a boolean variable from string
- 18 Create an Boolean object from boolean value
- 19 Java boolean value
- 20 java.lang.Boolean
- 21 Performs an xor on a set of booleans.
- 22 toString(): return the string representation of a boolean
- 23 Using the boolean type
- 24 valueOf(): parse a String to a Boolean object
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
- Variables of type boolean can have only one of two values, true or false.
- 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 handlenull
input gracefully. * An exception will not be thrown for anull
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"
, * ornull
*/ 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 iftrue
, * may benull
* @param falseString the String to return iffalse
, * may benull
* @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 handlenull
input gracefully. * An exception will not be thrown for anull
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 fortrue
, * may benull
* @param falseValue the value to match forfalse
, * may benull
* @returntrue
orfalse
* @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 handlenull
input gracefully. * An exception will not be thrown for anull
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 fortrue
* @param falseValue the value to match forfalse
* @returntrue
orfalse
* @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 handlenull
input gracefully. * An exception will not be thrown for anull
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 returntrue
. *"false"
,"off"
or"no"
* (case insensitive) will returnfalse
. * 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 ornull
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 handlenull
input gracefully. * An exception will not be thrown for anull
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 ifarray
isnull
* @throws IllegalArgumentException ifarray
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 ofBoolean<code>s * @return <code>true
if the xor is successful. * @throws IllegalArgumentException ifarray
isnull
* @throws IllegalArgumentException ifarray
is empty. * @throws IllegalArgumentException ifarray
contains anull
*/ 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 returnsnull
for anull
input array. * * @param array aBoolean
array, may benull
* @return aboolean
array,null
if null array input * @throws NullPointerException if array content isnull
*/ 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