Java学习 | 基础知识 - 数据类型和类型转换

    技术2022-08-16  86

    Java基本知识

    1、数据类型

    java是强类型语言,要求变量的使用要严格符合规定,所有变量都必须先定义后才能使用

    Java的数据类型分为两大类:

    基本类型(primitive type)引用类型(reference type)

    1.1 基本类型

    类别类型说明数值类型byte8位有符号整数short16位有符号整数int32位有符号整数long64位有符号整数(声明时需带L : 10L)float32位浮点数 (声明时需带F : 3.14F)double64位浮 点数字符类型char16位Unicode字符布尔类型boolean布尔值,true/false

    代码定义如下 :

    //八大数据类型 //整型 byte num1 = 1; short num2 = 1280; int num3 = 30000; long num4 = 4L; //浮点型 float num5 = 1.111F; double num6 = 123.12123; //字符类型 char name = 'a'; //布尔值 boolean isDelete = false;

    1.2 引用类型

    类接口数组

    1.3 基本类型和引用类型的区别

    基本类型的变量保存原始值,即它代表的值就是数值本身, 原始值一般对应在内存上的栈区;

    引用类型的变量保存引用值,引用值指向内存空间的地址。代表了某个对象的引用,而不是对象本身。对象本身存放在这个引用值所表示的地址的位置。被引用的对象对应内存上的堆内存区。

    基本数据类型在声明时系统就给它分配空间

    int a; //虽然没有赋值,但声明的时候虚拟机就会 分配 4字节 的内存区域, //而引用数据类型不同,它声明时只给变量分配了引用空间,而不分配数据空间: String str; //声明的时候没有分配数据空间,只有 4byte 的引用大小, //在栈区,而在堆内存区域没有任何分配 str.length(); //这个操作就会报错,因为堆内存上还没有分配内存区域,而 a = 1; 这个操作就不会报错。

    2、类型转换

    boolean不能转换成其他类型char可转换为int、long、float和double,其他类型不能转换为char其他六种类型按容量大小排序:byte < short < int < long < float < double多种数据类型混合计算的时候,系统首先自动转换为容量最大的那个类型再来继续计算转换的时候可能存在内存溢出,或者精度问题!!!

    2.1 自动转换(低–>高)

    代码测试 :

    //自动转换 byte a = 1; short b = a; int c = b; long d = c; float e = d; double f = e; System.out.println("a : " + a); //a : 1 System.out.println("b : " + b); //b : 1 System.out.println("c : " + c); //c : 1 System.out.println("d : " + d); //d : 1 System.out.println("e : " + e); //e : 1.0 System.out.println("f : " + f); //f : 1.0 //计算时自动转换成高类型 System.out.println("计算 a + e : " + (a + e)); //计算 a + e : 2.0 //精度问题 float A = 2 + 10f; float B = A - 11.9f; System.out.println(B); //0.10000038

    特殊情况 :

    如采用+=、*=等缩略形式的运算符,系统会自动强制将运算结果转换为目标变量的类型。 //如采用+=、*=等缩略形式的运算符,系统会自动强制将运算结果转换为目标变量的类型。 int a = 10; float b = 10F; a += b; System.out.println("a : " + a); //a : 20 int c = 10; float d = 10F; d += c; System.out.println("d : " + d); //d : 20.0 当运算符为自动递增运算符(++)或自动递减运算符(–)时,如果操作数为byte,short或char,类型不发生改变; public class Demo02 { public static void main(String[] args) { short a = 10; a++; System.out.println(getType(a)); //java.lang.Short a+=1; System.out.println(getType(a)); //java.lang.Short System.out.println(getType(a+1)); //java.lang.Integer } /** * 获取变量类型方法 * @param o * @return String */ public static String getType(Object o) { return o.getClass().getName().toString(); } }

    2.2 强制转换( 高–>低)

    double a = 3.14; int b = (int)a; System.out.println(b); //3

    3、类型默认值

    定义后的变量,如果不进行赋值操作,则默认值如下:

    数值类型:0

    字符类型:null

    布尔类型:false

    Processed: 0.015, SQL: 9