Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Beginners Compare string example

 
 

Share on Google+Share on Google+

Compare string example

Advertisement
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
Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 8, 2007

Related Tutorials

Discuss: Compare string example   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:5
Talal
October 7, 2011
it was very helpful

nice explanation. keep going...
yuda
July 4, 2012
thanks

thanks very useful
Surbhi Agarwal
September 7, 2012
Java and visual basics

I am the fresher for this site and i need the complete guidance for my subjects thats why i have tried this site with hoping of help
Shrikant
March 8, 2013
Thank you

Really thanks u for this post.
Ajin
March 28, 2013
Good,thanks

THank u for the great information
DMCA.com