How do we mix two strings and generate another in java?


Strings are used to store a sequence of characters in Java, they are treated as objects. The String class of the java.lang package represents a String.

You can create a String either by using the new keyword (like any other object) or, by assigning value to the literal (like any other primitive datatype).

String stringObject = new String("Hello how are you");
String stringLiteral = "Welcome to Tutorialspoint";

Concatenating Strings

You can concatenate Strings in Java in the following ways −

Using the "+" operator − Java Provides a concatenation operator using this, you can directly add two String literals

Example

import java.util.Scanner;
public class StringExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the first string: ");
      String str1 = sc.next();
      System.out.println("Enter the second string: ");
      String str2 = sc.next();
      //Concatenating the two Strings
      String result = str1+str2;
      System.out.println(result);
   }
}

Output

Enter the first string:
Krishna
Enter the second string:
Kasyap
KrishnaKasyap
Java

Using the concat() method − The concat() method of the String class accepts a String value, adds it to the current String and returns the concatenated value.

Example

import java.util.Scanner;
public class StringExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the first string: ");
      String str1 = sc.next();
      System.out.println("Enter the second string: ");
      String str2 = sc.next();
      //Concatenating the two Strings
      String result = str1.concat(str2);
      System.out.println(result);
   }
}

Output

Enter the first string:
Krishna
Enter the second string:
Kasyap
KrishnaKasyap

Using StringBuffer and StringBuilder classes − StringBuffer and StringBuilder classes are those that can be used as alternative to String when modification needed.

These are similar to String except they are mutable. These provide various methods for contents manipulation. The append() method of these classes accepts a String value and adds it to the current StringBuilder object.

Example

import java.util.Scanner;
public class StringExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the first string: ");
      String str1 = sc.next();
      System.out.println("Enter the second string: ");
      String str2 = sc.next();
      StringBuilder sb = new StringBuilder(str1);
      //Concatenating the two Strings
      sb.append(str2);
      System.out.println(sb);
   }
}

Output

Enter the first string:
Krishna
Enter the second string:
Kasyap
KrishnaKasyap

Updated on: 10-Oct-2019

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements