Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading