LearnFrenzy
Sign in Take a free test

Classes and Objects · Predict the Output · Question 15

Comparing objects safely when one may be null Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 15 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.Objects;

public class Main {
    public static void main(String[] args) {
        String a = null, b = "x";
        System.out.println(Objects.equals(a, b) + " " + Objects.equals(a, null) + " " + "x".equals(b) + " " + Objects.toString(a, "none") + " " + Objects.hashCode(a));
    }
}
  • A false true true none 0 Correct
  • B false false true null 0
  • C NullPointerException
  • D false true true null -1
Correct Answer: Option A

The java.util.Objects helpers accept null safely: equals, toString with a default, and hashCode (0 for null).

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links