user7407870
user7407870

Reputation:

What is the purpose of multiple type-casting in java?

I came across a code fragment in java today, as follows:

long longValue = 100;
byte b = (byte)(short)(int)longValue;
byte byteValue = 100;
long l = (long)(int)(short)byteValue;
System.out.println(b+l);

What is the purpose of type casting multiple times, from int to short to byte and from short to int to long? Would it make any difference if I cast directly from long to byte or vice-versa?

The above code did not make any difference even when there was no explicit type casting!

Upvotes: 0

Views: 299

Answers (1)

Stephen C
Stephen C

Reputation: 719261

What is the purpose of type casting multiple times, from int to short to byte and from short to int to long?

There is no purpose. Period.

byte b = (byte)(short)(int) longValue;
long l = (long)(int)(short) byteValue;

are 100% equivalent to:

byte b = (byte) longValue;
long l = byteValue;

The code in your question is probably one of the following:

  • an indication that the author of the code doesn't understand Java,
  • a test ... to see if >>you<< understand Java,
  • part of a unit test for a Java compiler or similar, or
  • code that was generated by some tool, which human beings shouldn't need to read, and a compiler will gleefully optimize.

There are one or two situations where a chain of typecasts is actually useful. Here is one:

int ch = ...
System.out.println("char is '" + (char)(byte) ch + "'");

Here, the (byte) narrows the int to an 8-bit signed value, and then the (char) widens it to a 16 bit unsigned value. Then the + operator causes Character.toString(char) to be used to convert the value to a String. (If you leave out the (char), the value will be formatted as a number, not a character ...)

(Note: there are problems with the above code. I am using it to illustrate that chaining type-casts is sometimes a useful thing to do.)

Upvotes: 5

Related Questions