Search code examples
javaprimitive

How are primitive types represented in the system? (Integer.toString(int) as example)


Objects are fairly easy to understand in Java. The object is constructed, is allocated space in the heap, and you assign it to a variable name (reference) that points to it. No big deal. But how are primitive types represented? And where are they located (stack or heap)?

I thought of this question when I was wondering what the Integer.toString(int) method might look like. It can't parse the text because... it's not text. It can't invoke a toString() method explicitly or implicitly, because that would be both circular logic and a flagrant disregard for the fact that primitive types can't have methods assigned to them (since they aren't objects). I suppose it is logically possible for the method to have tons of if/else conditionals for all possible int values between Integer.MIN_VALUE and Integer.MAX_VALUE, but that also seems much more complicated than it should be.

So how does this work?


Solution

  • But how are primitive types represented?

    Instances of primitive types are represented as bit patterns in memory. So for example, an int is represented as 32 bits (4 bytes, 1 32-bit word).

    And where are they located (stack or heap)?

    Either. It depends on what kind of variable you hold the primitive value in.

    I was wondering what the Integer.toString(int) method might look like.

    The core of the method is a simple algorithm is a loop that repeatedly

    1. takes the last decimal digit by taking the number remainder 10, and
    2. divides the number by 10.

    Just like you would do if you were converting a binary number to decimal by hand.

    (For details, look at the source code. Every Sun / Oracle JDK includes the source code for the core libraries. Alternatively you can easily find the source code (in various versions) on the internet with a Google search.)