Skip to content

Casting

If we had the below operations:

short x = 1;
int y = x + 2;
// This will return 3

As we are dealing with two different value types one of these value types should be converted to the other type prior to returning a final value. As a short is 2 bytes and an integer is 4 Java will look at the value of our short variable and allocate it to an anonymous memory location. This would be defined as implicit casting (Automatic conversion).

If we have a value that can be converted to a data type that is bigger of the same category casting or conversion happens implicitly/automatically.

//implicit casting
double x = 1.1;
double y = x + 2;
// This will return 3.1

In this case we are dealing with a double and an integer, an integer is less precise so in this example Java will automatically cast the integer to a double 2.0 adding it to 1.1.

As a general rule of thumb implicit casting happens when there is no risk of losing data.

//explicit casting
double x = 1.1;
int y = (int)x + 2;
//this will return 3

Compatibility: Explicit casting can only occur between compatible types, meaning the source type (like double) and the destination type (like int) must be compatible in some way. If you try to cast a completely incompatible type (like String to int), you’ll get an error.

Data loss: Explicit casting is often used when converting from a type with greater precision or range (like double) to one with less precision or range (like int). This can result in the loss of data, such as the fractional part when casting a double to an int.

All primitive types have wrapper classes which allows for the conversion of type’s to that primitive. These classes are especially useful when converting inputs from your application.

As an example:

String x = "1";
int y = Integer.parseInt(x) + 2;
// This will return 3
String x = "1.1";
int y = Integer.parseInt(x) + 2;
// This code will return an error and will need to have a float wrapper.