Table of Contents
In this post, we will see how to convert 0 and 1 to Boolean in Java.
Given “0” and “1” in String datatype, convert it to boolean datatype where
“0” represents false
“1” represents true
Convert 0 and 1 to Boolean in Java
Here is program to convert 0 and 1 to boolean in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package org.arpit.java2blog; public class Convert0And1ToBoolean { public static void main(String[] args) { boolean boolean1 = getBoolean("1"); System.out.println("Boolean value for 1: "+boolean1); boolean boolean2 = getBoolean("0"); System.out.println("Boolean value for 0: "+boolean2); } public static boolean getBoolean(String value) { return !value.equals("0"); } } |
Output
1 2 3 4 |
Boolean value for 1: true Boolean value for 0: false |
In case, if you have integer values as 0 and 1, you can just make small change to getBoolean()
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package org.arpit.java2blog; public class Convert0And1ToBooleanInt { public static void main(String[] args) { boolean boolean1 = getBoolean(1); System.out.println("Boolean value for 1: "+boolean1); boolean boolean2 = getBoolean(0); System.out.println("Boolean value for 0: "+boolean2); } public static boolean getBoolean(int value) { return (value!=0); } } |
Output
1 2 3 4 |
Boolean value for 1: true Boolean value for 0: false |
Utility method to convert all possible values to boolean in Java
Here is simple utility method to convert all possible values to boolean in Java.
1 2 3 4 5 6 7 8 9 |
private boolean convertToBoolean(String value) { boolean returnValue = false; if ("1".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value) || "on".equalsIgnoreCase(value)) returnValue = true; return returnValue; } |
That’s all about how to convert 0 and 1 to boolean in Java.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.