当前位置: 首页 > news >正文

【Java】7. 类型转换和类型判断

7. 类型转换

7.1 基本类型转换

image.png

顺箭头:隐式转换(自动)

逆箭头:强制转换(可能造成精度丢失)

byte a = 10;
int  b = a;
int c = 1000;
byte d = (byte) c;
System.out.println(d);  // -24  

7.2 包装类型与基本类型之间的转换

image.png

int a = 10;
Integer b = a;
Integer c = new Integer(20);
int d = c;
System.out.println(d);

7.3 引用类型之间的转换规则

继承特点:

  • 单继承:子类只能继承一个父类
  • Object 是其他类型直接或者间接的父类型(不写 extends 也是继承 Object)

转换规则:

  • 顺箭头:隐式转换

image.png

public class TestArray {public static void main(String[] args) {Animal a = new Cat();  // 对象还是原本的对象,只是用父类型或者祖先类型来代表它Object b = new Cat();
//        Appliance c = new Cat();  // 不合法}
}
class Animal extends Object {}
class Cat extends Animal {}
class Dog extends Animal {}
class Appliance {}
  • 逆箭头:强制转换
public class TestArray {public static void main(String[] args) {Animal a = new Cat();  // 对象还是原本的对象,只是用父类型或者祖先类型来代表它Object b = new Cat();Cat c = (Cat) a;
//        Dog d = (Dog) a;  // 类型转换错误 ClassCastExceptionAnimal d = (Animal) a;}
}
class Animal extends Object {}
class Cat extends Animal {}
class Dog extends Animal {}
class Appliance {}

7.4 类型判断

System.out.println(a.getClass()); // class com.example.demo.Cat
System.out.println(b.getClass()); // class com.example.demo.Cat
System.out.println(a instanceof Cat);  // true

7.5 字符串和数字的转换

String a = "1";
String b = "2";
System.out.println(a + b); // 12
System.out.println(Integer.parseInt(a) + Integer.parseInt(b)); // 3
http://www.lryc.cn/news/247151.html

相关文章:

  • c语言练习12周(15~16)
  • 2023-简单点-机器学习中矩阵向量求导
  • 帮管客CRM SQL注入漏洞复现
  • 如何编写自己的python包,并在本地进行使用
  • xv6 磁盘中断流程和启动时调度流程
  • Spring Security 6.x 系列(6)—— 显式设置和修改登录态信息
  • Linux的软件安装
  • 443. 压缩字符串
  • Python面经【6】
  • 2020年6月9日 Go生态洞察:VS Code Go扩展加入Go项目
  • C语言错误处理之“非局部跳转<setjmp.h>头文件”
  • 【SpringCloud】微服务架构设计模式
  • 【EI会议征稿】第三届航空航天工程与系统国际研讨会(ISAES 2024)
  • 唯创知音WT588F02A-16S录音语音芯片在宠物喂食器中的应用:小芯片,大功能
  • SELinux零知识学习三十七、SELinux策略语言之约束(1)
  • sqli-labs靶场详解(less25/25a-less28/28a)
  • 如何优化 Elasticsearch 查询性能
  • 成功的蓝图:实现长期成长与卓越表现的 6 项策略
  • 【JavaEE初阶】认识线程、创建线程
  • uniapp中uni.navigateBack返回后刷新页面数据
  • sed文本 免交互
  • 轻巧高效的剃须好工具,DOCO黑刃电动剃须刀上手
  • 第15关 K8s HPA:自动水平伸缩Pod,实现弹性扩展和资源优化
  • 接口测试工具(Jmeter)必学技巧
  • C++面试,说明const和#define的特点和区别
  • aikit 2023 3D与机械臂结合!
  • 模拟退火算法应用——求解TSP问题
  • 【LeetCode】每日一题 2023_11_28 设计前中后队列(数组/链表/双端队列)
  • python基于YOLOv8全系列模型【n/s/m/l/x】开发构建不同参数量级的钢铁产业产品智能自动化检测识别系统
  • 力扣142. 环形链表 II