CopyPastehas never been so tasty!

Convert String and integer into Boolean in java

by anonymous

  • 0
  • 0
  • 0
103 views

Convert String and integer into Boolean in java

Boolean Data Type:In Boolean data type there are only two conditions that is true or false, yes or no, or on or off.  It is Built- in data type in Java. Conversion of Boolean to String:To convert a Boolean value to a String you need to use the class of the Boolean data type that will tell whether it is true or false then it will print the value as String. ToString() method reads the Boolean type object and converts it into a string  and returns a string object .Here is the simple code that converts Boolean to String:

public class Main {   

    /**

    * Convert Boolean to String conversion

     */

    public void convertBooleanToString()

 {

      boolean theValue = true;

       //Boolean to String Conversion

        String theValueAsString = new Boolean(theValue).toString();

        System.out.println(theValueAsString);

    }

    public static void main(String[] args)

    {

        new Main().convertBooleanToString();

    }

}

Conversion of String to Boolean:

To convert a Boolean value you make an instance of the class and pass the Boolean value as argument to the constructor.

Then you simply call the toString ( ) method which will return a String.

Following is the sample code to convert String to Boolean:

public class Main {

    /**

     * String to boolean conversion

     */

    public void convertStringToBoolean() {

        String myBoolean = "true";

        //Perform the String to boolean conversion

        boolean theValue = Boolean.parseBoolean(myBoolean);

        System.out.println(theValue);

    }

    public static void main(String[] args) {

        new Main().convertStringToBoolean();

    }

}

Conversion of Boolean to Integer:

To convert the Boolean to integer, first you have to make a class with public access and then you have to pass the value as an argument. An exception will occur.

Exception: An exception is an event that occurs during the execution of a program that disturbs the flow of instructions.Here is a simple code:

 public class Main {

  public static void main(String [] args) throws Exception {
    int i=10;
    Boolean x = (i != 0);

    System.out.println(a);
  }
}
//true

 Conversion of Integer to Boolean:

 To convert the integer to Boolean you have make a class with public access and then you have pass the argument as String. You also have to use conditional operator. An exception will occur.Here is simple code that converts Integer to Boolean:

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

This simple article tells you about conversion of Boolean to string and integer and vice versa.

Add A Comment: