In Java, primitive variables and object variables exhibit different levels of isolation due to their inherent characteristics:
Primitive Variables:
- Value Storage: Primitive variables store actual values directly. For example, an
intvariable holds an integer value. - Isolation: When you pass a primitive variable to a method, a copy of the value is made. Any changes made to the parameter inside the method do not affect the original variable outside the method. This is known as "passing by value."
- Default Values: If a primitive variable is not initialized, it gets a default value (e.g.,
0forint,falseforboolean).
Object Variables:
- Reference Storage: Object variables store references (or pointers) to objects in memory, not the actual object itself. For example, a
Stringvariable holds a reference to aStringobject. - Less Isolation: When you pass an object variable to a method, you pass the reference to the object. Any modifications made to the object through the reference inside the method will affect the original object outside the method. This is known as "passing by reference."
- Default Value: If an object variable is not initialized, it defaults to
null, indicating that it does not reference any object.
Example:
public class IsolationExample {
public static void main(String[] args) {
// Primitive variable
int primitiveVar = 10;
modifyPrimitive(primitiveVar);
System.out.println("After modifyPrimitive: " + primitiveVar); // Output: 10
// Object variable
StringBuilder objectVar = new StringBuilder("Hello");
modifyObject(objectVar);
System.out.println("After modifyObject: " + objectVar); // Output: Hello World
}
public static void modifyPrimitive(int value) {
value = 20; // This change does not affect the original variable
}
public static void modifyObject(StringBuilder str) {
str.append(" World"); // This change affects the original object
}
}
In this example:
- The
modifyPrimitivemethod does not change the originalprimitiveVarbecause it operates on a copy of the value. - The
modifyObjectmethod modifies theobjectVarbecause it operates on the reference to the originalStringBuilderobject.
