[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
1. 为什么int类型变量不能直接赋值给char类型变量?
char a = 97; -->a //为char类型变量 a 赋值常量值 97。
char b = ‘a’+3; -->d // 97+3=100,ASCII对应的字符为 d。
char c = a+3; -->报错 //无法从int类型转换为char类型,接下来让我们了解下为什么不能这样运算:
* 首先,我们先知道在jvm内存机制中,char类型数据运算是将字符在ASCII表对应的整数以int类型参与运算(可以认为’ a
'=97),常量(97)与常量(3)运算得到一个新的常量(100),常量赋值给变量(b),不存在强制转换,只要这个接受变量(b)的类型范围大于这个常量即可。
* 而变量声明时需要定义数据类型(例:char
a),内存就为这个变量划分一个char类型大小的空间,其中变量(a)的值是可变的,而常量(3)的值是不变的,两个运算得到的还是一个变量,本例中(a+3)是int类型的变量,而int类型变量(a+3)赋值给char类型变量(c)需要强制转换,因此会报错。
char c=(char)(a+3); -->d
char+char,char+int——类型均提升为int,附值char变量后,输出字符编码表中对应的字符。
2. 为什么char类型的变量可以赋值为整型数字?
* char在java中是unicode编码,Java中对char型数据,在内存中存的就是整数,对应一张ASCII码表 ,比如说字符知 ‘A’
对应的是65,字符 ‘a’ 对应的是97 ,所以char c1 = ‘A’ ; 等效于 char c1 = 65 ;
* 正是因为这样,所以字符型数据既可以作为一个字符使用,也可以作为一个整数使用,所以char型数据可以和int型数据进行运算!
比如 ‘A’ + 1 的结果如果用char型变量接收就是 ‘B’ , 用int型变量接收就是66
char c = ‘A’+1; 最后c为’B’
int i = ‘A’ + 1 ; 最后i为 66
虽然char型是以整数存储,但是和int型还是有一定区别的,表现在取值范围上,
char型 占2个字节 无符号 范围是0~65535
所以char c = 65536 就会报错了,因为越界了