Does the variable take place in the heap during the declaration? In other words, if I want to declare a variable, will this affect the amount of memory used?
2 answers
Yes, it will affect, but only slightly, but if the variables are many, the increase in the amount of memory used will be large (for modern PCs it is still uncritical).
Memory for a variable is allocated only if you use it in code. (compiler merit)
Depending on the type, variables may occupy different amounts of memory. The smallest byte - Occupies one byte of memory, and the most "Volumetric" type double - 8 bytes. String - depending on how many characters are in a string. Here you can see the entire list of primitives. The more primitives in a class, the more the class object will weigh.
Specifically, only objects are added to the heap, variables are placed on the stack.
- Thank you so much to both commentators! - Max
- oneYou obviously have very superficial ideas about the organization of memory. It looks like you are confusing variables with fields. The size of the object is affected by the fields of not only primitive, but also reference types. A variable of type String always has one size — the size of the link. The number of characters in a string can only affect the size of the array in which the String object stores characters. - Hivemaster
Objects in a heap. Variables take up space on the stack. But if you declare a variable and never use it, the compiler will throw it out altogether. For example, this code
public class Example { public static void main(String[] args) { int a; int b = 2; } } It will be compiled into such a class file (for brevity, I only show the main method):
public static void main(java.lang.String[]); descriptor: ([Ljava/lang/String;)V flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=3, args_size=1 0: iconst_2 1: istore_2 2: return LineNumberTable: line 53: 0 line 54: 2 LocalVariableTable: Start Length Slot Name Signature 0 3 0 args [Ljava/lang/String; 2 1 2 b I As you can see, there is not even a mention of the variable a .