Java base is null

Java base is null

This class consists of static utility methods for operating on objects, or checking certain conditions before operation. These utilities include null -safe or null -tolerant methods for computing the hash code of an object, returning a string for an object, comparing two objects, and checking if indexes or sub-range values are out of bounds.

Method Summary

Checks if the sub-range from fromIndex (inclusive) to fromIndex + size (exclusive) is within the bounds of range from 0 (inclusive) to length (exclusive).

Checks if the sub-range from fromIndex (inclusive) to toIndex (exclusive) is within the bounds of range from 0 (inclusive) to length (exclusive).

Checks that the specified object reference is not null and throws a customized NullPointerException if it is.

Checks that the specified object reference is not null and throws a customized NullPointerException if it is.

Returns the first argument if it is non- null and otherwise returns the non- null value of supplier.get() .

Returns the result of calling toString on the first argument if the first argument is not null and returns the second argument otherwise.

Читайте также:  Java jframe убрать кнопки

Methods declared in class java.lang.Object

Method Detail

equals

Returns 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.

deepEquals

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.

hashCode

hash

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()

Warning: 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) .

toString

toString

public static String toString​(Object o, String nullDefault)

Returns the result of calling toString on the first argument if the first argument is not null and returns the second argument otherwise.

compare

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.

requireNonNull

public static T requireNonNull​(T obj)

Checks that the specified object reference is not null . This method is designed primarily for doing parameter validation in methods and constructors, as demonstrated below:

requireNonNull

Checks that the specified object reference is not null and throws a customized NullPointerException if it is. This method is designed primarily for doing parameter validation in methods and constructors with multiple parameters, as demonstrated below:

public Foo(Bar bar, Baz baz)

isNull

nonNull

requireNonNullElse

public static T requireNonNullElse​(T obj, T defaultObj)

requireNonNullElseGet

Returns the first argument if it is non- null and otherwise returns the non- null value of supplier.get() .

requireNonNull

Checks that the specified object reference is not null and throws a customized NullPointerException if it is. Unlike the method requireNonNull(Object, String) , this method allows creation of the message to be deferred until after the null check is made. While this may confer a performance advantage in the non-null case, when deciding to call this method care should be taken that the costs of creating the message supplier are less than the cost of just creating the string message directly.

checkIndex

public static int checkIndex​(int index, int length)

checkFromToIndex

public static int checkFromToIndex​(int fromIndex, int toIndex, int length)

checkFromIndexSize

public static int checkFromIndexSize​(int fromIndex, int size, int length)

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

9 вещей о NULL в Java

Java-университет

9 вещей о NULL в Java - 1

Java и null неразрывно связаны. Едва ли существует Java-программист, не встречавшийся с «null pointer exception» и это печальный факт. Даже изобретатель концепции «null» назвал ее своей ошибкой на миллиард долларов, тогда зачем Java поддерживает ее? null был здесь долгое время, и я полагаю, создатели Java знают, что он создает больше проблем чем решает, так почему же они все еще мирятся с этим. И это удивляет меня еще больше, потому что философией Java было упростить вещи, вот почему они больше не возятся с указателями, перегрузкой операторов и множественным наследованием, но почему null?Ну, я действительно не знаю ответ на этот вопрос, но, что я точно знаю, не имеет значения сколько бы null критиковался Java-программистами и open-source сообществом, мы должны жить с ним. Вместо того чтобы сожалеть, лучше узнать больше и быть уверенным что мы используем null правильно.

Почему Вы должны узнать о null в Java?

Потому что, если Вы не обратите внимания на null, будьте уверены, Java заставит страдать от ужасного java.lang.NullPointerException и Вы выучите этот урок, но пойдете более трудным путем. Написание устойчивого к «падениям» кода — это искусство и Ваша команда, заказчики и пользователи оценят это. По моему опыту, одна из основных причин NullPointerException это недостаток знаний о null в Java. Многие из Вас уже знакомы с null, остальные смогу узнать некоторые старые и новые вещи о ключевом слове null. Давайте повторим или узнаем некоторые важные вещи о null в Java.

Что есть null в Java

  1. Перво-наперво, null это ключевое слово в Java, так же как public , static или final . Регистр учитывается, Вы не можете писать null как Null или NULL, компилятор не распознает его и будет выброшена ошибка.
 Object obj = NULL; // Not Ok Object obj1 = null //Ok 
 private static Object myObj; public static void main(String args[]) < System.out.println("What is value of myObjc : " + myObj); >What is value of myObjc : null 
 String str = null; // null can be assigned to String Integer itr = null; // you can assign null to Integer also Double dbl = null; // null can also be assigned to Double String myStr = (String) null; // null can be type cast to String Integer myItr = (Integer) null; // it can also be type casted to Integer Double myDbl = (Double) null; // yes it's possible, no error 
 int i = null; // type mismatch : cannot convert from null to int short s = null; // type mismatch : cannot convert from null to short byte b = null: // type mismatch : cannot convert from null to byte double d = null; //type mismatch : cannot convert from null to double Integer itr = null; // this is ok int j = itr; // this is also ok, but NullPointerException at runtime 
 Integer iAmNull = null; int i = iAmNull; // Remember - No Compilation Error 
 Exception in thread "main" java.lang.NullPointerException 

