Write a program to find maximum between two string


This is a Java program that compares the lengths of two input strings and outputs the one with the maximum length.

  • The program starts by importing the Scanner class from the java.util package. It defines a class Maximum_String and a main() method.
  • Inside the main() method, it creates a new Scanner object input and prompts the user to enter two strings using the System.out.print() method and reads them using the nextLine() method of the Scanner class.
  • It then calculates the length of both strings using the length() method of the String class and stores them in variables len1 and len2.
  • It then checks if len1 is greater than len2, prints str1 followed by the message "is Maximum String.." to the console using the System.out.println() method. If len2 is greater than len1, it prints str2 followed by the message "is Maximum String..". If both len1 and len2 are equal, it prints both the strings followed by the message "Both are Same Length".

Source Code

import java.util.Scanner;
class Maximum_String
{
	public static void main(String args[])
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter the String 1 :");
		String str1 = input.nextLine();
		System.out.print("Enter the String 2 :");
		String str2 = input.nextLine();
		int len1 = str1.length();
		int len2 = str2.length();
		if(len1>len2)
			System.out.println(str1+" is Maximum String..");
		else if(len2>len1)		
			System.out.println(str2+" is Maximum String..");
		else			
			System.out.println(str1+" or "+str2+" Both are Same Length");
	}
}

Output

Enter the String 1 :Apple
Enter the String 2 :Banana
Banana is Maximum String..

Example Programs