Thursday 6 September 2018

Why Java compound assignment operators do not require casting?

Casting is required when you are trying to assign a high data type value to low data type variable.

For example,
byte byteVar = 10;
int intVar = 100;
                 
byteVar = (byte) (byteVar + intVar);

In the above example, I am adding byteVar, intVar and assigning the final result to byteVar. I must do explicit casting here, otherwise my compiler gives an error.

But in case of compound assignment operations, casting is done by Java internally. As per Java documentation, A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

byteVar += intVar;

Is Equivalent to

byteVar = (byte) (byteVar + intVar);

Find the below working application.

Application.java
package com.sample.app;

public class Application {
 public static void main(String args[]) {
  byte byteVar = 10;
  int intVar = 100;
  
  byteVar += intVar;
  
  System.out.println(byteVar);
 }
}

Reference


You may like

No comments:

Post a Comment