int
About
Definition:
int
is one of the most commonly used primitive data types in Java, representing a 32-bit signed integer. It is used for handling general integer values in both mathematical computations and for data storage.Size: Occupies 4 bytes (32 bits) in memory.
Value Range:
-2,147,483,648
to2,147,483,647
(-2^31
to2^31 - 1
).Default Value: The default value of
int
is0
.Wrapper Class: The wrapper class for
int
isInteger
, located injava.lang
.
Characteristics of int
int
Signed Integer Representation: The
int
type is signed, allowing both positive and negative values.Memory Usage: It consumes 32 bits (4 bytes) of memory, which provides a large range of integer values.
Most Common Type:
int
is the default data type for integers in Java and is widely used in loops, counters, and mathematical operations.Promotion in Expressions: In expressions involving
int
and other numeric types, Java promotes theint
to larger types (likelong
ordouble
) as needed. Example:Performance:
int
is typically faster than larger data types likelong
ordouble
for most applications, and is especially preferred when performance is critical and values are within the range ofint
.Interoperability: It is often used in APIs, databases, and frameworks as the default integer type due to its wide range and performance efficiency.
Memory and Implementation Details
Memory Usage: Each
int
occupies 4 bytes of memory (32 bits). This allows for the representation of a wide range of integer values.Bytecode Representation: The
int
type in Java is efficiently represented in the JVM as a 32-bit integer. All operations onint
values are performed using the JVM's native integer arithmetic instructions.
Operations with int
int
Arithmetic and Logical Operations
Operation
Example
Description
Arithmetic Operations
int sum = a + b;
Addition, subtraction, multiplication, division.
Comparison Operations
a == b
, a > b
, etc.
Compares two int
values.
Bitwise Operations
a & b
, `a
b`, etc.
Conversion Methods
Conversion
Method
Example
int
to String
String.valueOf(int)
String.valueOf(123)
→ "123"
String
to int
Integer.parseInt(String)
Integer.parseInt("123")
→ 123
int
to long
Implicit conversion
long l = 123L
long
to int
Explicit cast (int)
(int) 123456789L
→ 123456789
Common Mistakes
Integer Overflow: If an operation exceeds the range of an
int
, it can lead to overflow or underflow:Implicit Type Conversion: When performing operations involving
int
and other types, Java promotes theint
to a larger data type (likelong
ordouble
):
Examples
Basic Example
Using int
in Arrays
int
in ArraysConverting int
to String
int
to String
Using int
in Streams
int
in StreamsBitwise Operations with int
int
Using int
with Collections (Boxed Integer
)
int
with Collections (Boxed Integer
)Last updated
Was this helpful?