This article demonstrates an Example of Reference Variables in Java.

Problem Statement

Build a Java application to create a class called Test and pass its object to one of its methods to illustrate the usage of reference variables.

Solution

class Test {
    int value;

    // A method that takes an object of the Test class as a parameter
    void modifyValue(Test obj) {
        obj.value = 100;
    }
}

public class ReferenceVariableDemo {
    public static void main(String[] args) {
        // Create an object of the Test class
        Test testObject = new Test();

        // Print the initial value
        System.out.println("Initial value: " + testObject.value);

        // Pass the object to the modifyValue method
        testObject.modifyValue(testObject);

        // Print the modified value
        System.out.println("Modified value: " + testObject.value);
    }
}

In this program:

  1. We define a class called Test with an instance variable value and a method modifyValue that takes an object of the Test class as a parameter and modifies its value field.
  2. In the main method, we create an object testObject of the Test class.
  3. We print the initial value of the value field.
  4. We pass the testObject to the modifyValue method, which modifies the value field of the object.
  5. Finally, we print the modified value of the value field.

When you run this Java program, you’ll see that the object’s reference is passed to the modifyValue method, and any changes made to the object within the method affect the original object. This demonstrates the usage of reference variables in Java.



Further Reading

Spring Framework Practice Problems and Their Solutions

From Google to the World: The Story of Go Programming Language

Why Go? Understanding the Advantages of this Emerging Language

Creating and Executing Simple Programs in Go

20+ Interview Questions on Go Programming Language

Java Practice Exercise

programmingempire

Princites