×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

How to convert string to boolean in Scala?

By IncludeHelp Last updated : October 20, 2024

String in Scala is a sequence of characters. In Scala, the String object is immutable.

Example:

String("includehelp.com")

A Boolean is a data type in Scala programming language (and another programming also), that is used or Boolean algebra. It has two valid values i.e. true and false.

Example:

var bool : Boolean = true; 

Convert string to boolean

The conversion from string to boolean can be done using multiple methods,

  1. Boolean.parseBoolean()
  2. Boolean.valueOf()

Convert string to boolean using Boolean.parseBoolean()

The Boolean.parseBoolean() method is used to convert a string to a boolean value. It returns true if the string is "true" (ignoring case), and false for any other input.

Syntax

Boolean.parseBoolean(String): Boolean

Scala program to convert String to Boolean using Boolean.parseBoolean()

import java.lang.Boolean
object MyClass {
    def main(args: Array[String]) {
         // For False values 
        println("String to Boolean for false values ")
        println(Boolean.parseBoolean("False"))
        println(Boolean.parseBoolean("false"))
        println(Boolean.parseBoolean("No"))
        println(Boolean.parseBoolean("FALSE"))
        
        // For Truth values 
        println("String to Boolean for false values ")
        println(Boolean.parseBoolean("True"))
        println(Boolean.parseBoolean("true"))
        println(Boolean.parseBoolean("TRUE"))
    }
}

Output:

String to Boolean for false values 
false
false
false
false
String to Boolean for false values 
true
true
true

Convert string to boolean using Boolean.valueOf()

The Boolean.valueOf() method converts a string to a Boolean object. It returns true if the string is "true" (ignoring case), and false for any other value.

Syntax

Boolean.valueOf(String) : Boolean

Scala program to convert String to Boolean using Boolean.valueOf()

import java.lang.Boolean
object MyClass {
    def main(args: Array[String]) {
         // For False values 
        println("String to Boolean for false values ")
        println(Boolean.valueOf("False"))
        println(Boolean.valueOf("false"))
        println(Boolean.valueOf("No"))
        println(Boolean.valueOf("FALSE"))
        
        // For Truth values 
        println("String to Boolean for false values ")
        println(Boolean.valueOf("True"))
        println(Boolean.valueOf("true"))
        println(Boolean.valueOf("TRUE"))
    }
}

Output:

String to Boolean for false values 
false
false
false
false
String to Boolean for false values 
true
true
true

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.