Photo by Santiago Lacarta on Unsplash

Managing Numeric Types and Lossy Conversions in Java

Sriram Kumar Mannava
2 min readApr 3, 2024

--

Java manages numeric literals in an interesting way. There are 4 datatypes to store whole numbers - byte, short, int and long.

when you compare the sizes, each can accommodate numbers ranging from 2⁷ (byte) to 2⁶⁴ (long)

However, by default Java tries to fit the number literal into the target type, although technically the value may not be that time.

For example, the below statement works without any issue -

long myVar = 235;

Although this is syntactically correct, it's technically wrong, because we're trying to put an integer into a long type.

The size of an int type is 2³², while that of a long is 2⁶⁴. Since the value falls within the range of the long type, it works.

On the contrary, if we try to fit a larger value into a smaller type, it'd throw an error.

For example, the below statement doesn't work.

byte myByte = 200;

This statement results in an error - incompatible types: possible lossy conversion from int to byte

This is called a lossy conversion. To circumvent this situation, we can use type casting to fit a larger size type to a smaller size type.

int myVar = 128;
byte myByte = (byte)myByte;

The output for myByte will be -127, because the value has actually overflown the max bounds of the byte type (-127, 127).

If a value goes beyond the limit bounds of a type, Java flips it to the other side of the bounds.

This is called wraparound vulnerability that is a known thing in Java terms.

Summary

Type conversions are an interesting but tricky part in any programming language. Java provides 4 primitive types to just store numbers, and each of these types have their own sizes and limits.

But since all of these are whole number literals, Java tries to smartly fit into the target type whatever we assign to it. By default it treats all the numbers as integers and fits into variables of even larger or smaller types.

But when you try to fit a larger value into a smaller value, you're doing a lossy conversion and Java throws an error for it.

downward type casting works, but you will still loose data and overflow condition will occur.

Get delicious Indian delights and groceries delivered home quickly! Use promo code WELCOME24 and Enjoy a fantastic 10% discount on all Quicklly transactions. Checkout quicklly.com for more!

--

--

Sriram Kumar Mannava

I make Full Stack Development Easy for You | Full Stack .NET Dev | 3× AWS Certified | Blogger