Java基础学习笔记-Java数据类型转换-(~ ̄▽ ̄)~

JAVA数据类型和JS数据类型转换不一样,因为它是强类型语言嘛

类型转换规则

  • 不允许数值类型和布尔类型 转换
  • 整型、实型、字符型数据可以混合运算

类型转换分类

自动类型转换-隐式转换

  • 1.整数转换为小数
  • 2.位数少转换为位数多的
  • 总结而言,就是范围扩大了,精度没有降低

转换规则表

举例

byte a =12;
int b=23;
b = a;

强制类型转换-显式类型转换

  • 1.位数多向位数少的进行转换.
  • 2.所有的小数转换为整数
  • 3.其一般形式为:(类型)表达式。

举例

1.将一个字符转换为int,就可以知道它在Unicode表中的顺序
2.反过来,也可以将整数转换为字符型
代码举例:


public class Base {
	public static void main(String[] args) {
		System.out.println("hello, world!");
		int anInt = 3;
		System.out.println("int anInt = 3 的类型:" + getType(anInt));
		// int anInt = 3 的类型:java.lang.Integer
		byte anByte = 3;
		System.out.println("int anByte = 3 的类型:" + getType(anByte));
		// int anByte = 3 的类型:java.lang.Byte
		// ! 强制类型转换的写法
		byte newByte = (byte) anInt;
		System.out.println("byte newByte = (byte)anInt; 的类型:" + getType(newByte));
		// byte newByte = (byte)anInt; 的类型:java.lang.Byte
		char anChar = '糖'; // 注意这里要用单引号
		System.out.println("糖的Unicode编码是:" + (int) anChar);
		// 糖的Unicode编码是:31958
		int codeNum = 31958;
		System.out.println("Unicode编码31958的字是:" + (char) codeNum);
		// Unicode编码31958的字是:糖
	}

	public static String getType(Object obj) {
		return obj.getClass().getTypeName();
	}

}

在这里插入图片描述

这是我作为一名前端,第一次学习JAVA,如果本文有错误,欢迎路过的小哥哥小姐姐们帮助我纠正错误哦~~

posted @ 2022-01-25 22:54  糖~豆豆  阅读(55)  评论(0编辑  收藏  举报
Live2D