CodesJava

Easy learning with example program codes

String comparison in java


In java there are three ways to compare two strings.

Ways of String Comparison:

1. By == operator.
2. By equals() method.
3. By compareTo() method.

1. By == operator:

== operator compares the references of the string objects not the actual content of the string objects. It returns true if reference of the compared strings are equal, otherwise returns false.

Example:

StringComparisonExample1.java

/**
 * This program is used to show the use of == operator.
 * @author codesjava.
 */
class TestString{
	String str1 = "codesjava";
	String str2 = "codesjava";
	String str3 = new String("codesjava");
 
	/**
	 * This method is used to compare strings using == operator.
	 * @author codesjava
	 */
	public void stringComparison(){
		//return true, because str1 and str2 both refers to the 
		//same instance created in String constant pool.
		System.out.println(str1 == str2);
 
		//return false, because str3 refers to the 
		// instance created in nonpool.
		System.out.println(str1 == str3);
	}
}
 
public class StringComparisonExample1 {
	public static void main(String args[]){
		//creating TestString object. 
		TestString obj = new TestString();
 
		//method call
		obj.stringComparison();
	}
}

Output:

True
false

Download this example.

2. By equals() method:

equals method compares the actual content of string objects not the references. equals() is an object class method and string class overrides it. String class provides following format of equals() method.

a. public boolean equals(Object obj): Compares the string with the specified object. Returns true if actual content are equal, otherwise returns false.
b. public Boolean equalsIgnoreCase(String str): Compares the actual content of the string with the content of specified string. Returns true if two string’s content are equal ignoring case, otherwise returns false.

Example:

StringComparisonExample2.java

/**
 * This program is used to show the use of equals method.
 * @author codesjava.
 */
class TestString{
	String str1 = "codesjava";
	String str2 = "codesjava";
	String str3 = new String("codesjava");
	String str4 = "jai";
	String str5 = "CODESJAVA";
 
	/**
	 * This method is used to compare strings using equals operator.
	 * @author codesjava
	 */
	public void stringComparison(){
		//return true, because content are same.
		System.out.println(str1.equals(str2));
		System.out.println(str2.equals(str3));
 
		//return false, because content are not same.
		System.out.println(str2.equals(str4));
 
		//return false, because content are not same
                //(differ in case).
		System.out.println(str2.equals(str5));
 
		//return true, because content are same ignoring case.
		System.out.println(str2.equalsIgnoreCase(str5));
	}
}
 
public class StringComparisonExapmle2 {
	public static void main(String args[]){
		//creating TestString object. 
		TestString obj = new TestString();
 
		//method call
		obj.stringComparison();
	}
}

Output:

true
true
false
false
true

Download this example.

3. By compareTo():

compareTo() method compares the two strings lexicographically i.e. character by character. String class provides the following formats of compareTo() method.

  a. public int compareTo(String str)
  b. public int compareToIgnoreCase(String str)

It returns 0 if the argument string is equal to this string, less than 0 if this string is lexicographically less than the string argument and greater than 0 if this string is lexicographically greater than the string argument.

Example:

StringComparisonExample3.java

/**
 * This program is used to show the use of compareTo method.
 * @author codesjava.
 */
class TestString{
	String str1 = "codesjava";
	String str2 = "codesjava";
	String str3 = "jai";
	String str4 = "sandy";
 
	/**
	 * This method is used to compare 
         * strings using compareTo operator.
	 * @author codesjava
	 */
	public void stringComparison(){
		//return 0, because content are same.
		System.out.println(str1.compareTo(str2));
 
		//return greater than 0, because str1 
                //lexicographically greater than str2.
		System.out.println(str1.compareTo(str3));
 
		//return less than 0, because str1 
                //lexicographically less than str2.
		System.out.println(str3.compareTo(str4));
	}
}
 
public class StringComparisonExample3 {
	public static void main(String args[]){
		//creating TestString object.
		TestString obj = new TestString();
 
		//method call
		obj.stringComparison();
	}
}

Output:

0
13
-9

Download this example.
 
Next Topic: String concatenation in java with example.
Previous Topic: String handling in java with example.

Related Topics:

String handling in java with example.
String Comparison in java with example.
String concatenation in java with example.
Substring in java with example.
How to write Immutable class in java with example.
toString() method in java with example.
Commonly used methods of String Class with example.
charAt(int index) String function in java with example.
startsWith(String prefix) and endsWith(String suffix) String functions in java.
indexOf(String str) and lastIndexOf(String str) String functions in java.
toLowerCase() and toUpperCase() String functions in java.
intern() String functions in java with example.
length() String functions in java with example.
trim() String functions in java with example.

 

Posted in Java   

Core Java Tutorial

Programming language overview.
Overview of Java.
Java features
JVM architecture details.
JVM, JRE and JDK.
Java Coding Guidelines.
Some important definitions.
Variable and data types.
Hello world java program.
Core java examples programs.
Important Java Programs.
How to set permanent path in java?
OOPs Basics.
Object and Class in Java.
OOPs Principles/Concepts.
Abstraction in java.
Encapsulation in java.
Polymorphism in java.
Method overloading in java.
Method overriding in java.
Dynamic method dispatch.
Runtime polymorphism.
Association in java.
Inheritance in java.
Aggregation in java.
Command line arguments in java.
Command line argument program in eclipse.
Read input from command line using Scanner.
Java array programs
Java star pattern programs
Java number pattern programs
final in java.
Abstract class in java.
Interface in java.
Custom marker Interface in java.
Constructor in java.
Package in java.
Access modifier in java.
Static import in java.
Package class in java.
this in java.
Instance initialize block.
Anonymous block.
super in java.
Static in java.
final in java.
Java cloning deep and shallow
Shallow vs Clone copy
String handling in java.
String handling programs.
StringBuffer in java.
StringBuilder in java.
Exception Handling Tutorial.
Multithreading Tutoial.
Java input output stream tutorial.
Collections framework in java tutorial.
Collections framework programs.
Java Random class
Java annotations.
Java design principles.
Java 7 features
Java 8 features
Java networking tutorial
Java Reflection tutorial


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap