Topics Index

Pass By Value - Java Example Program

Pass By Value
class PassByValue
    public static void main(String s[])
        int i = 5;
        System.out.println("i before increment : " + i);
        System.out.println("i after increment : " + i);
    public static void increment(int i)
        System.out.println("i before increment in method : " + i);
        System.out.println("i after increment in method : " + i);

i before increment : 5
i before increment in method : 5
i after increment in method : 6
i after increment : 5


In this program we have defined a increment method and calling it from the main method. increment is the called method, where as the main is the calling method. Here we passed the parameter i using pass by value method. As we can see here the value of i is not changed in the main method. The value which is incremented to 6 in the method increment is not reflected in the calling method main. So, any changes done in the called method are not reflected in the calling method.

  • Change the return type of increment method from void to int and return the incremented value. In the main method, change the code increment(i); to i = increment(i);. Observe that the value incremented in the called method is now reflected in the calling method main.

© meritcampus 2019

All Rights Reserved.

Open In App