Java Integer Compare Method

JavaJavaBeginner
Practice Now

Introduction

In Java, Integer is a wrapper class that encapsulates a primitive data type int. Integer class provides various useful methods to perform operations on integer values. One of the methods is compare() which is used to compare two int values.

Define main method

In the IntegerCompareMethod.java file, define the main() method, which is the entry point to the Java program.

public static void main(String[] args) {
    // code goes here
}

Call compare() method

In the main() method, call the compare() method with two int values as parameters. Store the result in a variable named result.

int val1 = 5;
int val2 = 10;
int result = Integer.compare(val1, val2);

Print the result

Print the value of the result variable using the System.out.println() method.

System.out.println("The result is: " + result);

Test the comparison

Test the comparison by running the code. The output should be -1 because val1 is less than val2.

javac IntegerCompareMethod.java && java IntegerCompareMethod

Compare equal values

In the main() method, create two int variables with the same value. Call the compare() method with these two variables as parameters and store the result in a variable named result.

int val3 = 5;
int val4 = 5;
int result = Integer.compare(val3, val4);

Print the result of the comparison

Print the value of the result variable using the System.out.println() method.

System.out.println("The result is: " + result);

Test the comparison

Test the comparison by running the code. The output should be 0 because val3 is equal to val4.

javac IntegerCompareMethod.java && java IntegerCompareMethod

Compare greater value

In the main() method, create two int variables where val5 is greater than val6. Call the compare() method with these two variables as parameters and store the result in a variable named result.

int val5 = 10;
int val6 = 5;
int result = Integer.compare(val5, val6);

Print the result of the comparison

Print the value of the result variable using the System.out.println() method.

System.out.println("The result is: " + result);

Test the comparison

Test the comparison by running the code. The output should be 1 because val5 is greater than val6.

javac IntegerCompareMethod.java && java IntegerCompareMethod

Summary

In this lab, you have learned how to use the compare() method in the Integer class of Java. You also learned the syntax, parameters, and returns of the method. By following the step-by-step guide, you were able to create a functional program that compares two int values using the compare() method.

Other Java Tutorials you may like