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.
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);
}
}
Boolean Data Type
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);
}
}
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.
public class MainClass {
public static void main(String[] args) {
boolean includeSign = true;
System.out.println(includeSign);
}
}
Boolean Variables
- Variables of type boolean can have only one of two values, true or false.
- The values "true" and "false" are boolean literals.
public class MainClass{
public static void main(String[] arg){
boolean state = true;
state = false;
System.out.println(state);
}
}
false
Compare Two Java boolean Arrays Example
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));
}
}
Convert boolean to integer
public class Main {
public static void main(String[] args) throws Exception {
boolean b = true;
int i = (b) ? 1 : 0;
}
}
Convert Boolean to String
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
Convert boolean value to Boolean
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);
}
}
Convert integer to boolean
public class Main {
public static void main(String[] args) throws Exception {
int i=10;
boolean b = (i != 0);
System.out.println(b);
}
}
//true
Convert Java boolean Primitive to Boolean object
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);
}
}
Convert Java String Object to Boolean Object
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);
}
}
Converts a boolean to a String returning "yes" or "no"
/*
* 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 <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code> 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 <code>"yes"</code>
* or <code>"no"</code>.
*
* <pre>
* BooleanUtils.toStringYesNo(true) = "yes"
* BooleanUtils.toStringYesNo(false) = "no"
* </pre>
*
* @param bool the Boolean to check
* @return <code>"yes"</code>, <code>"no"</code>,
* or <code>null</code>
*/
public static String toStringYesNo(boolean bool) {
return toString(bool, "yes", "no");
}
/**
* Converts a boolean to a String returning one of the input Strings.
*
* <pre>
* BooleanUtils.toString(true, "true", "false") = "true"
* BooleanUtils.toString(false, "true", "false") = "false"
* </pre>
*
* @param bool the Boolean to check
* @param trueString the String to return if <code>true</code>,
* may be <code>null</code>
* @param falseString the String to return if <code>false</code>,
* may be <code>null</code>
* @return one of the two input Strings
*/
public static String toString(boolean bool, String trueString, String falseString) {
return bool ? trueString : falseString;
}
}
Converts an Integer to a boolean specifying the conversion values.
/*
* 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 <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code> 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.
*
* <pre>
* 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
* </pre>
*
* @param value the Integer to convert
* @param trueValue the value to match for <code>true</code>,
* may be <code>null</code>
* @param falseValue the value to match for <code>false</code>,
* may be <code>null</code>
* @return <code>true</code> or <code>false</code>
* @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");
}
}
Converts an int to a boolean specifying the conversion values.
/*
* 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 <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code> 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.
*
* <pre>
* BooleanUtils.toBoolean(0, 1, 0) = false
* BooleanUtils.toBoolean(1, 1, 0) = true
* BooleanUtils.toBoolean(2, 1, 2) = false
* BooleanUtils.toBoolean(2, 2, 0) = true
* </pre>
*
* @param value the Integer to convert
* @param trueValue the value to match for <code>true</code>
* @param falseValue the value to match for <code>false</code>
* @return <code>true</code> or <code>false</code>
* @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");
}
}
Converts a String to a Boolean.
/*
* 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 <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code> 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.
*
* <code>"true"</code>, <code>"on"</code> or <code>"yes"</code>
* (case insensitive) will return <code>true</code>.
* <code>"false"</code>, <code>"off"</code> or <code>"no"</code>
* (case insensitive) will return <code>false</code>.
* Otherwise, <code>null</code> is returned.</p>
*
* <pre>
* 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
* </pre>
*
* @param str the String to check
* @return the Boolean value of the string,
* <code>null</code> if no match or <code>null</code> 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;
}
}
Convert String to Boolean
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
Create a boolean variable from string
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);
}
}
Create an Boolean object from boolean value
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
*/
Java boolean value
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
*/
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.
public Boolean (boolean value)
public Boolean (String value)
false true
Performs an xor on a set of booleans.
/*
* 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 <code>null</code> input gracefully.
* An exception will not be thrown for a <code>null</code> 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.
*
* <pre>
* BooleanUtils.xor(new boolean[] { true, true }) = false
* BooleanUtils.xor(new boolean[] { false, false }) = false
* BooleanUtils.xor(new boolean[] { true, false }) = true
* </pre>
*
* @param array an array of <code>boolean<code>s
* @return <code>true</code> if the xor is successful.
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> 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.
*
* <pre>
* 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
* </pre>
*
* @param array an array of <code>Boolean<code>s
* @return <code>true</code> if the xor is successful.
* @throws IllegalArgumentException if <code>array</code> is <code>null</code>
* @throws IllegalArgumentException if <code>array</code> is empty.
* @throws IllegalArgumentException if <code>array</code> contains a <code>null</code>
*/
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 <code>null</code> for a <code>null</code> input array.
*
* @param array a <code>Boolean</code> array, may be <code>null</code>
* @return a <code>boolean</code> array, <code>null</code> if null array input
* @throws NullPointerException if array content is <code>null</code>
*/
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;
}
}
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)
public class MainClass {
public static void main(String[] args) {
Boolean b = Boolean.valueOf("true");
System.out.println(b.toString());
}
}
true
Using the boolean type
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));
}
}
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)
public class MainClass {
public static void main(String[] args) {
Boolean b = Boolean.valueOf("true");
System.out.println(b);
}
}
true