Tutorial :What's happening with those concatenations in Java?



Question:

byte[] b1 = null;  byte[] b2 = null;    System.out.println(b1 + b2);    // 1  System.out.println("" + b1 + b2); // 2  

if I uncomment 1 it's giving compilation error.
if I uncomment 2 it's printing nullnull;

so what's happening here?


Solution:1

Line 2 is doing an implicit cast to String of both arrays and concatenating them, which is valid. In line one you are attempting to apply the add operator to two byte arrays, which is not supported.


Solution:2

  1. You use + operator for byte arrays like this. So compilation error.
  2. The initial double quotes converts b1 to b2 to string. Equivalent to b1.toString()+b2.toString(). So nullnull


Solution:3

1 tries to add two arrays, both of which are null. This does not work.

2 appends the string value of the array (null for null values, the result of toString() otherwise) to an empty string


Solution:4

  1. The add operation ( + ) is not defined for byte arrays. Simple as that.

  2. The "special" + operation for Strings tries very hard to convert all kinds of data types into Strings to make the operation work. In this particular case, converts a null reference into the String "null". Weird but it prevents some errors.

The reason why (2) didn't apply to (1) is that there were no Strings involved in (1), while the presence of "" in (2) forced the expression to be evaluated as Strings.


Solution:5

In 1 you are trying to use operator + on two arrays which is not defined in Java.

In 2 you are concatenating a string "" with the string representation of you null arrays. This only works because + resolves left to right, so it is interpreted as string concatenation. Move the "" to the end of the line and it will also give you compile errors.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »