Write java program for String Concatenation.

Write code to get two strings as input and If strings are of the same length simply append them together and return the final string. If given strings are of different length, remove starting characters from the long string so that both strings are of the same length then append them together and return the final string.

The return type of the output is a string which is the concatenated string.

Input and Output Format:

Input consists of two strings.

The output is a string.

Refer sample output for formatting specifications.

Sample Input 1:

Hello

hi

Sample Output 1:

lohi

Sample Input 2:

Hello

Delhi

Sample Output 2:

HelloDelhi

String Concatenation in Java.

import java.util.Scanner;

public class Main {
  /**
   * @param args
   */
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String s1 = sc.nextLine();
    String s2 = sc.nextLine();

    getvalues(s1, s2);
  }

  public static void getvalues(String s1, String s2) {
    StringBuffer sb = new StringBuffer();
    int l1 = s1.length();
    int l2 = s2.length();
    if (l1 == l2) {
      sb.append(s1).append(s2);
    } else if (l1 > l2) {
      sb.append(s1.substring(s1.length() - s2.length(), s1.length()))
          .append(s2);
    } else if (l1 < l2) {
      sb.append(s1).append(
          s2.substring(s2.length() - s1.length(), s2.length()));
    }
    System.out.println(sb);
  }

}

Add a Comment

Your email address will not be published. Required fields are marked *

1 × 2 =