Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "Primitive values do not share state with other primitive values" mean?

Tags:

java

Section 4.2 of the Java Language Specification states that, "Primitive values do not share state with other primitive values". What exactly does this mean?

like image 898
Ryan Avatar asked May 08 '14 02:05

Ryan


People also ask

What does primitive value mean?

In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods or properties. There are 7 primitive data types: string. number. bigint.

What is the difference between a primitive value and a reference value?

Primitive values are data that are stored on the stack. Primitive value is stored directly in the location that the variable accesses. Reference values are objects that are stored in the heap. Reference value stored in the variable location is a pointer to a location in memory where the object is stored.

What is the difference between primitive and reference?

Variables in Java are classified into primitive and reference variables. From the programmer's perspective, a primitive variable's information is stored as the value of that variable, whereas a reference variable holds a reference to information related to that variable.


2 Answers

This means that each value of primitive type occupies its own space in memory, representing a state which cannot be shared with other values. In other words, you cannot change the state of a variable or a field of a primitive type in any way other than assigning it, directly or through a compound assignment operator.

This is in contrast with reference types, which may or may not share state by "pointing" to the same object. You can change a reference object by manipulating it through a different variable.

like image 97
Sergey Kalinichenko Avatar answered Sep 20 '22 10:09

Sergey Kalinichenko


I suspect it's drawing a distinction between primitives and reference types - where in the latter case, two values (references) can both refer to the same object. If you have two primitive variables, there is nothing you can do to one that would affect the other.

It's not terribly clearly worded though, as even with reference types the values themselves (the references) don't share state; in particular, changing the value of one reference type variable doesn't change the value of another variable... it's the state of the object itself which is sort of shared "via" variables with the same value.

like image 44
Jon Skeet Avatar answered Sep 21 '22 10:09

Jon Skeet