Compare Two Strings in Java

Exercise:

Write a Java Program to compare two strings.

Click Here to View the Solution!
public class CompareTwoStrings {
  
     public static void main(String[] args) {
         String style = new String("Java");
         String style2 = new String("Javascript");
  
         if(style.equals(style2))
             System.out.println("Equal");
         else
             System.out.println("Not Equal");
     }
 } 
Click Here to View the Output!
Not Equal
Click Here to View the Explanation!
  • This program deals with the comparison between two strings by employing equals() method.
  • In comparison with the previous example, strings in this example are produced by employing String constructor.
  • In the if condition equals () method takes style2 string as an argument, and is called upon style to compare the contents.  
  • In the previous example, referencing was being compared instead of actual contents.
  • The console displays ‘Equal’ if the contents of strings are identical and ‘Not Equal’ otherwise.
  • The Output is ‘ Not Equal’ as the contents of both strings are not identical.
  • Output would have been “ Equal”, if both strings were identical.

%d bloggers like this: