類型轉換 (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