int
About
Definition:
intis 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,648to2,147,483,647(-2^31to2^31 - 1).Default Value: The default value of
intis0.Wrapper Class: The wrapper class for
intisInteger, located injava.lang.
Characteristics of int
intSigned Integer Representation: The
inttype 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:
intis the default data type for integers in Java and is widely used in loops, counters, and mathematical operations.Promotion in Expressions: In expressions involving
intand other numeric types, Java promotes theintto larger types (likelongordouble) as needed. Example:int a = 5; double result = a / 2.0; // Promoted to doublePerformance:
intis typically faster than larger data types likelongordoublefor 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
intoccupies 4 bytes of memory (32 bits). This allows for the representation of a wide range of integer values.Bytecode Representation: The
inttype in Java is efficiently represented in the JVM as a 32-bit integer. All operations onintvalues are performed using the JVM's native integer arithmetic instructions.
Operations with int
intArithmetic 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
intand other types, Java promotes theintto a larger data type (likelongordouble):
Examples
Basic Example
Using int in Arrays
int in ArraysConverting int to String
int to StringUsing int in Streams
int in StreamsBitwise Operations with int
intUsing int with Collections (Boxed Integer)
int with Collections (Boxed Integer)Last updated