The Wayback Machine - https://web.archive.org/web/20240907012345/https://www.geeksforgeeks.org/java-util-objects-class-java/
Open In App

Java.util.Objects class in Java

Last Updated : 24 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.



Previous Article
Next Article

Similar Reads

Java.util.TimeZone Class (Set-2) | Example On TimeZone Class
TimeZone class (the methods of this class was discussed in this article Java.util.TimeZone Class | Set 1) can be used in many cases like using TimeZone class we can get the time difference in term of hour and minute between two places.Problem : How we can get time difference of time in terms of hours and minutes between two places of Earth?Solution
5 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Java.util.concurrent.RecursiveAction class in Java with Examples
RecursiveAction is an abstract class encapsulates a task that does not return a result. It is a subclass of ForkJoinTask, which is an abstract class representing a task that can be executed on a separate core in a multicore system. The RecursiveAction class is extended to create a task that has a void return type. The code that represents the compu
3 min read
Java.util.concurrent.Phaser class in Java with Examples
Phaser's primary purpose is to enable synchronization of threads that represent one or more phases of activity. It lets us define a synchronization object that waits until a specific phase has been completed. It then advances to the next phase until that phase concludes. It can also be used to synchronize a single phase, and in that regard, it acts
7 min read
Java.util.concurrent.RecursiveTask class in Java with Examples
RecursiveTask is an abstract class encapsulates a task that returns a result. It is a subclass of ForkJoinTask. The RecursiveTask class is extended to create a task that has a particular return type. The code that represents the computational portion of the task is kept within the compute() method of RecursiveTask. RecursiveTask class is mostly use
2 min read
Java.util.BitSet class in Java with Examples | Set 1
BitSet is a class defined in the java.util package. It creates an array of bits represented by boolean values. Constructors: BitSet class Constructors / \ BitSet() BitSet(int no_Of_Bits)BitSet() : A no-argument constructor to create an empty BitSet object. BitSet(int no_Of_Bits): A one-constructor with an integer argument to create an instance of t
2 min read
Java.util.BitSet class methods in Java with Examples | Set 2
Methods discussed in this post: BitSet class methods. / / | | \ \ set() xor() clone() clear() length() cardinality() We strongly recommend to refer below set 1 as a prerequisite of this. BitSet class in Java | Set 1 set() : java.util.BitSet.set() method is a sets the bit at the specified index to the specified value. Syntax:public void set(int bitp
4 min read
Java.util.zip.DeflaterInputStream class in Java
Implements an input stream filter for compressing data in the "deflate" compression format. Constructor and Description DeflaterInputStream(InputStream in) : Creates a new input stream with a default compressor and buffer size. DeflaterInputStream(InputStream in, Deflater defl) : Creates a new input stream with the specified compressor and a defaul
3 min read
Java.util.zip.InflaterOutputStream class in Java
This class implements an output stream filter for uncompressing data stored in the "deflate" compression format. Constructors InflaterOutputStream(OutputStream out) : Creates a new output stream with a default decompressor and buffer size. InflaterOutputStream(OutputStream out, Inflater infl) : Creates a new output stream with the specified decompr
3 min read
Java.util.zip.InflaterInputStream class in Java
This class implements a stream filter for uncompressing data in the "deflate" compression format. It is also used as the basis for other decompression filters, such as GZIPInputStream. Constructors InflaterInputStream(InputStream in) : Creates a new input stream with a default decompressor and buffer size. InflaterInputStream(InputStream in, Inflat
3 min read
Java.util.zip.ZipOutputStream class in Java
This class implements an output stream filter for writing files in the ZIP file format. Includes support for both compressed and uncompressed entries. Constructor : ZipOutputStream(OutputStream out) : Creates a new ZIP output stream. ZipOutputStream(OutputStream out, Charset charset) : Creates a new ZIP output stream. Methods: void close() : Closes
3 min read
Java.util.jar.JarEntry class in Java
This class is used to represent a JAR file entry. Constructors : JarEntry(JarEntry je) : Creates a new JarEntry with fields taken from the specified JarEntry object. JarEntry(String name) : Creates a new JarEntry for the specified JAR file entry name. JarEntry(ZipEntry ze) : Creates a new JarEntry with fields taken from the specified ZipEntry objec
2 min read
Java.util.zip.GZIPInputStream class in Java
This class implements a stream filter for reading compressed data in the GZIP file format. Constructors GZIPInputStream(InputStream in) : Creates a new input stream with a default buffer size. GZIPInputStream(InputStream in, int size) : Creates a new input stream with the specified buffer size. Methods : void close() : Closes this input stream and
2 min read
Java.util.zip.ZipEntry class in Java
This class is used to represent a ZIP file entry. Constructors ZipEntry(String name) : Creates a new zip entry with the specified name. ZipEntry(ZipEntry e) : Creates a new zip entry with fields taken from the specified zip entry. Methods: Object clone() : Returns a copy of this entry. Syntax :public Object clone() Overrides: clone in class Object
4 min read
Java.util.jar.JarInputStream class in Java
The JarInputStream class is used to read the contents of a JAR file from any input stream. It extends the class java.util.zip.ZipInputStream with support for reading an optional Manifest entry. The Manifest can be used to store meta-information about the JAR file and its entries. Constructors JarInputStream(InputStream in) : Creates a new JarInputS
3 min read
Java.util.zip.ZipInputStream class in Java
This class implements an input stream filter for reading files in the ZIP file format. Includes support for both compressed and uncompressed entries. Constructors: ZipInputStream(InputStream in) : Creates a new ZIP input stream. ZipInputStream(InputStream in, Charset charset) : Creates a new ZIP input stream Methods : int available() : Returns 0 af
3 min read
Java.util.PriorityQueue class in Java
It is a priority queue based on priority heap. Elements in this class are in natural order or depends on the Constructor we used at this the time of construction. It doesn't permit null pointers. It doesn't allow inserting a non-comparable object, if it relies on natural ordering. Constructors: PriorityQueue(): Creates a PriorityQueue with the defa
6 min read
Java.util.Locale Class in Java | Set 1
As the name suggests util.Locale Class is used to perform locale tasks and provides locale information for the user. Declaration : public final class Locale extends Object implements Cloneable, Serializable Constructors : Locale(String L): Creates Locale from the given language code.Locale(String L, String C): Creates Locale from the given language
4 min read
Java.util.Locale Class in Java | Set 2
Java.util.Locale Class in Java | Set 1 More methods: getDisplayVariant() : java.util.Locale.getDisplayVariant() displays variant of the Locale Syntax : public final String getDisplayVariant() Parameters : ---- Return : ----------- getDisplayVariant(Locale in) : java.util.Locale.Locale in(Locale in) returns the variant of "in" locale. Syntax : publi
3 min read
Java.util.Random class in Java
Random class is used to generate pseudo-random numbers in java. An instance of this class is thread-safe. The instance of this class is however cryptographically insecure. This class provides various method calls to generate different random data types such as float, double, int. Constructors: Random(): Creates a new random number generator Random(
4 min read
Java.util.TimerTask class in Java
TimerTask is an abstract class defined in java.util package. TimerTask class defines a task that can be scheduled to run for just once or for repeated number of time. In order to define a TimerTask object, this class needs to be implemented and the run method need to be overridden. The run method is implicitly invoked when a timer object schedules
3 min read
Java.util.Timer Class in Java
Timer class provides a method call that is used by a thread to schedule a task, such as running a block of code after some regular instant of time. Each task may be scheduled to run once or for a repeated number of executions. Each timer object is associated with a background thread that is responsible for the execution of all the tasks of a timer
6 min read
Java.util.ArrayDeque Class in Java | Set 1
java.util.ArrayDeque class describes an implementation of a resizable array structure which implements the Deque interface. Array deques has not immutable and can grow as necessary. They are not thread-safe and hence concurrent access by multiple threads is not supported unless explicitly synchronized. Null elements are invalid in this structure. M
5 min read
Java.util.ArrayDeque Class in Java | Set 2
Java.util.ArrayDeque Class in Java | Set 1 More Methods of util.ArrayDeque Class : 16. offer(Element e) : java.util.ArrayDeque.offer(Element e) : inserts element at the end of deque. Syntax : public boolean offer(Element e) Parameters : e - element to add Return : true, if element is added else; false 17. offerFirst(Element e) : java.util.ArrayDequ
5 min read
Java.util.Dictionary Class in Java
The java.util.Dictionary class in Java is an abstract class that represents a collection of key-value pairs, where keys are unique and are used to access the values. It was part of the Java Collections Framework introduced in Java 1.2 but has been largely replaced by the java.util.Map interface since Java 1.2. The Dictionary class is an abstract cl
7 min read
Java.util.Observable class in Java
java.util.Observable is used to create subclasses that other parts of the program can observe. When an object of such subclass undergoes a change, observing classes are notified. The update( ) method is called when an observer is notified of a change. Note: Observing class must implement the Observer interface, which defines the update( ) method. A
8 min read
Java.util.UUID class in Java
A class that represents an immutable universally unique identifier (UUID). A UUID represents a 128-bit value. There exist different variants of these global identifiers. The methods of this class are for manipulating the Leach-Salz variant, although the constructors allow the creation of any variant of UUID (described below). There are four differe
7 min read
Java.util.TimeZone Class | Set 1
TimeZone class is used to represents a time zone offset, and also figures out daylight savings.What is a Time Zone and Time Offset?"Time Zone" is used to describe the current time for different areas of the world. It refers to one of the specific regions out of the 24 total regions in the world that are divided up by longitude. Within each one of t
7 min read
Java.util.concurrent.Exchanger class with Examples
Exchanger is the most interesting synchronization class of Java. It facilitates the exchange of elements between a pair of threads by creating a synchronization point. It simplifies the exchange of data between two threads. Its operation is simple: it simply waits until two separate threads call its exchange() method. When that occurs, it exchanges
3 min read
Java.util.IntSummaryStatistics class with Examples
The IntSummaryStatistics class is present in java.util package. It takes a collection of Integer objects and is useful in the circumstances when we are dealing with a stream of integers. It maintains a count of the number of integers it has processed, their sum and various other statistics. The class can also be used with Streams. It is useful in t
3 min read
Article Tags :
Practice Tags :