Home > Blockchain >  JAVA instance vs local variable
JAVA instance vs local variable

Time:12-20

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?

CodePudding user response:

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;
}
  • Related