A string is a sequence of characters. In Scala, objects of String are immutable which means a constant and cannot be changed once created. when a new string is created by adding two strings is known as a concatenation of strings. Scala provides concat() method to concatenate two strings, this method returns a new string which is created using two strings. we can also use ‘+’ operator to concatenate two strings.
Syntax:
str1.concat(str2);
Or
"str1" + "str2";
Below is the example of concatenating two strings.
Using concat() method: This method appends argument to the string.
Example #1:
Scala
object GFG
{
var str 1 = "Welcome! GeeksforGeeks "
var str 2 = " to Portal"
def main(args : Array[String])
{
var Newstr = str 1 .concat(str 2 );
println( "String 1:" +str 1 );
println( "String 2:" +str 2 );
println( "New String :" +Newstr);
println( "This is the tutorial" +
" of Scala language" +
" on GFG portal" );
}
}
|
Output:
String 1:Welcome! GeeksforGeeks
String 2: to Portal
New String :Welcome! GeeksforGeeks to Portal
This is the tutorial of Scala language on GFG portal
In above example, we are joining the second string to the end of the first string by using concat() function. string 1 is Welcome! GeeksforGeeks string 2 is to Portal. After concatenating two string we get new string Welcome! GeeksforGeeks to Portal.
Using + operator : we can add two string by using + operator.
Example #2:
Scala
object GFG
{
def main(args : Array[String])
{
var str 1 = "Welcome to " ;
var str 2 = "GeeksforGeeks" ;
println( "After concatenate two string: " + str 1 + str 2 );
}
}
|
Output:
After concatenate two string: Welcome toGeeksforGeeks
In above example, string 1 is Welcome to string 2 is GeeksforGeeks. By using + operator concatenating two string we get output After concatenate two string: Welcome toGeeksforGeeks.