-2
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?

2

1 Answer 1

2
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;
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.