- Please go through this tutorial to understand the basic concept
- List returned by Arrays.asList(): it is documented not to support any removing or adding elements.
- If we update a list from a method X by calling another void method Y, list modification will be affected in the list object in the method X.
- Because the the same object memory is used when passing the reference. So java is Pass by value.
public class MemoryTest {
public static void main(String[] args) {
MemoryTest mt = new MemoryTest();
mt.scopeTest();
}
private void scopeTest() {
int numberInt = 2;
Integer numberInteger = 10;
List numberList = new ArrayList();
numberList.add(10);
numberList.add(20);
Student student = new Student();
student.setId(1);
student.setName("Sonu");
MemoryTest mt = new MemoryTest();
System.out.println("numberInt before = " + numberInt);
mt.modifyInt(numberInt);
System.out.println("numberInt after = " + numberInt);
System.out.println("numberInteger before = " + numberInteger);
mt.modifyInteger(numberInteger);
System.out.println("numberInteger after = " + numberInteger);
System.out.println("numberList before = " + numberList);
mt.modifyList(numberList);
System.out.println("numberList after = " + numberList);
System.out.println("student before = " + student);
mt.modifyStudent(student);
System.out.println("student after = " + student);
}
private void modifyInt(int i) {
i = 3;
}
private void modifyInteger(Integer i) {
i = 200;
}
private void modifyList(List list) {
list.add(100);
}
private void modifyStudent(Student student) {
student.setId(2);
student.setName("Sreenu");
}
}
Output
numberInt before = 2
numberInt after = 2
numberInteger before = 10
numberInteger after = 10
numberList before = [10, 20]
numberList after = [10, 20, 100]
student before = 1, Sonu
student after = 2, Sreenu
No comments:
Post a Comment