⬅ Previous Topic
Java StringcodePointCount()
methodNext Topic ⮕
Java StringcompareToIgnoreCase()
methodcompareTo()
method⬅ Previous Topic
Java StringcodePointCount()
methodNext Topic ⮕
Java StringcompareToIgnoreCase()
methodThe compareTo()
method in Java is a powerful tool for comparing strings. It doesn't just tell you if two strings are the same or different; it tells you *how* they differ based on their lexicographical order (essentially, dictionary order). Think of it like how words are arranged alphabetically - that's what compareTo()
does for your strings.
public int compareTo(String anotherString)
Parameter | Description |
---|---|
anotherString |
The string to compare with the current string. |
The compareTo()
method returns an integer value, which indicates the relationship between the two strings:
anotherString
, it returns a negative integer.anotherString
, it returns a positive integer.This example demonstrates a simple comparison between two strings.
String str1 = "apple";
String str2 = "banana";
int result = str1.compareTo(str2);
System.out.println(result); // Output: -1
-1
Explanation: Since "apple" comes before "banana" alphabetically, str1.compareTo(str2)
returns a negative value (-1).
This example shows what happens when the strings being compared are identical.
String str1 = "orange";
String str2 = "orange";
int result = str1.compareTo(str2);
System.out.println(result); // Output: 0
0
Explanation: Because both strings are exactly the same, compareTo()
returns 0.
This example illustrates a comparison where the first string comes after the second alphabetically.
String str1 = "zebra";
String str2 = "apple";
int result = str1.compareTo(str2);
System.out.println(result); // Output: 1
1
Explanation: "zebra" comes after "apple", so the result is a positive integer (1).
This example highlights that compareTo()
is case-sensitive.
String str1 = "Apple";
String str2 = "apple";
int result = str1.compareTo(str2);
System.out.println(result); // Output: 1
1
Explanation: Because "Apple" (uppercase 'A') has a higher Unicode value than "apple" (lowercase 'a'), compareTo()
considers "Apple" greater and returns a positive value.
This example demonstrates comparing strings that contain numbers. The comparison is based on the string representation, not numerical values.
String str1 = "file10";
String str2 = "file2";
int result = str1.compareTo(str2);
System.out.println(result); // Output: 1
1
Explanation: The comparison is done lexicographically, treating the strings as text. "file10" comes after "file2" because '1' comes after '2' when compared as characters.
⬅ Previous Topic
Java StringcodePointCount()
methodNext Topic ⮕
Java StringcompareToIgnoreCase()
methodYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.