1

To my best knowledge Java uses pass by value. but if you look below I passed a list and added a Integer to it.

Desired output : list before [] and after should be []
Resultant output : list before [] and after is [20]

Also,

if I initialize the list inside static function that my desired output is achieved .

Can i know the reason for this phenomenon please

import java.util.ArrayList;
import java.util.List;

public class NormalTest {

    public static void testMethod(Integer testInt, List<Integer> sampleList) {
        testInt *= 2;
        System.out.println(" Inside testInt :: " + testInt);
        sampleList.add(testInt);
    }

    public static void main(String[] args) {
        Integer testInt = 10;
        List<Integer> sampleList = new ArrayList<>();
        System.out.println(" Before testInt :: " + testInt);
        System.out.println(" Before sampleList :: " + sampleList);
        NormalTest.testMethod(testInt, sampleList);
        System.out.println(" After testInt :: " + testInt);
        System.out.println(" After sampleList :: " + sampleList);
    }
}
khelwood
  • 55,782
  • 14
  • 81
  • 108

1 Answers1

0

You added 20 to the sampleList which is an arraylist. In Java, objects are passed by reference. Only primitive data types like int are passed by value.

The result you are getting is correct

Mohan
  • 334
  • 2
  • 12