Java examples for Language Basics:int
Use the comparison operators to compare integer values.
int int1 = 1; int int2 = 10; int int3 = -5; System.out.println(int1 == int2); // Result: false System.out.println(int3 == int1); // Result: false System.out.println(int1 == int1); // Result: true System.out.println(int1 > int3); // Result: true System.out.println(int2 < int3); // Result: false
The Java language has the following comparison operators.
Operator | Function |
---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
Use the Integer.compare(int,int) method to compare two int values.
System.out.println("Compare method -> int3 and int1: " + Integer.compare(int3, int1)); // Result -1 System.out.println("Compare method -> int2 and int1: " + Integer.compare(int2, int1)); // Result 1
This static method accepts two int values and compares them, returning
public class Main { //from w ww. j a va 2 s. c o m public static void main(String[] args){ int int1 = 1; int int2 = 10; int int3 = -5; System.out.println(int1 == int2); System.out.println(int3 == int1); System.out.println(int1 == int1); System.out.println(int1 > int3); System.out.println(int2 < int3); System.out.println("Compare method -> int3 and int1: " + Integer.compare(int3, int1)); System.out.println("Compare method -> int2 and int1: " + Integer.compare(int2, int1)); } }