-1

I have a method that is supposed to return a ByteBuffer. The meat of the method does the following:

if (true) {
    //code that puts some data into ByteBuffer bb
    return bb
}
else {
    //should not be writing any data to bb 
    //intention: leave bb as is
    return null;
}

After calling this method and putting the necessary data into the ByteBuffer, I turn it into a byte array by first calling bb.flip(). However, if the last iteration through the if-else loop happened to be false, the last data inputted was null and I get the java.lang.NullPointerException error.

Allocating zero capacity ByteBuffer

According to the page above, I'm supposed to return a zero-length ByteBuffer, but I'm not sure how to return something like that.

Any ideas on how to return an empty byte buffer?

  • [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) The answer, *"A lot. An absurd amount. More than you think you are capable of. After you have reached the end of your rope and the pain of not having the answer exceeds the vast amount of shame received by posting your question, that's when you can go ahead and ask. Because at that point, you will have done whatever research necessary to make it a good question worth asking."* –  Jul 26 '17 at 17:20
  • The question you posted has the exact code you need. **It is literally the second line in the question!** Every [tag:java] question you have asked so far is explained by simply reading the [tag:javadoc]. –  Jul 26 '17 at 17:20
  • Learn to use the [JavaDoc](https://stackoverflow.com/questions/11747712/where-is-the-javadoc-for-my-installed-java-i-have-sdk-for-7) before coming here to ask someone else to read it to you. [`ByteBuffer.allocate()`](https://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#allocate(int)) –  Jul 26 '17 at 17:24
  • I really wonder what about `capacity` - *The new buffer's capacity, in bytes* is not in *"laymans"* terms? Combined with passing `0` does not scream *zero-length ByteBuffer,*? –  Jul 26 '17 at 17:29

2 Answers2

0

Since you're going to use the ByteBuffer in either case, the method should just unconditionally return it -- returning null just leads to the error you observed.

To make this code clearer, I would just make the method return type void. The method can add bytes into the ByteBuffer (or not) by calling methods on it -- the return value here is actually superfluous.

Daniel Pryden
  • 59,486
  • 16
  • 97
  • 135
0

In else block use following statement to avoid NPE(null pointer exception)

return ByteBuffer.allocate(0);