English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java Input/Output (I/O)

Java Reader/Writer

Other Java topics

Java program converts string (string) type variable to boolean (boolean)

    Java Examples Comprehensive

In this program, we will learn how to convert a String type variable to a boolean in Java.

To understand this example, you should understand the followingJava programmingTopic:

Example1: Use parseBoolean() to convert a string to a Boolean value

class Main {
  public static void main(String[] args) {
    //Create String Variable
    String str1 ="true";
    String str2 ="false";
    //Convert String to Boolean
    //Use parseBoolean()
    boolean b1 = Boolean.parseBoolean(str1);
    boolean b2 = Boolean.parseBoolean(str2);
    //Printing Boolean Value
    System.out.println(b1);    // true
    System.out.println(b2);    // false
  }
}

In the above example, we use the parseBoolean() method of the Boolean class to convert a string variable to a Boolean value.

Here, Boolean is a wrapper class in Java. For more information, please visitJava Wrapper class.

Example2: Use valueOf() to convert a string to a Boolean value

We can also use the valueOf() method to convert a string variable to a boolean (Boolean value). For example,

class Main {
  public static void main(String[] args) {
    //Create String Variable
    String str1 ="true";
    String str2 ="false";
    //Convert String to Boolean
    //Using valueOf()
    boolean b1 Boolean.valueOf(str1);
    boolean b2 Boolean.valueOf(str2);
    //Printing Boolean Value
    System.out.println(b1);    // true
    System.out.println(b2);    // false
  }
}

In the above example, the valueOf() method of the Boolean class converts the string variable to a boolean value.

Here, the valueOf() method actually returns an object of the Boolean class. However, the object is automatically converted to the primitive type. In Java, this is called unboxing. Learn more atJava Auto-boxing and Unboxing.

That is,

//valueOf() returns a Boolean object
//Object to Boolean Conversion
boolean b1 Boolean obj = Boolean.valueOf(str1)

Java Examples Comprehensive