Java Object Null Check for method
Solution 1
First you should check if books
itself isn't null, then simply check whether books[i] != null
:
if(books==null) throw new IllegalArgumentException();
for (int i = 0; i < books.length; i++){
if(books[i] != null){
total += books[i].getPrice();
}
}
Solution 2
You can add a guard condition to the method to ensure books
is not null and then check for null when iterating the array:
public static double calculateInventoryTotal(Book[] books)
{
if(books == null){
throw new IllegalArgumentException("Books cannot be null");
}
double total = 0;
for (int i = 0; i < books.length; i++)
{
if(books[i] != null){
total += books[i].getPrice();
}
}
return total;
}
Solution 3
If you are using Java 7 You can use Objects.requireNotNull(object[, optionalMessage]);
- to check if the parameter is null
. To check if each element is not null just use
if(null != books[i]){/*do stuff*/}
Example:
public static double calculateInventoryTotal(Book[] books){
Objects.requireNotNull(books, "Books must not be null");
double total = 0;
for (int i = 0; i < books.length; i++){
if(null != book[i]){
total += books[i].getPrice();
}
}
return total;
}
Solution 4
If array of Books is null, return zero as it looks that method count total price of all Books provided - if no Book is provided, zero is correct value:
public static double calculateInventoryTotal(Book[] books)
{
if(books == null) return 0;
double total = 0;
for (int i = 0; i < books.length; i++)
{
total += books[i].getPrice();
}
return total;
}
It's upon to you to decide if it's correct that you can input null input value (shoul not be correct, but...).
Solution 5
You simply compare your object to null
using the ==
(or !=
) operator. E.g.:
public static double calculateInventoryTotal(Book[] books) {
// First null check - the entire array
if (books == null) {
return 0;
}
double total = 0;
for (int i = 0; i < books.length; i++) {
// second null check - each individual element
if (books[i] != null) {
total += books[i].getPrice();
}
}
return total;
}
CoShark
Updated on July 18, 2022Comments
-
CoShark almost 2 years
I need to create a null check in this formula for the books[i] and I am not entirely sure how to go about this as I am not greatly familiar with null checks and very new at programming. Any and all help is much appreciated!
public static double calculateInventoryTotal(Book[] books) { double total = 0; for (int i = 0; i < books.length; i++) { total += books[i].getPrice(); } return total; }
-
Bohemian over 10 yearsYoda tests have no value in java: Just code normally as
if (books == null)
-
Svetlin Zarev over 10 yearsIf you code only in java, they might not have any value, but if you program in more than one language, in which there is a difference, yoda checks are quite important and quickly become a habit. Even more I find them more readable :)
-
Bohemian over 10 yearsBut this us a java question and nobody uses them in java. It's an industry standard thing.
-
Brian Roach over 10 yearsWhat is the correct result is
0
? In general, exceptions ornull
(via autoboxed return type) are preferred over using magic numbers. -
Brian Roach over 10 yearsWhat is the correct result is
0
? In general, exceptions ornull
(via autoboxed return type) are preferred over using magic numbers. -
Brian Roach over 10 years::raises hand:: I use them. Because of habit (one, quite frankly that I don't want to break because I'm a polyglot). And I'd be willing to bet I'm not the only one ;)
-
1ac0 over 10 years@BrianRoach It looks that
calculateInventoryTotal(Books[] books)
count total price of a provided Books. So if no Books is provided, total price is zero. So 0 is correct return value in this case, it's definitely no magic number. -
Brian Roach over 10 yearsHow do you differentiate between a
null
array being passed in, and an array containing one/all book with a price of0
? The reason throwing anIllegalArgumentException
is a better choice is because it prevents two different cases (one valid, one not) from producing the same result, and explicitly indicates a programming error. -
1ac0 over 10 years@BrianRoach do you need to diferentiate this? in hypothetical method
calculateInventoryCount(Book[] books)
you should need this but if you need total price - in real world price should be zero or higher than zero and doesn't matter if you don't have a book or you have hundreds of books. it depends on your analysis ;-) -
Brian Roach over 10 yearsNote that I'm not downvoting your answer or anything, I just think that's it's important to explain to beginners the best-practice approach rather than something that works, right now, for what they're doing. Note the OP has actually accepted the least explanatory answer ::sigh::
-
1ac0 over 10 years@BrianRoach yes, i see :-) just thinking that in some situations there isn't need to over-exception-throwing, better should be look what method is doing. but of course, for beginer this should be confusing.
-
1ac0 over 10 yearshave you tried it with null as input value for books?
-
Kuba Spatny over 10 years@ladislavDANKO Thanks, I initially answer only what OP was asking for, but it is a good comment! Edited my answer.
-
1ac0 over 10 yearsthis is only correct check for null values: at first check array and secondly check each element.
-
John over 10 yearsFair point; if the books parameter is null there'll be a NullPointerException, but I don't believe that is the type of null check that the questioner was talking about.
-
Marco Tulio Avila Cerón about 6 yearsOld fashion programming, please update to Java 8, see my comment below. (And the worse is that the answer is incorrect, you don't use double for monetary calculations, that is the job of BigDecimal)