Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

compareTo()

Example

Analyze two strings for equality.

String myStr1 = "Hello";
String myStr2 = "Hello";
System.out.println(myStr1.compareTo(myStr2)); // Returns 0 because they are equal

Definition and Usage

The compareTo() method performs a lexicographical comparison of two strings, relying on the Unicode values of their respective characters.

The method yields 0 when the string equals the other string. It returns a value less than 0 if the string is shorter than the other string and a value greater than 0 if the string is longer than the other string.

Tip: Consider employing compareToIgnoreCase() to compare two strings lexicographically while disregarding differences in case

Tip: Utilize the equals() method to compare two strings without taking Unicode values into consideration.

Syntax

one of the next:

public int compareTo(String string2) 
public int compareTo(Object object)

Parameter Values

Parameter

Description

string2

A string representing the other string for comparison.

object

An object representing another object to compare.

Technical Details

Returns:

An integer value: 0 indicates equality between the string and the other string. A value less than 0 indicates the string is lexicographically before the other string. A value greater than 0 indicates the string is lexicographically after the other string (having more characters).