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 to 2,147,483,647 (-2^31 to 2^31 - 1).

  • Default Value: The default value of int is 0.

  • Wrapper Class: The wrapper class for int is Integer, located in java.lang.

Characteristics of int

  1. Signed Integer Representation: The int type is signed, allowing both positive and negative values.

  2. Memory Usage: It consumes 32 bits (4 bytes) of memory, which provides a large range of integer values.

  3. Most Common Type: int is the default data type for integers in Java and is widely used in loops, counters, and mathematical operations.

  4. Promotion in Expressions: In expressions involving int and other numeric types, Java promotes the int to larger types (like long or double) as needed. Example:

    int a = 5;
    double result = a / 2.0; // Promoted to double
  5. Performance: int is typically faster than larger data types like long or double for most applications, and is especially preferred when performance is critical and values are within the range of int.

  6. 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 on int values are performed using the JVM's native integer arithmetic instructions.

Operations with 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) 123456789L123456789

Common Mistakes

  1. Integer Overflow: If an operation exceeds the range of an int, it can lead to overflow or underflow:

  2. Implicit Type Conversion: When performing operations involving int and other types, Java promotes the int to a larger data type (like long or double):

Examples

Basic Example

Using int in Arrays

Converting int to String

Using int in Streams

Bitwise Operations with int

Using int with Collections (Boxed Integer)

Last updated