• missing xbfish.com image

[Java] Type casting examples

missing xbfish.com image
Posted on

In Java programming language, when a value is assigned to a variable of different types, one of the 2 cases can occur:

Widening (Promotion)

  • Value has a smaller range compared to the variable
  • Converted automatically by Java compiler

Narrowing (Demotion)

  • Value has a larger range compared to the variable
  • Explicit type casting by the programmer is needed

Example (without type casting):

1
2
3
4
5
double d;
int i = 31415;
 
d = i / 10000;
System.out.println(d);

This will output:

3.0

We are expecting the output to be 3.1415 in this case.

Example (with type casting):

1
2
3
4
5
double d;
int i = 31415;
 
d = (double) i / 10000;
System.out.println(d);

This will output:

3.1415

Here, we type cast int i to double type so that the calculation of the result will match the double type of variable d.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">