Это часто происходит при работе с HashMap и Integer key . Выполнение кода, показанного ниже прервется, как только Вы его запустите.

 import java.util.HashMap; import java.util.Map; /** * An example of Autoboxing and NullPointerExcpetion * * @author WINDOWS 8 */ public class Test < public static void main(String args[]) throws InterruptedException < Map numberAndCount = new HashMap<>(); int[] numbers = ; for(int i : numbers) < int count = numberAndCount.get(i); numberAndCount.put(i, count++); // NullPointerException here >> > 
 Output: Exception in thread "main" java.lang.NullPointerException at Test.main(Test.java:25) 
 Integer iAmNull = null; if(iAmNull instanceof Integer)< System.out.println("iAmNull is instance of Integer"); >else
 Output : iAmNull is NOT an instance of Integer 
 public class Testing < public static void main(String args[])< Testing myObject = null; myObject.iAmStaticMethod(); myObject.iAmNonStaticMethod(); >private static void iAmStaticMethod() < System.out.println("I am static method, can be called by null reference"); >private void iAmNonStaticMethod() < System.out.println("I am NON static method, don't date to call me by null"); >> 
 Output: I am static method, can be called by null reference Exception in thread "main" java.lang.NullPointerException at Testing.main(Testing.java:11) 
 public void print(Object obj) 
 public class Test < public static void main(String args[]) throws InterruptedException < String abc = null; String cde = null; if(abc == cde)< System.out.println("null == null is true in Java"); >if(null != null) < System.out.println("null != null is false in Java"); >// classical null check if(abc == null) < // do something >// not ok, compile time error if(abc > null) < >> > 
 Output: null == null is true in Java 

Источник

Check if an Object Is Null in Java

Check if an Object Is Null in Java

  1. Java Check if Object Is Null Using the == Operator
  2. Java Check if Object Is Null Using java.utils.Objects

This tutorial will go through the methods to check if an object is null in Java with some briefly explained examples.

Java Check if Object Is Null Using the == Operator

As an example, we have created two classes — User1 and User2 . The class User1 has one instance variable name and the Getter and Setter methods to update and retrieve the instance variable name . The User2 class has one method, getUser1Object , which returns the instance of class User1 .

In the main method, we create an object of the User2 class named user and call the getUser1Object() on it, which returns the instance of the class User1 . Now we check if the instance of the User1 class returned by the method is null or not by using the == operator in the if-else condition.

If the object returned is not null , we can set the name in the User1 class by calling the setter method of the class and passing a custom string as a parameter to it.

public class JavaCheckNullObject    public static void main(String[] args)    User2 user;  user = new User2();   User1 getUserObject = user.getUser1Object();   if (getUserObject == null)   System.out.println("Object is Null");  > else   System.out.println("Not Null");   getUserObject.setName("Sam");  System.out.println(getUserObject.getName());  >  >  >  class User2    User1 user;   public User1 getUser1Object()   return user;  > >  class User1   String name;   public String getName()   return name;  >   public void setName(String name)   this.name = name;  >  > 

Java Check if Object Is Null Using java.utils.Objects

The java.utils.Objects class has static utility methods for operating an object. One of the methods is isNull() , which returns a boolean value if the provided reference is null, otherwise it returns false.

We have created two classes — User1 and User2 as shown in the code below. In the main method, we created an object of the User2 class using the new keyword and called the getUser1Object() method. It returns an object of class User1 , which we later store in getUser1Object .

To check if it is null, we call the isNull() method and pass the object getUserObject as a parameter. It returns true as the passed object is null.

import java.util.Objects;  public class JavaCheckNullObject   public static void main(String[] args)   User2 user;  user = new User2();   User1 getUserObject = user.getUser1Object();   if (Objects.isNull(getUserObject) )  System.out.println("Object is Null");  > else   System.out.println("Not Null");   getUserObject.setName("Sam");  System.out.println(getUserObject.getName());  >  > > class User2    User1 user;   public User1 getUser1Object()   return user;  > >  class User1   String name;   public String getName()   return name;  >   public void setName(String name)   this.name = name;  >  > 

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

Related Article — Java Object

Copyright © 2023. All right reserved

Источник

Оцените статью