How are primitive variables and object variables isolated in Java?

0115

In Java, primitive variables and object variables exhibit different levels of isolation due to their inherent characteristics:

Primitive Variables:

  1. Value Storage: Primitive variables store actual values directly. For example, an int variable holds an integer value.
  2. 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."
  3. Default Values: If a primitive variable is not initialized, it gets a default value (e.g., 0 for int, false for boolean).

Object Variables:

  1. Reference Storage: Object variables store references (or pointers) to objects in memory, not the actual object itself. For example, a String variable holds a reference to a String object.
  2. 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."
  3. 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 modifyPrimitive method does not change the original primitiveVar because it operates on a copy of the value.
  • The modifyObject method modifies the objectVar because it operates on the reference to the original StringBuilder object.

0 Comments

no data
Be the first to share your comment!