×

Java Integer compareTo() method

The compareTo() method of Integer class compares two Integer objects numerically.

Syntax

public static int compareTo(int anotherInteger)

Parameters

The parameter ‘anotherInteger’ represents the Integer to be compared.

Specified by

This method is specified by compareTo in interface Comparable< Integer >

Return Value

This method returns an integer value.

  • It returns zero, if this Integer is equal to the parameter.
  • It returns positive one, if this Integer is numerically greater than the argument Integer.
  • It returns negative one, if this Integer is numerically smaller than the argument Integer.

Example 1

public class JavaIntegerCompareToExample1 {
    public static void main(String[] args) {
        Integer val1 = 500 ;
        Integer val2 = 127654 ;
        // It compares two Integer objects numerically
        int val = val1.compareTo(val2);
        if(val==0){
            System.out.println("Both are equal");
        }
        else if (val>0) {
            System.out.println(val1 + " is greater than " + val2);
        }
        else{
            System.out.println(val2 + " is greater than " + val1);
        }
    }
}

Output

127654 is greater than 500

Example 2

import java.util.Scanner;
public class JavaIntegerCompareToExample2 {
    public static void main(String[] args) {
        Integer val1 = 18 ;
        Scanner scanner=new Scanner(System.in);
        System.out.print("Enter your age : ");
        Integer val2 = scanner.nextInt();
        // It  compares two Integer objects numerically.
        int val = val1.compareTo(val2);
        if (val<=0){
            System.out.println("Congratulations! You are an adult. You can vote..");
        }
        else{
            int year=18-val2;
            System.out.println("Sorry! You are not an adult. You can vote after "+year+" years.");
        }
    }
}

Output

Enter your age : 70
Congratulations! You are an adult. You can vote..

Example 3

import java.util.Scanner;
public class JavaIntegerCompareToExample3 {
    public static void main(String[] args) {
        Integer val1 = 90 ;
        Scanner scanner=new Scanner(System.in);
        System.out.print("Enter you 12 percentage : ");
        Integer val2 = scanner.nextInt();
        // It  compares two Integer objects numerically.
        int val = val1.compareTo(val2);
        if (val<0){
            System.out.println("Congratulations! You percentage is with the first cut off list.");
        }
        else{
            System.out.println("Sorry! Your percentage is not in the range of first cut off list. wait for the second cut off.");
        }
    }
}

Output

Enter you 12 percentage : 98
Congratulations! You percentage is with the first cut off list.

Related Topics

Java Math floorMod() Method

The floorMod() method of Math class returns the floor modulus of the specified arguments. It firstly divides the dividend and divisor and then returns an integer that is equal to...

1 minute read.

Java Integer doubleValue() method

The doubleValue() method of Integer class returns a double value for this Integer after a widening primitive conversion. Syntax public double doubleValue() Parameters NA Specified by This method is specified by doubleValue in class Number Return Value This...

1 minute read.

Java Math.multiplyExact() method in Java

Java has an inbuilt math function called Math.multiplyExact() that returns the sum of the parameters. If the result exceeds an integer, an exception is thrown. There is no need to...

2 minutes read.

How to stop execution after a certain time in Java

We will learn how to stop a long-running execution after a set amount of time in this post. We will take a look at a few alternative approaches to this...

6 minutes read.

Difference between Static and Instance Methods in Java

Static Method in Java The static technique has a place with the class as opposed to the object of the course. These are intended to be divided between every one of...

10 minutes read.

Finding Odd Occurrence of a Number in Java

In this tutorial, we will learn how to find the odd occurrence of a number through a java program. Let us consider an array of non-negative integers. Here, except for one...

6 minutes read.

Java StringWriter Class

The StringWriter class is a character stream in which it is used to store the output consisting of characters into the string buffer. Upon collecting output into a string buffer,...

3 minutes read.

GCD Program in Java

GCD Program in Java The GCD program in Java outputs the GCD of the given numbers. In mathematics, Greatest Common Divisor (GCD), Greatest Common Factor or Highest Common Factor (HCF) of...

14 minutes read.

How to take Multiple String Input in Java using Scanner class

Scanner class is a class which takes the multiple input data or the single input data through an objects and methods. The Scanner class will be available in the java.util...

3 minutes read.

Difference between print() and println() in Java

In this tutorial, we will discuss the differences between print and println in Java language. There are mainly two methods to display the text on the console printprintln The above two methods are...

4 minutes read.

Java Integer toBinaryString() method

The toBinaryString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 2. Syntax public static String toBinaryString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

Internal Working of ArrayList in Java

Java's version of a resizable array is called ArrayList. The dynamic growth of an array list ensures that there is always room for new elements. ArrayList's backing data structure is...

8 minutes read.

List all files in a Directory in Java

The list of all files in the directory can be done using Java. You should be aware that a directory may include a subfolder and that subdirectory may also contain some...

3 minutes read.

Java Integer rotateLeft() method

The rotateLeft() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value left by the specified number of bits. Syntax public...

1 minute read.

Difference Between Access Specifiers and Modifiers in Java

Java employs access modifiers to restrict a class's data members, member functions, and constructor. Access modifiers are essential when creating Java program and applications. Access modifiers in Java include: defaultpublicprotectedprivate Default Access Modifiers Without...

4 minutes read.

Equilibrium Index of an Array in Java

An array's equilibrium index is the condition where the sum of items with lower and higher indices equals. For example, an array A=[-4,5 2,6,-5] where: a[0]=-4, a[1]=5, a[2]=2, a[3]=6, a[4]=-5 Now according...

4 minutes read.

How to get ASCII value of char in Java

Introduction: On this application, you will learn how to find and show the ASCII value of char in Java. That is done with the use of type-casting and also everyday...

4 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

6 minutes read.

Difference between String Tokenizer and split Method in Java

Introduction Today, let us understand the difference between String Tokenizer and Split Method. First, let us learn about the String Tokenizer and Split method individually and then know about their differences String...

7 minutes read.

String Concatenation in Java

In Java, it gathers a new String that combines several strings. Following are the manners to concatenate strings in Java: By + (String concatenation) operatorBy concat() method By + (String concatenation) operator Java...

4 minutes read.