Compare Two Strings in Java


Q. Write a Java program to compare two strings

import java.util.Scanner;

public class CompareStrings {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Read two strings from the user
        System.out.print("Enter the first string: ");
        String str1 = scanner.nextLine();

        System.out.print("Enter the second string: ");
        String str2 = scanner.nextLine();

        // Compare strings using equals() method
        if (str1.equals(str2)) {
            System.out.println("The strings are equal.");
        } else {
            System.out.println("The strings are NOT equal.");
        }

        scanner.close();
    }
}

Q. Write an algorithm to compare two strings

 1. Start
2. Read first string str1
3. Read second string str2
4. Use str1.equals(str2) to compare both strings
     If true, print "Strings are equal"
     Else, print "Strings are not equal"
5. End



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.