Quantcast
Channel: Tech Tutorials
Viewing all articles
Browse latest Browse all 938

Java Automatic Numeric Type Promotion

$
0
0

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

As example


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 in Java

There are several type promotion rules in Java 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 automatically promoted to float.
  • If any operand is a double then the expression result is double. i.e. whole expression is promoted to double in Java.

Let's see a Java example depicting the numeric promotion rules-

automatic numeric type promotion in Java

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 in Java 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 type 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. Access Modifiers in Java
  2. interface 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


Viewing all articles
Browse latest Browse all 938

Trending Articles