Overclock.net banner

1 - 4 of 4 Posts

·
Registered
Joined
·
327 Posts
Discussion Starter · #1 ·
Code:

Code:
public class Test {

    String instVar;
    static String statVar = "A";

    Test() {
        System.out.println("test: " + instVar + statVar);
        instVar = "B";
        statVar = "C";
    }

    public static void main(String[] args) {
        Test t1 = new Test();
        t1.instVar = "D";
        t1.statVar = "E";
        Test t2 = new Test();
        System.out.println("inst: " + t1.instVar + t2.instVar);
        System.out.println("stat: " + t1.statVar + t2.statVar);

    }
}
what i'm confused about is the output from these lines:

Code:

Code:
Test t2 = new Test();
System.out.println("stat: " + t1.statVar + t2.statVar);
someone care to explain?
biggrin.gif
 

·
Registered
Joined
·
172 Posts
The object Test has been instantiated 2 times. In the first instance, values for instVar and statVar were manually assigned.

For the second instance (variable t2), no manual values were assigned, hence the default values were used based on the constructor. Which would be B and C. The manually assigned values are D and E.
 

·
Registered
Joined
·
327 Posts
Discussion Starter · #3 ·
That's what I though too kind of. But the complier got nullE for test t2 which confused me like crazy
 

·
Registered
Joined
·
172 Posts
Its natural that it would do that. In your constructor, you are printing the value of instVar before you actually assign a value to it. So the value for instVar at the time of printing is null. Which is expected based on your code.
 
1 - 4 of 4 Posts
Top