Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Different Ways to Create Objects in Java
Next article icon

Java.util.Objects class in Java

Last Updated : 24 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Java 7 has come up with a new class Objects that have 9 static utility methods for operating on objects. These utilities include null-safe methods for computing the hash code of an object, returning a string for an object, and comparing two objects.

Using Objects class methods, one can smartly handle NullPointerException and can also show customized NullPointerException message(if an Exception occur).

  1. String toString(Object o) : This method returns the result of calling toString() method for a non-null argument and "null" for a null argument.
    Syntax :
    public static String toString(Object o)
    Parameters :
    o - an object
    Returns :
    the result of calling toString() method for a non-null argument and
    "null" for a null argument
  2. String toString(Object o, String nullDefault) : This method is overloaded version of above method. It returns the result of calling toString() method on the first argument if the first argument is not null and returns the second argument otherwise.
    Syntax : 
    public static String toString(Object o, String nullDefault)
    Parameters :
    o - an object
    nullDefault - string to return if the first argument is null
    Returns :
    the result of calling toString() method on the first argument if it is not null and
    the second argument otherwise.
    Java
    // Java program to demonstrate Objects.toString(Object o)  // and Objects.toString(Object o, String nullDefault) methods  import java.util.Objects;  class Pair<K, V>  {     public K key;     public V value;      public Pair(K key, V value)      {         this.key = key;         this.value = value;     }          @Override     public String toString() {         return "Pair {key = " + Objects.toString(key) + ", value = " +                      Objects.toString(value, "no value") + "}";                  /* without Objects.toString(Object o) and           Objects.toString(Object o, String nullDefault) method          return "Pair {key = " + (key == null ? "null" : key.toString()) +       ", value = " + (value == null ? "no value" : value.toString()) + "}"; */     } }  class GFG {     public static void main(String[] args)      {         Pair<String, String> p1 =                          new Pair<String, String>("GFG", "geeksforgeeks.org");         Pair<String, String> p2 = new Pair<String, String>("Code", null);                  System.out.println(p1);         System.out.println(p2);     } } 
    Output:
    Pair {key = GFG, value = geeksforgeeks.org}
    Pair {key = Code, value = no value}
  3. boolean equals(Object a,Object b) : This method true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals() method of the first argument.
    Syntax : 
    public static boolean equals(Object a,Object b)
    Parameters :
    a - an object
    b - an object to be compared with a for equality
    Returns :
    true if the arguments are equal to each other and false otherwise
    Java
    // Java program to demonstrate equals(Object a, Object b) method  import java.util.Objects;  class Pair<K, V>  {     public K key;     public V value;      public Pair(K key, V value)      {         this.key = key;         this.value = value;     }      @Override     public boolean equals(Object o)     {         if (!(o instanceof Pair)) {             return false;         }         Pair<?, ?> p = (Pair<?, ?>) o;         return Objects.equals(p.key, key) && Objects.equals(p.value, value);              } }  class GFG {     public static void main(String[] args)      {         Pair<String, String> p1 =                  new Pair<String, String>("GFG", "geeksforgeeks.org");                  Pair<String, String> p2 =                  new Pair<String, String>("GFG", "geeksforgeeks.org");                  Pair<String, String> p3 =                  new Pair<String, String>("GFG", "www.geeksforgeeks.org");                  System.out.println(p1.equals(p2));         System.out.println(p2.equals(p3));              } } 
    Output:
    true
    false
  4. boolean deepEquals(Object a,Object b) :This method returns true if the arguments are deeply equal to each other and false otherwise. Two null values are deeply equal. If both arguments are arrays, the algorithm in Arrays.deepEquals is used to determine equality. Otherwise, equality is determined by using the equals method of the first argument.
    Syntax : 
    public static boolean deepEquals(Object a,Object b)
    Parameters :
    a - an object
    b - an object to be compared with a for equality
    Returns :
    true if the arguments are deeply equals to each other and false otherwise
  5. T requireNonNull(T obj) : This method checks that the specified object reference is not null. This method is designed primarily for doing parameter validation in methods and constructors, as demonstrated in below example:
    Syntax : 
    public static T requireNonNull(T obj)
    Type Parameters:
    T - the type of the reference
    Parameters :
    obj - the object reference to check for nullity
    Returns :
    obj if not null
    Throws:
    NullPointerException - if obj is null
  6. T requireNonNull(T obj,String message) : This method is overloaded version of above method with customized message printing if obj is null as demonstrated in below example:
    Syntax : 
    public static T requireNonNull(T obj,String message)
    Type Parameters:
    T - the type of the reference
    Parameters :
    obj - the object reference to check for nullity
    message - detail message to be used in the event that a NullPointerException is thrown
    Returns :
    obj if not null
    Throws:
    NullPointerException - if obj is null
    Java
    // Java program to demonstrate Objects.requireNonNull(Object o)  // and Objects.requireNonNull(Object o, String message) methods  import java.util.Objects;  class Pair<K, V>  {     public K key;     public V value;      public Pair(K key, V value)      {         this.key = key;         this.value = value;     }      public void setKey(K key) {         this.key = Objects.requireNonNull(key);     }          public void setValue(V value) {         this.value = Objects.requireNonNull(value, "no value");     } }  class GFG {     public static void main(String[] args)      {         Pair<String, String> p1 =                      new Pair<String, String>("GFG", "geeksforgeeks.org");                  p1.setKey("Geeks");                  // below statement will throw NPE with customized message         p1.setValue(null);              } } 
    Output:
    Exception in thread "main" java.lang.NullPointerException: no value
    at java.util.Objects.requireNonNull(Objects.java:228)
    at Pair.setValue(GFG.java:22)
    at GFG.main(GFG.java:36)
  7. int hashCode(Object o) : This method returns the hash code of a non-null argument and 0 for a null argument.
    Syntax : 
    public static int hashCode(Object o)
    Parameters :
    o - an object
    Returns :
    the hash code of a non-null argument and 0 for a null argument
    Java
    // Java program to demonstrate Objects.hashCode(Object o) object  import java.util.Objects;  class Pair<K, V>  {     public K key;     public V value;      public Pair(K key, V value)      {         this.key = key;         this.value = value;     }      @Override     public int hashCode()     {         return (Objects.hashCode(key) ^ Objects.hashCode(value));                  /* without Objects.hashCode(Object o) method         return (key == null ? 0 : key.hashCode()) ^          (value == null ? 0 : value.hashCode()); */     } }  class GFG {     public static void main(String[] args)      {         Pair<String, String> p1 =                  new Pair<String, String>("GFG", "geeksforgeeks.org");         Pair<String, String> p2 =                  new Pair<String, String>("Code", null);         Pair<String, String> p3 = new Pair<String, String>(null, null);                  System.out.println(p1.hashCode());         System.out.println(p2.hashCode());         System.out.println(p3.hashCode());     } } 
    Output:
    450903651
    2105869
    0
  8. int hash(Object... values) : This method generates a hash code for a sequence of input values. The hash code is generated as if all the input values were placed into an array, and that array were hashed by calling Arrays.hashCode(Object[]). This method is useful for implementing Object.hashCode() on objects containing multiple fields. For example, if an object that has three fields, x, y, and z, one could write:
    @Override 
    public int hashCode() {
    return Objects.hash(x, y, z);
    }
    Note: When a single object reference is supplied, the returned value does not equal the hash code of that object reference. This value can be computed by calling hashCode(Object).
    Syntax : 
    public static int hash(Object... values)
    Parameters :
    values - the values to be hashed
    Returns :
    a hash value of the sequence of input values
    Java
    // Java program to demonstrate Objects.hashCode(Object o) object  import java.util.Objects;  class Pair<K, V>  {     public K key;     public V value;      public Pair(K key, V value)      {         this.key = key;         this.value = value;     }      @Override     public int hashCode()     {         return (Objects.hash(key,value));     } }  class GFG {     public static void main(String[] args)      {         Pair<String, String> p1 =                  new Pair<String, String>("GFG", "geeksforgeeks.org");         Pair<String, String> p2 =                  new Pair<String, String>("Code", null);         Pair<String, String> p3 = new Pair<String, String>(null, null);                  System.out.println(p1.hashCode());         System.out.println(p2.hashCode());         System.out.println(p3.hashCode());     } } 
    Output:
    453150372
    65282900
    961
  9. int compare(T a,T b,Comparator c) : As usual, this method returns 0 if the arguments are identical and c.compare(a, b) otherwise. Consequently, if both arguments are null 0 is returned. Note that if one of the arguments is null, a NullPointerException may or may not be thrown depending on what ordering policy, if any, the Comparator chooses to have for null values.
    Syntax : 
    public static int compare(T a,T b,Comparator c)
    Type Parameters:
    T - the type of the objects being compared
    Parameters :
    a - an object
    b - an object to be compared with a
    c - the Comparator to compare the first two arguments
    Returns :
    0 if the arguments are identical and c.compare(a, b) otherwise.

