类型转换

    xiaoxiao2021-03-25  106

    代码1:`package com.v512.main;

    //变量:基本数据类型(8个) vs 引用数据类型(类、接口、数组) //1.java中的变量定义的格式:数据类型 变量名 = 初始化值 class TestVeriable { public static void main(String[] args) { //2.变量得先定义,后使用 int myInt1 = 10; double d = 12.3;

    System.out.println(myInt1); System.out.println(myInt1 + d); //i1超出了其作用的范围,不可使用。 //System.out.println(i1); //3.整型:byte(-128~+127) short int(默认类型) long byte b1 = 12; //byte b2 = 128; short s1 = 128; int i1 = 12; //定义long型变量,值的末尾加“L”或“l” long l1 = 2134123351345325L; System.out.println(l1); //4.浮点型(带小数点的数值):float double(默认类型) double d1 = 12.3; //声明float类型的浮点型数据,末尾要加“F”或者“f” float f1 = 12.3F; System.out.println(f1); //5.字符型(=两个字节):char 只能表示一个字符(英文、中文、标点符号、日文、。。。) char c1 = 'a'; //char c2 = 'ab'; String str = "ab"; char c3 = '中'; String str1 = "中国"; //可以表示转义字符 char c4 = '\t'; char c5 = '\n'; System.out.println("abc" + c5 + "def"); //了解 char c6 = '\u1234'; System.out.println(c6); //6.布尔类型:boolean 只能够取值为true 或 false 。不能取值null boolean bool1 = true; if(bool1){ System.out.println("佟老师是个\"帅\"哥"); }else{ System.out.println("你在说谎!"); } } public void method1(){ int i1 = 10; System.out.println(i1); }

    }

    代码2:package com.v512.main;

    /* 变量之间的运算:(不考虑boolean。剩下:char byte short int long float double) 1.自动类型转换 2.强制类型转换 */ class TestVeriable1{ public static void main(String[] args){ //1.自动类型转换:当容量小的数据类型与容量大的数据类型做运算时,容量小的会自动转换为 //容量大的数据类型:char,byte,short ===>int ===>long ===>float===double int i1 = 12; short s1 = 2; int i2 = i1 + s1; float f1 = 12.3F; float f2 = f1 + i2; //float d1 = f2 + 12.3;

    long l = 12L; float f3 = l; System.out.println(i2); System.out.println(f2); char c1 = 'a';//97 c1 = 'A';//65 int i3 = c1 + 1; System.out.println(i3); //需要注意的:当char\byte\short之间做运算时,默认的结果为int类型 short ss1 = 12; byte bb1 = 1; char cc1 = 'a'; //short ss2 = ss1 + bb1; int ii1 = ss1 + bb1; //char cc2 = cc1 + bb1; int ii2 = cc1 + bb1; short ss2 = 11; //short ss3 = ss1 + ss2; //2.强制类型转换:容量大转换为容量小的.要使用强制类型转换符:() //强制类型转换的问题:导致精度的损失 long l1 = 12345L; int m1 = (int)l1; System.out.println(m1); byte by1 = (byte)m1; System.out.println(by1); //平时常用的字符串,也是一种数据类型:String String nation = "我是一个中国人"; System.out.println(nation); //字符串与基本数据类型之间的运算:只能是连接运算:+。得到的结果仍为一个字符串 String str = "abc"; String str1 = str + m1;//abc12345 System.out.println(str1); //题目: String st1 = "hello"; int myInt1 = 12; char ch1 = 'a';//97 System.out.println(str1 + myInt1 + ch1);//hello12a System.out.println(myInt1 + ch1 + str1);//109hello System.out.println(ch1 + str1 + myInt1);//ahello12 String st2 = "12"; st2 = 12 + ""; System.out.println(st2); }

    } `

    转载请注明原文地址: https://ju.6miu.com/read-34146.html

    最新回复(0)