0

Why is it like this?

Codes:

public class Class1 {
    Class1 c1
    public Class1() { c1 = null; }
}

public class Class2 {
    public static void main(String[] args) {
        Class1 cs1 = new Class1();
        System.out.println(cs1 == null);
    }
}

In Class1 I initialized the c1 as null in its contructor. Then when I instantiated the Class1 in Class2 then check if its value is really null (cs1 == null) the output it produces is false. Why does it output as false? cs1 is null, hence it's supposed to print as true. Why does this happen? Can someone please explain this to me? Thanks...

1
  • 3
    you you are checking cs1, not cs1.c1. cs1 it not null. Use better variable names. Commented Sep 22, 2020 at 15:45

2 Answers 2

1

You did initialize c1 as null, yes, but c1 is not the Class1 being initialized in the constructor.

new Anything() is never, ever null.

Sign up to request clarification or add additional context in comments.

2 Comments

yeah but c1 is of type Class1 so I thought that it should output as null as well. I'm still a little confused...
@robert: one is a local variable of type Class1 and the other is a field inside Class1 of type Class1. They have basically no relation to each other except that they hold the same type of value (a reference to an object of Class1). There's absolutely no reason why changing one of them should change the other as well.
0

Class1‘s c1 attribute is null, not the instance itself. So, basically you’ve created a wrapper around a null. This should print true:

System.out.println(cs1.c1 == null);

Comments

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.