Tuesday, September 2, 2008

Comparing Two Strings Using equals()

The given example show you how to compare two strings with the help of equals() method in java. The equals() method is used to compare the contents of objects. The method returns value in either "true" or "false". The code give below compare two strings whether both are equal or not. If both are same then it returns true else not :

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

public class equalstrings{
public static void main(String[] args) throws IOException{
System.out.println("String Compares Example Using Equals() Method");
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter First String:");
String str1 = bf.readLine();
System.out.println("Enter Second String to Compare :");
String str2 = bf.readLine();
if (str1.equals(str2)){
System.out.println("Both the Strings are Equal!");
System.out.println("Both the Strings are not Equal!");