当前位置:网站首页>short i =1; i=i+1与short i=1; i+=1的区别
short i =1; i=i+1与short i=1; i+=1的区别
2022-07-06 11:23:00 【qq_37705525】
short i =1; i=i+1与short i=1; i+=1的区别
很典型的一到JAVA 基础面试题,上次面试遇到的,现在记录一下。
short i =1; i=i+1;
short i=1;i+=1;
这两有什么区别呢 ?
对两个容量不一样的数据类型的变量进行算术运算时,java会自动将小容量的变量进行精度提升,然后再进行运算,得到的结果类型是提升后的大容量的数据类型.如果将该结果赋值给小容量的数据类型的变量,则必须进行强制的类型转换,否则编译程序会报损失精度错.如楼主示例,用i来表示1:
short s1 = 1;
int i = 1;
首先,因为short类型是16位的,而int类型是32位的,在进行
(s1+i) 运算时,自动将s1提升到32位,然后与i相加,得到的结果是32位的,而此时
s1=s1+i; 必然报错,因为如果赋值成功,只是把低16位赋给了s1,这个虽然正是楼主想要的结果,但是编译程序却不能判定你的意图是什么.
执行强转:
s1=(short)(s1+i); 就没问题了.
s1+=i;能编译通过并得到正确结果,而 s1=s1+i; 却报错,是因为它们并不是等价的,s1+=i的方式java会对i进行窄化转换,由编译程序自动执行.
边栏推荐
- Nuc11 cheetah Canyon setting U disk startup
- 渲大师携手向日葵,远控赋能云渲染及GPU算力服务
- openmv4 学习笔记1----一键下载、图像处理背景知识、LAB亮度-对比度
- Oracle advanced (IV) table connection explanation
- 手写一个的在线聊天系统(原理篇1)
- R语言ggplot2可视化:使用ggpubr包的ggviolin函数可视化小提琴图
- In 50W, what have I done right?
- Xingnuochi technology's IPO was terminated: it was planned to raise 350million yuan, with an annual revenue of 367million yuan
- Interface test tool - postman
- AUTOCAD——中心线绘制、CAD默认线宽是多少?可以修改吗?
猜你喜欢
Binary search tree
If you have any problems, you can contact me. A rookie ~
AUTOCAD——中心线绘制、CAD默认线宽是多少?可以修改吗?
涂鸦智能在香港双重主板上市:市值112亿港元 年营收3亿美元
Master Xuan joined hands with sunflower to remotely control enabling cloud rendering and GPU computing services
Yutai micro rushes to the scientific innovation board: Huawei and Xiaomi fund are shareholders to raise 1.3 billion
倒计时2天|腾讯云消息队列数据接入平台(Data Import Platform)直播预告
Understanding disentangling in β- VAE paper reading notes
Describe the process of key exchange
助力安全人才专业素养提升 | 个人能力认证考核第一阶段圆满结束!
随机推荐
Xingnuochi technology's IPO was terminated: it was planned to raise 350million yuan, with an annual revenue of 367million yuan
助力安全人才专业素养提升 | 个人能力认证考核第一阶段圆满结束!
R语言使用rchisq函数生成符合卡方分布的随机数、使用plot函数可视化符合卡方分布的随机数(Chi Square Distribution)
2022.2.12
Video based full link Intelligent Cloud? This article explains in detail what Alibaba cloud video cloud "intelligent media production" is
Online notes
Oracle advanced (IV) table connection explanation
AcWing 3537.树查找 完全二叉树
LeetCode-1279. 红绿灯路口
[translation] a GPU approach to particle physics
Php+redis realizes the function of canceling orders over time
第五期个人能力认证考核通过名单公布
In 50W, what have I done right?
Master Xuan joined hands with sunflower to remotely control enabling cloud rendering and GPU computing services
包装行业商业供应链管理平台解决方案:布局智慧供应体系,数字化整合包装行业供应链
裕太微冲刺科创板:拟募资13亿 华为与小米基金是股东
驼峰式与下划线命名规则(Camel case With hungarian notation)
helm部署etcd集群
If you have any problems, you can contact me. A rookie ~
Simple understanding of MySQL database