Tuesday, 21 April 2015

Java automatic numeric type promotion

In Java numeric promotion happens in case of primitive types when those primitives are used in an expression.

As exp.

  byte a = 100;
  byte b = 50;
  int i = a * b;
  

in the above code a * b will exceed the range of its byte operand (range of byte is -128 to 127). In these type of situations Java will automatically promote the byte, short or char to int when evaluating an expression. Also, note that the result is assigned to an int variable i without any explicit casting as the result was already an int.

Rules for Type promotion

There are several type promotion rules that are followed while evaluating expressions-
  • All byte, short and char values are promoted to int.
  • If any operand is long then the expression result is long. i.e. whole expression is promoted to long.
  • If any operand is a float then the expression result is float. i.e. whole expression is promoted to float.
  • If any operand is a double then the expression result is double. i.e. whole expression is promoted to double.

Let's see an example depicting the rules -

automatic numeric type promotion

As shown in the code, since one of the value is float so the result should also be float and that's what the compiler is complaining about here.

Problems because of automatic type promotion

Sometimes automatic numeric promotion may cause confusing compilation problems.
Let's see it with an example -

automatic numeric type promotion

Here byte b has the value 2. Again I am trying to assign (b * 2) to b which is with in the range of byte (-128 to 127) but compiler complains "Can't convert from int to byte". This error is there because the byte is automatically converted to int at the time of evaluating the expression. If it has to be assigned to a byte then explicit casting is required.

b=(byte)b*2;

That's all for this topic Java automatic numeric type promotion. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. interface in Java
  2. Inheritance in Java
  3. Constructor in Java
  4. static in Java
  5. Core Java basics interview questions

You may also like -

>>>Go to Java Basics page

1 comment:

  1. What happens if you mix and match long, float and double operands with each other? How do the rules apply? Which operand takes precedence?

    ReplyDelete