2021-11-10 Java学习

学习视频:https://www.bilibili.com/video/BV18J411W7cE?p=1

类型转换

自动类型转换:

把一个表示据范围小的数值或变量赋值给数据范围大的变量

 

double d=10;     //正确

char c=10;         //错误

强制类型转换:(存在数据丢失)

把一个表示数据范围大的数值或者变量赋值给另一个表示数据范围小的变量

格式:目标数据类型变量名=(目标数据类型)值或变量

eg:    int k=(int)88.88

运算符:

算数运算符:+ - * /  %加减乘除取余

字符的加操作:

 算数表达式中包含多个基本数据类型的值时,整个算数表达式会自动进行提升。

提升规则:

 public class HelloWorld{
    public static void main(String[] args){
        //定义两个变量
        int i = 10 ;
        char c = 'A';            //'A'的值是65
        System.out.println(i + c);
        c = 'a' ;                //'a'的值是97
        System.out.println(i + c);
        c = '0';                //'0'的值是49
        System.out.println(i + c);
        
        //char ch = i + c;
        //char类型会被自动提升为int类型
        int j = i + c;
        System.out.println(j);
    }
}

 字符串加操作:

当“+”操作中出现字符串时,“+”表示字符串连接,

"helloworld"+666

从左往右,出现字符串就是连接字符串,否则为算数运算。

 6+666+"helloworld"

public class demo{
    public static void main(String[] args){
        System.out.println("hello"+"world");
        System.out.println("helloworld"+666);
        System.out.println(666+"helloworld");
        System.out.println(6+666+"helloworld");
        System.out.println("helloworld"+666+6);
    }
}


赋值运算符:(=)

= :

int  i = 10;   //将10赋值给i

+= :(隐含了强制类型转换)

i +=  20; //值为30 

i = i + 20 ; //值为30

short s = 10;

s += 20;        //√

s = s + 20; //×  s为short类型,20为int类型

自增自减运算符:

++     变量的值加一

--       变量的值减一

int j = ++i;  先运算再赋值

int k = i++;  先赋值再运算

猜你喜欢

转载自blog.csdn.net/qq_54525532/article/details/121254815