简体   繁体   中英

Print the object and check null

public void printManagerAvailable(Manager mgr) {
    System.out.println(" Is Manager object available : " + mgr!=null);
}

Output:

true

Why output is only true here? I'm expecting:

Is Manager object available : true

because it thinks that you are saying " Is Manager object available : " + mgr is all to the left of != null . In other words, it does " Is Manager object available : " + mgr first and then it compares " Is Manager object available : [Object:Manager]" != null .

Do this.

Manager mgr = new Manager();
    mgr.setChangeClass(5);
    mgr.setChangeClockIn(10);
    System.out.println(" Is Manager object available : " + (mgr!=null));

Other answers cover what is happening, this is why it is happening:

The order of operator precedence in Java puts addition, + , ahead of equality, != .

It's important to realize that it's not caused by left-to-right ordering here.

So what you have is applying the operators in the order like so:

("Is null : " + mgr) != null

And to fix it you can use brackets to force the precedence the other way:

"Is null : " + (mgr != null)

尝试使用此行代码。

System.out.println(" Is Manager object available : " + (mgr == null ? "is null" : "not null"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM