zoukankan      html  css  js  c++  java
  • Java中int型和char型数据转换问题

    众所周知,Java中int型和char型数据不像C语言中那样可以任意转换,即不可以将一个int型变量自动转换为char型,如下面代码中的演示:

    public class TestSort{
     public static void main(String args[]){
      int x='a';//不会产生编译错误,因为'a'赋给x是隐式转换
      System.out.println(x);
      char ch=x;//会产生编译错误,因为x类型比ch优先级高,必须强制类型转换,但是在C语言中这样是可以的
      System.out.println(ch);
     }
    }

    但是看下面的代码:

    public class TestSort{
     public static void main(String args[]){
      int x='a';
      System.out.println(x);
      char ch=97;//不会产生编译错误
      System.out.println(ch);
     }
    }

    上面代码不会产生任何编译错误,此处的97虽然在数学意义上是一个整数(注意整数和整型的区别),但是java语言中它被作为常数来对待,也就是说一个值为97的int型变量和97本身是不同的概念,97在没有和某个类型关联以前赋给ch是完全没有错误的。其实我们用char ch='a'给ch赋值的时候,'a'在内存中的存储值就是97。

  • 相关阅读:
    my first android test
    VVVVVVVVVV
    my first android test
    my first android test
    my first android test
    ini文件
    ZZZZ
    Standard Exception Classes in Python 1.5
    Python Module of the Week Python Module of the Week
    my first android test
  • 原文地址:https://www.cnblogs.com/wei1/p/9582132.html
Copyright © 2011-2022 走看看