Home Java Beginners Compare string example



Compare string example
Posted on: June 8, 2007 at 12:00 AM
In this section, you will learn how to compare two string in java.

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

Related Tags for Compare string example:
javacstringcomidestringshelpmethoddisplaycompareviequalsmessageidpackagecasecasshowifwithprogramtoramcilcilanshboteilitdesnotlslisplusewisepeinnoasmplayparpstrsagecacomparingjisppackesaseagemehowproppackequalwersssaspesspackisirllivfollowandarstrsawingwisvausestwssriringthshoavstdispeitherpariplprndomogrolo


More Tutorials from this section

Ask Questions?    Discuss: Compare string example   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.