In Java, the int
data type is a primitive data type that represents a 32-bit signed two’s complement integer. It has a minimum value of -2147483648
and a maximum value of 2147483647
.
The byte
, short
, and long
data types are also integers, but they are stored in fewer bits and have a smaller range of values. The byte
data type is a 8-bit signed two’s complement integer with a minimum value of -128 and a maximum value of 127. The short
data type is a 16-bit signed two’s complement integer with a minimum value of -32768 and a maximum value of 32767. The long
data type is a 64-bit signed two’s complement integer with a minimum value of -9223372036854775808
and a maximum value of 9223372036854775807
.
In addition to the primitive integer data types, Java also has an Integer
class that represents an integer object. This class provides a number of methods for working with integers, such as converting an integer to a string or vice versa.
It’s important to note that the int
data type is primarily used for working with integers in a performance-critical context. In situations where an object-oriented approach is desired or where the range of values is larger than the maximum value of an int
, the Integer
class should be used instead.
Following is an example of using the int
data type in a Java program:
public class Main {
public static void main(String[] args) {
int x = 10;
int y = 20;
int sum = x + y;
System.out.println("The sum of x and y is: " + sum);
}
}
Similarly the example of using the Integer
class is given below:
public class Main {
public static void main(String[] args) {
Integer x = 10;
Integer y = 20;
Integer sum = x + y;
System.out.println("The sum of x and y is: " + sum.toString());
}
}