w3resource
Java Programming Exercies

Java String Exercises: Read two strings append them together and return the result

Java String: Exercise-60 with Solution

Write a Java program to read two strings append them together and return the result.If the strings are different lengths, omit chars from the beginning of longer string and make them equal length.

Sample Solution:

Java Code:

import java.util.*;
public class Main
{
public String minCat(String st1, String st2) 
{
  if (st1.length() == st2.length())
    return st1+st2;
  if (st1.length() > st2.length())
  {
    int diff = st1.length() - st2.length();
    return st1.substring(diff, st1.length()) + st2;
  } else 
  {
    int diff = st2.length() - st1.length();
    return st1 + st2.substring(diff, st2.length());
  }
}
public static void main (String[] args)
    {
      Main m= new Main();
      String str1 =  "Welcome";
	  String str2 =  "home";
	  
      System.out.println("The given strings is: "+str1+" and "+str2);
      System.out.println("The new string is: "+m.minCat(str1,str2));
	  }
}

Sample Output:

The given strings is: Welcome and home
The new string is: comehome

Pictorial Presentation:

Java String Exercises: Read two strings append them together and return the result

Flowchart:

Flowchart: Java String Exercises - Read two strings append them together and return the result

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to read a string,if the string begins with "red" or "black" return that color string, otherwise return the empty string.
Next: Write a Java program to read a string and an int n, return a string made of the first and last n characters from the string.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming