Witscale Test Center

10.3 Type conversion in primitives > 10.3.2 Primitive type conversion during assignment


10.3.2 Primitive type conversion during assignment

Following rules are observed when you assign a value of a primitive type to a variable of another primitive:

1.       You can assign any non-boolean value to any non-boolean variable. The type conversion takes place only if  the type is changed to a wider type.

For example, the following code compiles as long is wider datatype than int.

 

int intNumber = 5;

long longNumber;

longNumber = intNumber; // int value assigned to a wider type long

 

Java will automatically convert the int value 5 into long value and then assign it to long variable.

2.       You cannot assign a non-boolean value to a non-boolean variable if the type is changed to a narrower type.

For example, the following code does not compile as short is a narrower datatype than int.

 

int intNumber = 5;

short shortNumber = intNumber; // Error! short is narrower than int

 

 Java cannot automatically convert the int value 5 into short value.

3.       You cannot assign a boolean value to a non-boolean primitive variable or vice versa.

The boolean and all other non-boolean primitive types are incompatible. For example, following code will not compile.

 

int number = true;  // Error! boolean to non-boolean not allowed

 

You cannot store true in int variable. Following code will also fail to compile as you cannot store a int value in boolean variable either:

 

int number = 1;

boolean result = number; // Error! non-boolean to boolean not allowed

 

You cannot assign a boolean value to non-boolean variable as well. The boolean value can be store only in boolean variable.