Compare string example

In this section, you will learn how to compare two string in java.

Compare string example

In this section, you will learn how to compare two string in java.

 Compare string example

Compare strings example

     

In this section, you will learn how to compare two strings in java. The java lang package provides a method to compare two with their case either upper and lower. The equals() method provides the facility of comparing the two strings. The following program uses the equals() method and helps you to compare the two strings. If both strings are equal, it will display a message "The given strings are equal" otherwise it will show "The given string are not equal".

Description of code:

equals():
This is the method that compares an object values and returns Boolean type value either 'true' or 'false'. If it returns 'true' for the both objects, it will be equal otherwise not. 

Here is the code of program:

import java.lang.*;
import java.io.*;

public class CompString{
  public static void main(String[] argsthrows IOException{
  System.out.println("String equals or not example!");
  BufferedReader bf = 
new 
BufferedReader(new InputStreamReader(System.in));
  System.out.println("Please enter first string:");
  String str1 = bf.readLine();
  System.out.println("Please enter second string:");
  String str2 = bf.readLine();
  if (str1.equals(str2)){
  System.out.println("The given string is equals");
  }
  else{
  System.out.println("The given string is not equals");
  }
  }
}

Download this example.

Output of program:

Both are equals:

C:\vinod\Math_package>javac CompString.java

C:\vinod\Math_package>java CompString
String equals or not example!
Please enter first string:
Rose
Please enter second string:
Rose
The given string is equals

Both are not equals:

C:\vinod\Math_package>java CompString
String equals or not example!
Please enter first string:
Rose
Please enter second string:
rose
The given string is not equals