In Java, primitive data types such as int
, float
, and boolean
are stored in memory as raw bits and bytes, rather than as objects. When you declare a variable of a primitive data type in Java, the Java Virtual Machine (JVM) allocates a fixed amount of memory for the variable based on the size of the data type.
For example, an int
variable in Java occupies 4 bytes of memory, a float
variable occupies 4 bytes, and a boolean
variable occupies 1 byte. The JVM uses these sizes to determine how much memory to allocate for each primitive data type variable.
When you use a primitive data type variable in your code, the JVM accesses the memory location where the variable is stored and retrieves or modifies the value stored there. This is done using low-level memory access instructions that are specific to the hardware and operating system on which the JVM is running.
In contrast, objects in Java are stored in a separate area of memory called the heap, and are accessed using references rather than directly by their memory address. When you declare a variable of an object type, the JVM allocates a reference to an object on the heap rather than the object itself. The reference contains the memory address of the object, and can be used to access the object's fields and methods.
In summary, Java knows where it has stored primitive data types by allocating a fixed amount of memory for each variable and accessing the memory location directly using low-level memory access instructions. Objects, on the other hand, are stored in a separate area of memory and accessed using references.