Note : In Java 8, Objects class has 3 more methods. Two of them(isNull(Object o) and nonNull(Object o)) are used for checking null reference. The third one is one more overloaded version of requireNonNull method. Refer here.


Next Article
Different Ways to Create Objects in Java

G

gaurav miglani
Improve
Article Tags :
  • Misc
  • Java
  • Java - util package
Practice Tags :
  • Java
  • Misc

Similar Reads

    Classes and Objects in Java
    In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects, wh
    11 min read
    Understanding Classes and Objects in Java
    The term Object-Oriented explains the concept of organizing the software as a combination of different types of objects that incorporate both data and behavior. Hence, Object-oriented programming(OOPs) is a programming model, that simplifies software development and maintenance by providing some rul
    10 min read
    Inner Class in Java
    In Java, inner class refers to the class that is declared inside class or interface which were mainly introduced, to sum up, same logically relatable classes as Java is object-oriented so bringing it closer to the real world. Now geeks you must be wondering why they were introduced? There are certai
    11 min read
    Anonymous Inner Class in Java
    Nested Classes in Java is prerequisite required before adhering forward to grasp about anonymous Inner class. It is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain "extras" such as o
    7 min read
    Nested Classes in Java
    In Java, it is possible to define a class within another class, such classes are known as nested classes. They enable you to logically group classes that are only used in one place, thus this increases the use of encapsulation and creates more readable and maintainable code. The scope of a nested cl
    5 min read
    Java.util.Objects class in Java
    Java 7 has come up with a new class Objects that have 9 static utility methods for operating on objects. These utilities include null-safe methods for computing the hash code of an object, returning a string for an object, and comparing two objects.Using Objects class methods, one can smartly handle
    7 min read
    Different Ways to Create Objects in Java
    Java is an object-oriented programming language where objects are instances of classes. Creating objects is one of the most fundamental concepts in Java. In Java, a class provides a blueprint for creating objects. Most of the time, we use the new keyword to create objects but Java also offers severa
    5 min read
    How are Java Objects Stored in Memory?
    In Java, memory management is handled by the Java Virtual Machine (JVM). The breakdown of how objects are stored in memory:All Java objects are dynamically stored in the heap memory.References to these objects are stored in the stack memory.Objects are created using the "new" keyword and are allocat
    5 min read
    Passing and Returning Objects in Java
    Although Java is strictly passed by value, the precise effect differs between whether a primitive type or a reference type is passed. When we pass a primitive type to a method, it is passed by value. But when we pass an object to a method, the situation changes dramatically, because objects are pass
    6 min read
    Java Lambda Expressions
    Lambda expressions in Java, introduced in Java SE 8. It represents the instances of functional interfaces (interfaces with a single abstract method). They provide a concise way to express instances of single-method interfaces using a block of code.Key Functionalities of Lambda ExpressionLambda Expre
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences