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<String> 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<String> 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<String> li = new ArrayList<>();
ArrayList<String> 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