Else return null java

How to return nothing from a function that returning value?

I have a binary search tree, and I want to delete a node. I need to get its parent, so I wrote a function:

private BSTreeNode getParent(BSTreeNode root, BSTreeNode node) < if(root == null) return null; if(node.element().lessThan(root.element())) < if(root.getLeft() != null && root.getLeft().element().equal(node.element())) return root; else getParent(root.getLeft(), node); >else < if(root.getRight() != null && root.getRight().element().equal(node.element())) return root; else getParent(root.getRight(), node); >> 
This method must return a result of type BSTreeNode

It forces me to return a value in the last line of the function. How can I fix it in the context of my function?

I don’t know, that’s part of your design. The point is your method must always return something if your return type is different than void .

C and C++ compilers may not force you to return a value for non-void return types, but that doesn’t mean it’s «allowed». If the function terminates without a return (or exception) the result is undefined. Java is just particularly keen on enforcing this rule.

@SotiriosDelimanolis Oh, my fault. I confused a minute that I have to return value in all the else-if blocks. thank you so much!

3 Answers 3

Your function does not have a return for every possible circumstance. You have:

if (null). if (less than root). else ( if . ) else (no return!) 

What do you return if it is not null, and goes to the final else? Nothing is returned.

Читайте также:  Java locale time format

You can either return getParent. in the else statement. or return null at the end of the function (not in an if or else statement)

I often see code like so to cover the event of neither if statement returning a value.

Источник

Java — how to return a null in this String method?

> this code will print 19abc 3.5 when i put obj = null in the main method this code is not working, Why?

«this code is not working» doesn’t tell us what you expected or what the result was. or where you set obj to null.

5 Answers 5

Your code as it stands try’s to index into the Object array without checking for null with the code things.length , which will throw a NullPointerException because there is no array object in existence, so the length field also does not exist.

To fix this use an if statement!

static String concatAll(Object[] things) < if(things == null) < return null; >. continue code. 

This will first check things for a null value BEFORE executing code that could throw an exception.

Calling a method on a null object causes a NullPointerException .

In your case if obj = null, then when you call concatAll, things will be null as well. You then try and call things.length which is not valid on a null object.

You can make this method safer by checking the input of strings first. What you want to do exactly will depend on your situation, but here is one example.

static String concatAll(Object[] things) < if (things == null) < return ""; >StringBuffer result = new StringBuffer(); for (int i = 0; i < things.length; i++) < result.append( things[i] ); >String x = result.toString(); return x; > 

Источник

Java Stream return null if either values is null

I have some Strings and if any one is null, then I need to return null. What is the way to achieve this via Stream? or is there any better way?

protected String toCombinedString(SomeClass shipment) < String prefix1 = ofNullable(shipment) .map(SomeClass::getBill) .map(Bill::getPrefixString) .orElse(null); String prefix2 = ofNullable(shipment) .map(SomeClass::getBill) .map(Bill::getPrefixString) .orElse(null); String number1 = ofNullable(shipment) .map(SomeClass::getBill) .map(Bill::getNumberString) .orElse(null); String number2 = ofNullable(shipment) .map(SomeClass::getBill) .map(Bill::getNumberString) .orElse(null); . return Stream.of(prefix1, number1, prefix2, number2. ) .filter(Objects::nonNull) .reduce((a, b) ->a + "-" + b) .orElseGet(String::new); > 

6 Answers 6

You seem to perform a ternary operation such as:

return prefix == null || number == null ? null : prefix + "-" + number; 

After the edit in the question, and the condition that only all such String type of attributes from the Bill entity would be considered in the result. You can formulate a method to extract the String from all attributes as:

protected String toCombinedString(SomeClass shipment) < return Optional.ofNullable(shipment) .map(SomeClass::getBill) .map(bill ->extractAttributes(bill, Bill::getNumberString, Bill::getPrefixString)) // use this further .orElse(null); > private String extractAttributes(Bill entity, Function. mappers) < Listattributes = Arrays.stream(mappers) .map(function -> function.apply(entity)) .collect(Collectors.toList()); return attributes.stream().anyMatch(s -> s == null || s.isEmpty()) ? null : String.join("-", attributes); > 

