Just like the title shows, I couldn't find any clue about it in Javadoc.
Asked
Active
Viewed 3,513 times
0
-
1I am so looking forward to `@Nullable`, `@NotNullable` annotations in the JDK... – Thilo Apr 09 '12 at 09:15
-
Both the JavaDoc and the source in Sun's JDK is clear - it won't ever happen. – Tomasz Nurkiewicz Apr 09 '12 at 09:17
-
1*"I couldn't find any clue about it in Javadoc"* The clue is that the Javadoc **doesn't** say that it will return `null`. Therefore, it won't. – T.J. Crowder Apr 09 '12 at 09:17
-
@T.J.Crowder Well, that is not something I would rely on. – Thilo Apr 09 '12 at 10:07
-
1@Thilo: If a method returns `null` without documenting it as a return value, it's a bug (in the method, or the Javadoc). If you catch anyone (including Sun/Oracle) doing it, report said bug to them. :-) – T.J. Crowder Apr 09 '12 at 10:31
3 Answers
4
No, it never will. It would never make sense to return null, and if you look at the implementation it definitely won't. (I realize it's generally better to rely on the documented guarantees than the implementation, but I see no reason to suppose it would ever return null here.)
In particular, the documentation states:
Creates a newly allocated byte array.
and
Returns: the current contents of this output stream, as a byte array.
Those wouldn't be correct if it returned null, would it?

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
0
It would return null
in one way ;)
ByteArrayOutputStream baos = new ByteArrayOutputStream()
{
public byte[] toByteArray()
{
return null;
}
};
System.out.println(baos.toByteArray());
OUTPUT:
null

Eng.Fouad
- 115,165
- 71
- 313
- 417
-
3Yes, but at that point it's not obeying the contract in the Javadoc, is it? – Jon Skeet Apr 09 '12 at 09:22
-
@JonSkeet You are right, but it at least it can return `null` at the end :) – Eng.Fouad Apr 09 '12 at 09:23
-
1That isn't a `ByteArrayOutputStream`. It's a `ByteArrayOutputStream` interface to a *derived* class (and one that's violating its parent's contract, as Jon pointed out). – T.J. Crowder Apr 09 '12 at 09:32
-
But it's not a java.io.ByteArrayOutputStream.toByteArray() actually ;) – artplastika Apr 09 '12 at 12:13
0
No it wouldn't. Ever. Look into the code ByteArrayOutputStream.toByteArray:
public synchronized byte toByteArray()[] {
return Arrays.copyOf(buf, count);
}
Arrays.copyOf:
public static byte[] copyOf(byte[] original, int newLength) {
byte[] copy = new byte[newLength];
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}

artplastika
- 1,972
- 2
- 19
- 38