类型转换 (Typecasting)
Typecasting is a term which is introduced in all the language similar to java.
Typecasting是一个用与Java类似的所有语言引入的术语。
When we assign primitive datatype to another datatype.
当我们将原始数据类型分配给另一个数据类型时。
In java Typecasting is of two types:
在Java中,类型转换具有两种类型:
- Widening Typecasting
- Narrowing Typecasting
We will study both typecasting with examples...
我们将通过示例研究两种类型转换。
a)加宽型铸 (a) Widening Typecasting)
When we convert a smaller size datatype to the larger size datatype.
当我们将较小的数据类型转换为较大的数据类型时。
In this typecasting no data loss is there.
在这种类型转换中,没有数据丢失。
It is done by the compiler (i.e automatic). It is not done by the user.
它是由编译器完成的(即自动的)。 它不是由用户完成的。
Hierarchy of widening typecasting is described below:
扩展类型转换的层次结构描述如下:
byte → short → char → int → long → float → double
字节→短→字符→整数→长→浮点→双精度
Example of Widening Typecasting
加宽型铸件的例子
public class WideningTypecast {
public static void main(String[] args) {
int num1;
byte num2 = 20;
// We are assigning smaller datatype
// byte to larger datatype
num1 = num2;
// Print the output
System.out.println("The value of num1 is :" + num1);
}
}
Output
输出量
D:\Programs>javac WideningTypecast.java
D:\Programs>java WideningTypecast
The value of num1 is :20
b)缩小类型转换 (b) Narrowing Typecasting)
When we convert a larger size datatype to the smaller size datatype.
当我们将较大的数据类型转换为较小的数据类型时。
In this typecasting data loss is there.
在这种类型转换中,存在数据丢失。
It is not done by the compiler (i.e manually). It is done by the user.
它不是由编译器(即手动)完成的。 它是由用户完成的。
Hierarchy of narrowing typecasting is described below:
缩小类型转换的层次结构描述如下:
double → float → long → int → char → short → byte
double→float→long→int→char→short→字节
Example of Narrowing Typecasting
缩小类型转换的示例
public class NarrowingTypecast {
public static void main(String[] args) {
int num1;
double num2 = 20.8;
// We are assigning larger size datatype
// long to smaller size datatype
num1 = (int) num2;
// Print the output
System.out.println("The value of num1 is :" + num1);
}
}
Output
输出量
D:\Programs>javac NarrowingTypecast.java
D:\Programs>java NarrowingTypecast
The value of num1 is :20
翻译自: https://www.includehelp.com/java/typecasting-in-java.aspx