Pre Exam Test Practice (SSC | Banking | IAS | GATE | State Level | CLAT | Railways | Insurance | Teaching Exams | NDA | Defence | IES |State Exam )

Organizational Research By

Surprising Reserch Topic

Java – boolean to String conversion

There are two methods by which we can convert a boolean to String:
1) Method 1: Using String.valueOf(boolean b): This method accepts the boolean argument and converts it into an equivalent String value.
Method declaration:
public static String valueOf(boolean b)
b – represent the boolean variable which we want to convert
String representation of b

boolean boovar = true;
String str = String.valueOf(boovar);
2) Method 2: Using Boolean.toString(boolean b): This method works same as String.valueOf() method. It belongs to the Boolean class and converts the specified boolean to String. If the passes boolean value is true then the returned string would be having “true” value, similarly for false the returned string would be having “false” value.
Method declaration:
public static String toString(boolean b)
b – represent the boolean variable that needs to be converted
The string representing the passed boolean value.

boolean boovar = false;
String str = Boolean.toString(boovar);
Example: Converting boolean to String

This program demonstrates the use of both the above mentioned methods. Here we have two boolean variables and we are converting one of them using String.valueOf() method and other one using Boolean.toString() method.

package com.beginnersbook.string;

public class BooleanToString {
    public static void main(String[] args) {
        /* Method 1: using valueOf() method
         * of String class.
        boolean boovar = true;
        String str = String.valueOf(boovar);
        System.out.println("String is: "+str);
        /* Method 2: using toString() method
         * of Boolean class
        boolean boovar2 = false;
        String str2 = Boolean.toString(boovar2);
        System.out.println("String2 is: "+str2);

String is: true
String2 is: false

asked Jun 11, 2015 in Java Interview Questions by rajesh
0 votes

Related Hot Questions

Government Jobs Opening