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

Why using static results in a different output?

I have the following code that prints 20.

import java.util.*;
import java.lang.*;
import java.io.*;

class A {
    public int val = 20; // <- no static
}


class Main {
    public static void main(String[] args) {
        A a = new A();
        updateVal(a);
        
        System.out.println(a.val);
    }
    
    private static void updateVal(A a) {
        a = new A();
        a.val = 50;
    }
}

But if I change val to static then it prints 50. How it works?

import java.util.*;
import java.lang.*;
import java.io.*;

class A {
    public static int val = 20; // <- there is static
}


class Main {
    public static void main(String[] args) {
        A a = new A();
        updateVal(a);
        
        System.out.println(a.val);
    }
    
    private static void updateVal(A a) {
        a = new A();
        a.val = 50;
    }
}

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

>Solution :

If the field is non-static, each instance has its own val field with its own value. Since Java is pass-by-value, not pass-by-reference, the statement a = new A() inside updateVal does not update the val field of the instance that was created in main.

If the field is static, all instances share the same field. The update inside updateVal is now that one shared field.

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