Question

I was going through primitive data types in java. It mentions that primitive values don't share state with other primitive values.

It makes sense to me but I was wondering if someone could give me an example where a data value actually share state with other data value in java. I could come up with a custom class that have static variables in it.

Naturally, instances of that class will share those static variables, hence some sort of state. But I'm looking for examples specifically showing state sharing in non-primitive data type offered by JAVA.

Was it helpful?

Solution

I think the sharing state here means that non-primitive variables are always references to objects in memory. And those objects are "shared" between those variables.

I.e. you can have this with non-primitive types :

    StringBuilder sb1 = new StringBuilder();
    StringBuilder sb2 = sb1;

    sb1.append("change thru sb1");
    sb2.append(" change thru sb2");

    // will print both modifications, since sb1 & sb2 refer to the same object
    System.out.println(sb1); 

and you can't have this with primitives as they always maintain their own copy of data.

OTHER TIPS

Primitive data types in java doesn't keep references to other objects, for example:

int a = 0;
int b = 1;

b = 2;
//a value is still 0;

Object variables in Java are pointers to objects, so you can share the state of two variables keeping them referencing the same object:

Object a = new Object();
Object b = a;

b.modifySomething();
// a is modified too because they are the same object

I suggest you to read this thread.

I depicts "the problem" of data passing in java.

Is Java "pass-by-reference" or "pass-by-value"?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top