Java is a pass-by-value or pass-by-reference explained with an example.

By | March 7, 2023

In Java, when you pass an argument to a method, the argument is always passed by value. This means that a copy of the argument is made and passed to the method, rather than a reference to the original argument being passed.

To understand this better, consider the following example:

public class Example {

    public static void main(String[] args) {

        int x = 5;

        System.out.println(“Value of x before method call: ” + x);


        System.out.println(“Value of x after method call: ” + x);


       public static void modifyValue(int y) {

        y = y + 10;

        System.out.println(“Value of y inside method: ” + y);



In this example, we have a main method that initializes an integer variable x to a value of 5. It then calls a method called modifyValue and passes x as an argument. The modifyValue method adds 10 to the value of y (which is a copy of x) and prints the new value of y. Finally, the main method prints the value of x again.

The output of this program is as follows:

Value of x before method call: 5

Value of y inside method: 15

Value of x after method call: 5

As you can see, the value of x remains unchanged after the method call, even though we modified the value of y inside the method. This is because the value of x was passed by value to the modifyValue method, which made a copy of it and worked with that copy instead of the original value.

In summary, Java is a pass-by-value language, which means that arguments are always passed by value and not by reference. This can lead to some confusion in certain cases, but it is an important concept to understand when working with Java programs.

Leave a Reply

Your email address will not be published. Required fields are marked *