M4 Conversion Type
M4 Conversion Type
Java provides various data types just like any other dynamic languages such as
boolean, char, int, unsigned int, signed int, float, double, long, etc in total
providing 7 types where every datatype acquires different space while storing in
memory. When you assign a value of one data type to another, the two types
might not be compatible with each other. If the data types are compatible, then
Java will perform the conversion automatically known as Automatic Type
Conversion, and if not then they need to be cast or converted explicitly. For
example, assigning an int value to a long variable.
boolean 1
byte 8 (1 byte)
char 16 (2 bytes)
int 32 (4 bytes)
long 64 (8 bytes)
float 32 (4 bytes)
double 64 (8 bytes)
Example:
Java
// Main class
class GFG {
Output
Int value 100
Long value 100
Float value 100.0
Narrowing or Explicit Conversion
If we want to assign a value of a larger data type to a smaller data type we
perform explicit type casting or narrowing.
This is useful for incompatible data types where automatic conversion
cannot be done.
Here, the target type specifies the desired type to convert the specified
value to.
char and number are not compatible with each other. Let’s see when we try to
convert one into another.
Java
// Main class
public class GFG {
// Main class
public class GFG {
// Double datatype
double d = 100.04;
// Print statements
System.out.println("Double value " + d);
Output
Double value 100.04
Long value 100
Int value 100
Note: While assigning value to byte type the fractional part is lost and is reduced to
modulo 256(range of byte).
Example:
Java
// Main class
class GFG {
// Display message
System.out.println("Conversion of int to byte.");
// i % 256
b = (byte)i;
// Print commands
System.out.println("i = " + i + " b = " + b);
System.out.println(
"\nConversion of double to byte.");
// d % 256
b = (byte)d;
// Print commands
System.out.println("d = " + d + " b= " + b);
}
}
Output
Conversion of int to byte.
i = 257 b = 1
// Main class
class GFG {
// The Expression
double result = (f * b) + (i / c) - (d * s);
Output
result = 626.7784146484375
// Main class
class GFG {
Output
100
Note: In case of single operands the result gets converted to int and then it is
typecast accordingly, as in the above example.