Scala program to convert string to integer

Scala | Converting string to integer: Here, we are going to learn how to convert a given string to an integer in Scala programming language?
Submitted by Shivang Yadav, on April 21, 2020

In Scala, there is a huge library to support different operations on a string. One such operation is to convert string to int in Scala.

A string can be converted to integer in Scala using the toInt method.



This will return the integer conversion of the string. If the string does not contain an integer it will throw an exception with will be NumberFormatException.

So, the statement: val i = "Hello".toInt will throw an exception instead of an integer.

So, we need to handle this exception and we will do this using the try-catch block and print "The string in not integer" when the string to be converted does not contain an integer value.

Program to convert string to integer in Scala

object MyClass {
       def main(args: Array[String]) {
        val string = "1C 2C++ 3Java"
        val stringContents = string.split("\\d+")
        println("Content of the string are: ")
        for(i <- 0 to stringContents.length-1)


The string is : 12345
Integer Conversion of string is 12345

Scala String Programs »



Comments and Discussions



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.