Primitive Types — easy but not so easy
This is my 1st blog and it starts with Core Java concepts. So are you guys excited? If yes, keep reading along and do send me your feedback, comments, which will help me to grow and motivate me to write more. If you find any content irrelevant or incorrect, let me know, I will be very much happy to update it.
Thank you guys and let us get started.
As you all know, Java is a statically typed language where each variable type or expression type is already known at the compile time. Once a variable is declared to be a certain type, it cannot hold the value of any other data type.
In Java, we have the following primitive data types (Note- Keep in mind the size of each data type as we are going to discuss later on in the post)
- boolean (Size:1 bit)
- byte (Size:8 bits)
- char (Size:16 bits)
- short (Size:16 bits)
- int (Size:32 bits)
- long (Size:64 bits)
- float (Size:32 bits)
- double (Size:64 bits)
Now, you are aware of all data types, let us look at the code below and try to analyze it.
Before analyzing the above code, let me create some background.
For each thread, JVM creates a separate stack at the time of thread creation. In our above example, it is the main thread. Whenever a thread starts executing a method, it first creates a stack frame entry into the newly created stack.
A stack frame consists of local variables, parameters of the method, intermediate computations, etc. Don’t be afraid!!! There will be a separate post on the stack frame.
To get a grip on a stack, let us generate the byte code of the above program by using the following command.
- javap -s -c ThePrimitiveDataType
You will see a lot of byte code being generated but our main focus will be on this one.
The 1st instruction of add method is byte a = 10 and its corresponding byte code is bipush 10.
Bipush means pushing a byte on a stack as an integer value. But why as an integer value? THINK THINK THINK!!!!!
If you see the size of each block on a stack, it is 32 bits on the 32-bit operating system and 64 bits on the 64-bit operating system. Since it is not possible to allocate only 8 bits out of 32, the value of the byte a = 8 is expanded so as to occupy the whole 32 bits of a block. The same instruction is used for all data types having size <=32.
In the case of data types having size> 32 (long, double), another byte code is used — ldc2_w, which pushes the value on to the stack and it occupies 2 blocks each of size 32 bits.
Following is the table which maps java primitive types to JVM types
Don’t worry about the other byte codes generated by the program. There will be a separate blog for this.
That's all from this topic. I hope you guys liked it.
Thank You.