Data type casting
In this chapter you will learn:
Not compatible type and casting
char
and boolean
are not compatible with each other.
public class Main {
public static void main(String[] argv) {
char ch = 'a';
int num = 99;
ch = num;//from j av a 2s . co m
}
}
Compiling the code above will generate the following error message.
To make it work we have to add casting before the assignment.
public class Main {
public static void main(String[] argv) {
char ch = 'a';
int num = 99;
ch = (char)num;
}/*from j a va 2s .co m*/
}
Casting Incompatible Types
A narrowing conversion is to explicitly make the value narrower. A cast is an explicit type conversion. It has this general form:
(target-type) value
target-type
specifies the desired type.
The following code casts int
type value to byte
type value.
public class Main {
public static void main(String[] argv) {
int a = 1234;
byte b;//from j a v a2 s . c om
b = (byte) a;
System.out.println("a is " + a);
System.out.println("b is " + b);
}
}
The output:
Truncation happens when assigning a floating-point value to an integer value.
For example, if the value 1.23
is assigned to an integer, the resulting value will
simply be 1
.
public class Main {
/*j a v a2s .c o m*/
public static void main(String args[]) {
byte b;
int i = 1;
double d = 1.123;
System.out.println("Conversion of double to int.");
i = (int) d;
System.out.println("d: " + d + " i: " + i);
System.out.println("Conversion of double to byte.");
b = (byte) d;
System.out.println("d: " + d + " b: " + b);
}
}
This program generates the following output:
Next chapter...
What you will learn in the next chapter:
- What is Automatic Type Promotion in Expressions
- How to fix the compile-time errors caused by automatic type promotions
- What is Java Type Promotion Rules
Home » Java Tutorial » Primitive Data Types