Search code examples
javainstancelocal

JAVA instance vs local variable


import comp102x.IO;  
  
public class testing {
  
        private int x;

        public testing(int x) {
  
                x = x;
        }

        public static void main(String[] args) {
  
                testing q1 = new testing(10);
                IO.outputln(q1.x);
        }
}

Why is the output 0 instead of 10? This is a JAVA script. The concept of instance and local variables is very confusing to me, can someone help to explain?


Solution

  • public testing(int x) {      
      x = x;
    }
    

    here you only reassign the value of the local variable x to itself, it doesn't change the instance variable.

    Either change the name of the local variable, like this:

    public testing(int input) {
      x = input;
    }
    

    or make sure you assign the value to the instance variable, like this:

    public testing(int x) {
      this.x = x;
    }