String Concatenation in Scala: How to add two Strings in Scala?

Here, we will learn about the String Concatenation in Scala. We will see the methods to add two strings in Scala with examples.
Submitted by Shivang Yadav, on February 05, 2021

String is an immutable collection that stores sequences of characters. There are various operations and methods defined on strings in Scala for proper functioning of the collections. One of them is concatenation.

String Concatenation

String Concatenation is joining two different strings to form a single one.

Scala provides two methods to concatenate strings. They are:

  1. concat() method
  2. '+' operator

The concat() method for string concatenation

The concat() method is used to add two strings and return a new method containing the character form both strings.

Syntax:

string1.concat(string2)

Parameters: The method accepts a single parameter which is the string to be added.

Return type: It returns the concatenated string.

Program to illustrate the working of concat() method in Scala

object myObject {
    def main(args: Array[String]) {
        val string1 = "Scala "
        val string2 = "Programming Language"
        
        val concatString = string1.concat(string2)
        
        println("The concatenated string is " + concatString)
    }
}

Output:

The concatenated string is Scala Programming Language

The '+' operator for string concatenation

The '+' operator adds the two strings and returns the result of addition.

Syntax:

string1 + string2

Program to illustrate the working of '+' operator

object myObject {
    def main(args: Array[String]) {
        val string1 = "Scala "
        val string2 = "Programming Language"
        
        val concatString = string1 + string2
        
        println("The concatenated string is " + concatString)
    }
}

Output:

The concatenated string is Scala Programming Language




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

© https://www.includehelp.com some rights reserved.