In Java, an int is used to store whole numbers (numbers without decimals).
An int:
- Has a fixed size of 32 bits (4 bytes) in memory
- Can store values from -2,147,483,648 to 2,147,483,647
Examples
int count = 19;
int score = -5;
int temperature = 0;
Integer types in Java
Java has four integer primitive types:
byte(1 byte)short(2 bytes)int(4 bytes)long(8 bytes)
Why is int used most often?
int is the default choice for whole numbers because:
- Its range is large enough for most programmes
- It uses a reasonable amount of memory (4 bytes)
- It is fast and efficient for Central Processing Units (CPUs) to process
Primitive type
int is a primitive data type. Primitive types are simple, fast, and memory‑efficient.
This means:
- It stores its actual value directly in memory
- It does not store a reference to an object
- It has no methods of its own
If you change the value of a long variable, the old value is replaced by the new:
int a = 15; // 'a' is 15
a = 20; // Now 'a' is replaced by 20
The Integer wrapper class
Although int itself has no methods, Java provides a wrapper class called Integer.
The Integer class:
- Wraps an
intvalue inside an object - Provides useful constants and methods
Integer methods
Useful Integer constants
| Constant | Example | Result |
| MAX_VALUE | Integer.MAX_VALUE | Returns largest possible long value (2147483647) |
| MIN_VALUE | Integer.MIN_VALUE | Returns Smallest positive long value (-2147483648) |
| SIZE | Integer.SIZE | Returns size of a long in bits (32) |
| BYTES | Integer.BYTES | Returns size of a long in bytes (4) |
Converting values
Converting numeric String to Integer. If the String is not numeric (e.g. "hello"), Java throws aNumberFormatException.
int num = Integer.parseInt("12345"); // Returns 12345
Converting an int to a String
String text = Integer.toString(12345); // Returns "12345"
Comparing Integer values
compare(int a, int b)
int result = Integer.compare(12, 23);
compareTo(Integer other)
Integer x = 12; // has to be Integer. int will generate an error
Integer y = 23;
x.compareTo(y);
Both compare and compareTo return these values:
0→ if values are equal-1→ if first is less than second1→ first is greater than second
equals(Object obj)
Integer x = 12; // has to be Integer. int will generate an error
Integer y = 15;
x.equals(y); // true
Math helper methods
| Method | Example | Result |
| max(int a, int b) | Integer.max(12, 15) | Returns the larger value |
| min(int a, int b) | Integer.min(12, 15) | Returns the smaller value |
| sum(int a, int b) | Integer.sum(12, 15) | Returns the sum of the two values |
Summary
intstores whole numbers- It is a 32‑bit primitive type
- It is fast, memory‑efficient, and widely used
- It has no methods, but the
Integerwrapper provides many utilities
Leave a Reply