Home »
Scala language
How to convert string to boolean in Scala?
Scala | Convert string to boolean: Here, we will learn to convert string to boolean in Scala. We will see the method with examples that will be used for the conversion.
Submitted by Shivang Yadav, on June 13, 2020
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,
- Boolean.parseBoolean()
- Boolean.valueOf()
1) Convert string to boolean using Boolean.parseBoolean()
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
2) Convert string to boolean using Boolean.valueOf()
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