Contenido del Curso
Java Extended
Java Extended
Data transfer in Java
How is information transmitted in Java?
You know from the previous course that there are two types of memory - stack and heap. Let's take a look at how data is stored in these two memory areas:
Main
package com.example; public class Main { public static void main(String[] args) { String number = new String("170"); String word = new String("word"); int poolNumber = -4; } }
We have created 3 different variables. Below is a diagram illustrating how and where they will be stored in memory:
Let's go through what you observed in the diagram:
- We see
String
fields in the stack memory that are links to values in the heap memory. This way, we don't access the heap memory directly every time. Instead, we initially access the link in the stack memory, which is faster than accessing the heap memory. You have already encountered links to values when learning about the String Pool topic; - You can see that
int
is not stored in the heap memory; its value is stored directly in the stack memory. This applies to all primitive data types (byte
,short
,int
,long
,float
,double
, andboolean
). Thus, primitive data types are passed in Java by value. However,String
is not a primitive data type, so its value is stored in the heap memory; - A new object is created in the heap memory for each new link. However, if two variables of the same type have the same value, they will reference the same object in the heap memory;
- The Integer Pool is an area in the stack memory where all integer values in the range from
-128
to127
are linked. This optimization is done to improve the performance of number handling in Java, as numbers in this range are commonly used. Remember that the stack memory operates faster than the heap memory, so we get faster responses thanks to the Integer Pool; - The String Pool is an area in the heap memory where identical string values are stored.
Note
It is also noticeable that data is stored in a more structured manner in the stack memory compared to the heap memory. We will learn why this is the case in a separate course.
Conclusion
We can conclude that in Java, data types are passed by value. Objects like String
are also passed by value, but they go through a stage of being passed through a reference.
¡Gracias por tus comentarios!