StringBuilder compareTo() in Java

compareTo(): This method is available in java.lang.StringBuilder class of Java.

Syntax:

int java.lang.StringBuilder.compareTo(StringBuilder another)

This method takes one argument of type StringBuilder as its parameter. This method compares two StringBuilder instances lexicographically.

Parameters: One parameter is required for this method.

another: the StringBuilder to be compared with.

Returns:

1. The value 0 if this StringBuilder contains the same character sequence as that of the argument StringBuilder.

2. A negative integer if this StringBuilder is lexicographically less than the StringBuilder argument.

3. A positive integer if this StringBuilder is lexicographically greater than the StringBuilder argument.

For Example:

StringBuilder str = new StringBuilder("Hello World")

StringBuilder another = new StringBuilder("Hello")

str.compareTo(another) = > It returns 6.

Approach

Java

public class CompareTo {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        StringBuilder another = new StringBuilder("Hello");
        System.out.println(str.compareTo(another));
    }
}

Output:

6

No comments:

Post a Comment