How to Compare Two Java String


Through this example, we may simply learn how to compare a String with another String object in Java.

Source Code

String
package com.beginner.examples;

public class StringCompare {

	public static void main(String[] args) {
		
		String string1  = "Hello World !";
		String string2  = "hello world !";
		
		/*
		 * To compare two Java String ues the method compareTo(String anotherString).
		 * This method returns negative int if first string is less than another,
		 * returns positive int if first string is grater than another,
		 * returns 0 if both strings are same.
		 */
		System.out.println(string1.compareTo(string2));
		
		/*
		 * To compare two Java String ues the method compareToIgnoreCase(String anotherString).
		 * Thid method compares two strings ignoring the character case of the given String.
		 */
		System.out.println(string1.compareToIgnoreCase(string2));
	}

}

Output:

-32
0
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments