数据类型2

数据类型

布尔值:只能取2个值,true和false;

 public class Demo4 {
     public static void main(String[] args) {
         boolean b1 = true;
         System.out.println(b1);
         boolean a = true;
         if (a){
             System.out.println("不能\"参加\"聚会!\\n很遗憾");
        }else{
             System.out.println("多参加聚会!");
        }
    }
 }
 

 

数据类型的运算规则

7种变量之间的运算

自动类型转换

结论:当容量小的数据类型的变量与容量大的数据类型的变量做运算时,结果自动提升为容量大的数据类型。

说明:容量大小是指数的范围大小;比如float容量要大于long的容量

byte,char,short-->int-->long-->float-->double

特别:当byte,char,short三种类型额变量做运算时,结果为int

 public class Demo5 {
     public static void main(String[] args) {
         byte b1 = 2;
         int i1 = 129;
         int i2 = b1+i1;
         System.out.println(i2);
         float f = b1+i1;
         System.out.println(f);
         short s1 = 123;
         double d1 = s1;
         System.out.println(d1);
         //*************************************************
         char c1 = 'a';
         int i3 = 10;
         int i4 = c1+i3;
         System.out.println(i4);
 
         short s2 = 10;
         //char c2 = c1+s2;//编译不通过
         //System.out.println(c2);
         byte b2 = 10;
         //char c3 = c1+b2;//编译不通过
         //short s3 = b2+s2;//编译不通过
         //short s4 = b1+b2;//编译不通过
         //*************************************************
 
    }
 }
 

 

强制类型转换

自动类型转换的逆运算

1.需要使用强转符:()

2.注意点:强制类型转换,可能导致精度损失

 public class Demo7 {
     public static void main(String[] args) {
         // 编码情况1
         long l = 123123;
         System.out.println(l);
         //编译失败:过大的整数
         //long l1 = 51135151566111l;
         long l1 = 51135151566111l;
         System.out.println(l1);
 
 
         //****************************
         //编译失败
         //float f1 = 12.3;
         float f1 = (float) 12.3;
         // 编码情况2
         //整型常量,默认为int型
         //浮点型常量,默认为double型
         byte b = 12;
         //byte b1 = b+1;//编译失败
         //float f1 = b+12.3;//编译失败
    }
 }
 
 public class Demo6 {
     public static void main(String[] args) {
         //精度损失1
         double d1 = 12.3;
         int i1 = (int)d1;//截断操作
         System.out.println(i1);
         //精度损失2
         int i2 = 128;
         byte b = (byte) i2;
         System.out.println(b);//-128
    }
 }
 

 

String类型的变量使用

1.string属于引用数据类型

2.使用string类型变量时,使用一对""

3,。String可以和8中基本数据类型变量运算,且运算只能是连接运算:+

4.运算的结果任然是String类型。

 public class Demo8 {
     public static void main(String[] args) {
         String s1 = "Hello World!";
         System.out.println(s1);
         String s2 = "a";
         String s3 = "";
         System.out.println(s2);
         System.out.println(s3);
 
         //char c1 = '';//编译不通过
         int number = 1001;
         String numberStr = "学号:";
         String info = numberStr+number;// + 连接运算
         System.out.println(info);
 
         boolean b1 = true;
         String info1 = info+b1;// + 连接运算
         System.out.println(info1);
 
    }
 }
 

 

posted @ 2021-08-04 17:55  开心的菜鸟  阅读(83)  评论(0)    收藏  举报