Do you know Java: Decorate your code


You do not need comments to decorate your code minimally.

Many years back then comments were the ultimate tool to decorate our code. And as it happened many times, sotware engineers glady used it to place ascii arts around their hotfixes or just simple seperate their solutions.

In this post I would like to show you a funny feature of operators which you can use to draw lines or more.

Let us see the following code snippet.

int i = 1 + + + + + + + 1;

Do you think it compiles? Yes, it does! And the reason is none other than the arity of the operators. We group the operators into three different groups such as unary, binary, and ternary operators. The arity of an operator is the number of operands we need to put around the operator.

Let us see some examples:

  • unary: !, ~, +, -, ++, --
  • binary: *, ==, <=
  • ternary: ? :

In our case, + and - operators can be unary or binary depending on the context where we use them. If there is only one operand before or after the operator the + or - is evaluated as unary, if there are operands on both sides then operators is binary.

Additional examples such as:

int j = 1 + - + - + - + 1;
int k = 1 - - - - - - - 1;

The key is the arity of the operators.

Further reading about operators.

Code can be found: https://github.com/torokmark/do-you-know-java