This is actually being a problem for me.
I am working with my java code & I am not sure how to convert a boolean value to a string?
I need some help in java converting boolean to string.
This is actually being a problem for me.
I am working with my java code & I am not sure how to convert a boolean value to a string?
I need some help in java converting boolean to string.
Convert Boolean to String
Code: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 to String
This program helps you in converting the Boolean type data into a string. The toString() method reads the Boolean type object and it converts into a string format. This method returns a string object and represents the boolean’s value. The Boolean object represents either “true” or “false".
code
OutputCode:import java.util.*; public class BooleanToString{ public static void main(String[] args){ boolean b = true; String s = new Boolean(b).toString(); System.out.println("String is:"+ s); } }
Code:C:\corejava>java BooleanToString String is:true C:\corejava>
Convert String to Boolean
Try this for reverse conversion from string data type to boolean.
There are 2 ways to do so.
1. you can create an instance of the wrapper class Boolean with a string value as argument to the constructor and call the method booleanValue()
2. call the static method parseBoolean() of the wrapper class to convert the string value to a boolean.
Note : The string value sent in has to be either 'true' or 'TRUE' to result in a boolean with the value of true, but it doesn't have to be 'false' to result in a false boolean value.
It actually makes sense that any other string value than 'true' or 'TRUE' will result in a return value that is set to false.
Code:/** * Main.java * * @author www.javadb.com */ public class Main { /** * String to boolean conversion */ public void convertStringToBoolean() { String strBoolean = "true"; //Do the String to boolean conversion boolean theValue = Boolean.parseBoolean(strBoolean); System.out.println(theValue); } /** * Starts the program * * @param args the command line arguments */ public static void main(String[] args) { new Main().convertStringToBoolean(); } }
Bookmarks