Java中的类型转换

类型转换 (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中,类型转换具有两种类型:

    1. Widening Typecasting
    2. 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值