public static void main(String[] args) {
int x = 3;
byte b = 4;
x = b + x;
System.out.println(x); //7
}

我们把上面例子改一下,改成如下的程序,会报错,可能损失精度,因为type比int小,从大往小可能损失精度,但我们知道结果为7,在byte的范围之内,但它就是报错了,怎么办呢
public static void main(String[] args) {
int x = 3;
byte b = 4;
b = b + x;
System.out.println(x); //报错饿了
}
碰到这种情况,就需要用到强制类型转换了,修改代码如下:
public static void main(String[] args) {
int x = 3;
byte b = 4;
b = (byte)( b + x);
System.out.println(b); //7
}
再看一张图,加深一下印象

上面的例子强制转换还在范围之内,但如果超国了范围之内呢?那么就丢失精度了。
public static void main(String[] args) {
byte b = (byte)(123 + 12);
System.out.println(b); //-121
}
System.out.println(‘a’);
System.out.println(‘a’+1);
通过看结果知道’a’的值是多少,由此引出ASCII码表
例子:
public static void main(String[] args) {
System.out.println('a' + 1); //98,因为有ASCII码表,a字符对应的是int类型的97
System.out.println((char)('a' + 1)); //b
System.out.println("hello"+'a'+1); //helloa1 任何数据类型用+与字符串相连接都会产生新的字符串
System.out.println('a'+1+"hello"); //98hello
System.out.println(" 5 + 5 = " + (5 + 5)); // 5 + 5 = 10
}
例子:
public static void main(String[] args) {
System.out.println(10 / 3); //3 整数相除结果只能是整数
System.out.println(10 / 3.0); //3.3333333 如果想得到小数,把其中一个数变成小数,另一个数在运算的时候会自动类型提升
System.out.println(-5 % 5); //0
System.out.println(13 % -5); //3
}
例子:
public static void main(String[] args) {
//单独使用
int c = 3;
//c++; //a = a + 1;
++c; //a = a + 1;
System.out.println(c); //4
//参与运算使用
int a = 3;
int b;
b = a++; //当++在变量后面的时候,会先将变量中的值取出做赋值操作,然后再自身加1
//b = ++a; //当++在变量前面的时候,会先自身加1,然后在将结果赋值
System.out.println("a = " + a); //a = 4
System.out.println("b = " + b); //b = 3
}
a:基本的赋值运算符:=
b:扩展的赋值运算符:+=,-=,*=,/=,%=
无论你的操作是简单还是复杂,结果是boolean类型。
“==“不能写成”=”。
A:逻辑运算符有哪些
B:案例演示
逻辑运算符的基本用法
注意事项:
C:结论:
&逻辑与:有false则false。
|逻辑或:有true则true。
^逻辑异或:相同为false,不同为true。
!逻辑非:非false则true,非true则false。
例子:
public static void main(String[] args) {
//(关系表达式) ? 表达式1 : 表达式2;
int x = 10;
int y = 5;
int z;
z = (x > y) ? x : y; //括号的值是true,把x赋值给z,为false,把y赋值给z
System.out.println("z = " + z); //z = 10
}