@naman I have updated the question. If I have to traverse 4/5 levels down and if any string is empty, then i have to return null. For one or two String ternary operation is sufficient. Any inputs on more Strings?

@ZafrullahSyed For multiple such arguments, you might want to collect them into a collection and validate the elements collected for the predicate that you’re willing to and return accordingly. The update in the question doesn’t really make it clear what your exact use case is. If the predicate is supposed to be the same for all variables, look for allMatch , otherwise, define better in the question what exactly are you looking forward to.

List list = Arrays.asList(prefix1, number1, prefix2, number2. ); return list.contains(null)? null: String.join("-", list); 

Using a Stream would not improve anything. The costs of the temporary storage are the same, as Stream.of(…) uses a temporary array just like Arrays.asList(…) or varargs methods in general.

But considering that each string is the result of a complex operation, the complexity or simplicity of the one final statement isn’t really relevant.

String prefix1 = your long complicated operation; if(prefix1 == null) return null; String prefix2 = second long complicated operation; if(prefix2 == null) return null; String number1 = third long complicated operation; if(number1 == null) return null; String number2 = fourth long complicated operation; if(number2 == null) return null; … return String.join("-", prefix1, number1, prefix2, number2 …); 

Источник

Return null in a method that returns doubles java

I am trying to test for a null input at the start of the method. And if found true I want to return null even though the method would usually return doubles. I need to keep the type of method as double

public double computeMean (double[] grades) < if (grades == null) < return null; 

Exactly as the error says. You cannot return null where a primitive is expected. You could if the method signature would be for a Double , though.

2 Answers 2

Explanation

null is a value that can only be used for objects. A double however is a primitive, it does not use the object-system. Which is why you can not return null if you specified double as return type.

Double wrapper

You can instead use Double , the wrapper class for double which uses the object-system.

Since Java provides automatic conversion between double and Double whenever needed (autoboxing), this can be quite handy to use.

Note that using Double brings quite some overhead to just a small double and that people regularly tend to forget to check for null when converting a Double to a double . I.e.

// foo() returns Double double value = foo(); // Bad code, it could be null! 

Instead, users must remember to check the resulting value:

Double result = foo(); if (result == null) < . >else

OptionalDouble

The modern, and probably better alternative, is to use Optional (you need at least Java 8 for this).

It was designed to be used whenever a method naturally might sometimes not return a result. For example if the array passed in empty. That case is completely okay and not to be considered as error.

This also solves the problem of users forgetting to check the result. Optional forces them to check it, else they can not get hands on the underlying value.

In order to avoid the performance overhead of Optional (wrapper class again), there is also OptionalDouble which internally uses double (primitive). Here is the code:

public OptionalDouble computeMean(double[] grades) < if (grades == null) < return OptionalDouble.empty(); >. return OptionalDouble.of(result); > 
OptionalDouble result = computeMean(. ); 

From there the user has a couple of options (see the documentation), for example

double value = result.orElse(10.4); // or double value = result.orElseThrow(); // or if (!result.isPresent()) < . >else

Exception

The last option is to actually just throw an exception. You should consider this whenever an user is doing something that is not intended and against what you consider correct usage (indicate this in your methods documentation).

I would actually say that in your specific situation, this is the case. It is impossible to compute a mean on null . It is different to passing in an empty array, where the I would go for an empty Optional . For a null array I would throw an exception, to indicate a bad usage.

A good exception for this situation is IllegalArgumentException , here is the code:

public double computeMean(double[] grades) < if (grades == null) < throw IllegalArgumentException("Grades must not be null!"); >. > 

Another idiomatic exception for exactly this use case is to throw NullPointerException . There is even a compact helper method to do all of this in one line:

public double computeMean(double[] grades) < Objects.requireNonNull(grades); // Yes, thats it . >

Result

Putting all of that together, I would do the following two changes:

  • Throw NullPointerException if grades is null , using Objects#requireNonNull
  • Return an empty OptionalDouble if grades is empty
public OptionalDouble computeMean(double[] grades) < Objects.requireNonNull(grades); if (grades.length == 0) < return OptionalDouble.empty(); >. return OptionalDouble.of(result); > 

Источник

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