Java Primitive's little secrets

Here is a bunch of java primitives' interesting behaviour that we ofter ignore or forget! Recap time in 3 - 2 - 1...

Data type promotions

When you try to perform a numerical operation on a short type for example, the result will be promoted to int, therefore it wont compile if you try to store the result in a short variable unless you explicitly cast it (check line x).

The same applies to byte. Adding two numbers of type byte they will automatically be promoted to short.

What about int? Adding two number of type int together wont result to a long promotion (of course)...

Same as int if you try to to add together two float numbers, the result wont be promoted to double.

All the above are great... but... There is an interesting behaviour when you do the following

the above is perfectly valid, but the bellow results in a compilation error:

Yes indeed!

an easier one now:
Please welcome the infamous Numeric Overflow!


Popular posts from this blog

How to create a Cassandra container for testing with Keyspace and the latest schema with a single script call

DTOs conversion with reflection example - applied on Thymeleaf (or how to get read of Pojo's conversion boilerplate)

How to test file operations with Junit5 TempDir