Question : Is Java Pass By Value or Pass By Reference? This was the question asked in one of the interview.
Answer : In most of the Java books it is given that Java is pass by value. So I told this answer. But interviewer gave me an example of arraylist. Where we pass an arraylist to function() and in this function we remove an element and same is reflected back on original array. This means Java also supports pass by reference. I was confused so asking this Question to all of you.
Example of ArrayList :
public static void functionToRemoveAnElement(List<String>strs){
strs.remove(0);
}
public static void main(String args[]) {
List<String> strs = new ArrayList<String>();
strs.add("nishant1");
strs.add("nishant2");
strs.add("nishant3");
strs.add("nishant4");
strs.add("nishant5");
strs.add("nishant6");
strs.add("nishant7");
for(String str : strs){
System.out.println("Before Calling Function : "+str);
//here it will print all the values
}
functionToRemoveAnElement(strs);
for(String str : strs){
System.out.println("After Calling Function : "+str);
//here it will not print nishant1 after calling function()
}
}
This is O/P for those who are saying the values will not change:
Before Calling Function : nishant1
Before Calling Function : nishant2
Before Calling Function : nishant3
Before Calling Function : nishant4
Before Calling Function : nishant5
Before Calling Function : nishant6
Before Calling Function : nishant7
After Calling Function : nishant2
After Calling Function : nishant3
After Calling Function : nishant4
After Calling Function : nishant5
After Calling Function : nishant6
After Calling Function : nishant7
We can see that nishant1 is not present after the call as we are removing 1st element.