Tuesday, 19 September 2017

java - Local variable behaviour with list, string, and stringbuffer




I am a newbee.
I have read that the scope of local variables will be within a block (correct me if I am wrong).
Here, the main method's local variables (the lists li and li1, and the StringBuffer y) are behaving like instance variables, and the variables (String y1 and int x) behave like local variables. Why ?



public class Test {

public static void addValues(ArrayList list, StringBuffer sb, int x){
list.add("3");
list.add("4");
list.add("5");

sb.append("String Buffer Appended !");
x=x+10;
}

public static void addValues(ArrayList list, String sb, int x){

list.add("3");
list.add("4");
list.add("5");

sb = sb + "is Appended !";
x=x+10;
}

public static void main(String[] args) {
ArrayList li = new ArrayList<>();

ArrayList li1 = new ArrayList<>();
StringBuffer y=new StringBuffer("ab");
int x=10;
String y1=new String("ab");
li.add("1");
li.add("2");
li1.add("1");
li1.add("2");
System.out.println("b4 : "+li+" , y = "+y+" , y1 = "+y1+" x= "+x);
addValues(li,y,x);

System.out.println("Af : "+li+" , y = "+y+" x= "+x);
addValues(li1,y1,x);
System.out.println("Af : "+li1+" , y1 = "+y1+" x= "+x);
}
}


Output :



b4 : [1, 2] , y = ab , y1 = ab x= 10

Af : [1, 2, 3, 4, 5] , y = abString Buffer Appended ! x= 10
Af : [1, 2, 3, 4, 5] , y1 = ab x= 10

Answer



In the case of the ArrayList and StringBuffer, you are passing a reference to an mutable object which reflects any modification on any variable that holds the same reference.



In the case of the String you are too passing a reference BUT its immutable so when you concatenate something to it, its actually creating a new String object and assigning a new reference to the variable within the method, you are not actually modifying the object itself.



And in the case of the int, all primitives are assigned and passed by value, so its actually making a copy of its value and passing it to the method, so anything you do to the variable within the method doesnt affect the variable outside of it.


No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...