-4

I know Java is always passing by value. However in the following code

public class Test{

String str = new String("good");
char[] ch = {'a','b','c'};
int i = 10;
public void change(String str,char ch,int i){

    str = "test ok";
    ch = 'g';
    this.i = i+1;    
}

public static void main(String[] args){

    Test tt = new Test();
    tt.change(tt.str,tt.ch[0],tt.i);
    System.out.println(tt.i);
    System.out.print(tt.str+" and ");
    System.out.println(tt.ch);     
}

}

The output of tt.i is 11. What is the "this " mean? Why it could change the value of i?

  • 1
    You have two variable 'i', the one created outside the method, and another one which is a parameter.. The keyword this will be used to call the one create outside the method. Without this it would have called the parameter. – Loïc Jan 12 '16 at 19:33
  • 1
    `i` is a class variable and you are adding 1 to it in the method. What are you expecting it to do? – WalterM Jan 12 '16 at 19:34
  • 4
    Using meaningful variable names is a *great* way to avoid this confusion. – David Jan 12 '16 at 19:34
  • so can I include as, primary value is passing by value but object is passing by reference – Zishuo Yang Jan 12 '16 at 19:38
  • @ZishuoYang The only way to understand what Java is actually doing is to get that Java is pass-by-value, but _Object references are passed by value_ and that that's different from pass-by-reference. – Louis Wasserman Jan 12 '16 at 19:41
  • @LouisWasserman I got it! the object is passing by the memory value! is that correct? – Zishuo Yang Jan 12 '16 at 20:41
  • Possible duplicate of [Is Java "pass-by-reference" or "pass-by-value"?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – Wayne Werner Jan 12 '16 at 21:29

1 Answers1

1

Because you changed the value of i to be 11. The meaning of "this" is a reference to the class instance of the class Test that you instantiated when you called new Test()

hofan41
  • 1,408
  • 11
  • 25