Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to compare two string.

Java Code Example — String Programs

ADVERTISEMENT

Java Program to compare two string.

Objective

Write a Java program to compare two strings to see if they are identical.

Algorithm / Approach

  1. Read two strings from the user and store them in s1 and s2.
  2. Use the equals() method in an if condition: if(s1.equals(s2)).
  3. If it returns true, print "SAME STRING".
  4. Otherwise, print "DIFFERENT STRING".
Test.java
import java.util.Scanner;
class Test {
 public static void main(String[] a)
 {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter 1st String: ");
  String s1 = s.nextLine();
  System.out.print("Enter 2nd String: ");
  String s2 = s.nextLine();
  if(s1.equals(s2)) {
   System.out.print("SAME STRING");
  }
  else {
   System.out.print("DIFFERENT STRING");
  }
 }
}

Expected Output

Enter 1st String: java prowess
Enter 2nd String: c++ prowess
DIFFERENT STRING

Explanation of the Program

  • In Java, you should NEVER use the == operator to compare the actual text of two strings. The == operator checks if both variables point to the exact same memory location, not if their text is the same.
  • The equals() method strictly compares the characters inside the strings for an exact match, including case sensitivity.
  • If you wanted to ignore case sensitivity, you would use equalsIgnoreCase() instead.

Complexity

Time Complexity O(n) - Checks characters one by one until a mismatch is found.
Space Complexity O(1)
ADVERTISEMENT