这是我参与更文挑战的第9天,活动详情查看:更文挑战
运算符
算数运算符
public class Demo01{
//算数运算符
public static void main[String[] args]{
int a = 10;
int b = 20;
int c = 30;
int d = 40;
int e = 21;
System.out.println(a+b);//30
System.out.println(a-b);//-10
System.out.println(a*b);//200
System.out.println(a/(double)b);//0.5
System.out.println(e%a);//%取余 也叫模运算 即21/10=2...1 21%10=1
}
}
注意事项
1.整数除法运算,会出现下溢出现象
public class Demo02 {
public static void main(String[] args) {
int a = 4;
int b = 3;
System.out.println(a/b);//1 下溢出,余数1被舍弃
}
}
- 低于int类型(short)(byte)的运算都按int类型运算
public class Demo {
public static void main[String[] args]{
long a = 111222333222111L;
int b = 123;
short c = 10;
byte d = 8;
//
System.out.println(a+b+c+d);//Long
System.out.println(b+c+d);//Int
System.out.println(C+D);//Int
}
}
模运算
(%)表示计算除法的余数
-
0对其他数的余数为0
-
负数的余数是负数
package datatype;
public class Demo {
public static void main(String[] args) {
int i1 = 11;
int i2 = 2;
int i3 = 0;
int i4 = -11;
System.out.println(i1 % i2);//1
System.out.println(i3 % i2);//0
System.out.println(i4 % i2);//-1
}
}
自增自减
public class Demo{
public static void main(String[] args){
//++ -- 自增 自减
int a = 3;
int b = a++;//表示a先赋值给b,然后再自增1
System.out.println(a);//4
int c = ++a;//表示a先自增1,然后赋值给c
System.out.println(a);//5
System.out.println(b);//3
System.out.println(c);//5
}
}
赋值运算符
=赋值运算符表示把等号右边的赋值给左边
==才是现实意义上的等于,属于关系运算符
关系运算符
public class Demo{
public static void main (String[] args){
//关系运算符,返回的是布尔值 false true
int a = 10;
int b = 20;
System.out.println(a>b);
System.out.println(a<b);
System.out.println(a==b);
}
}
逻辑运算符
//逻辑运算符
public class Demo{
pubic static void main(String[] args){
//&&与 ||或 !非
boolean a = true;
boolean b = false;
System.out.println("a&&b:"+(a&&b));
System.out.println("a||b"+(a||b));
System.out.println("!(a&&b)"+!(a&&b));
//短路运算,进行逻辑与运算时会发生短路运算
int c = 5;
boolean d = (c<4)&&(c++<4);//这里发生了短路运算,与运算下,c<4为false,计算机就不会计算&&后面的c++<4,所以c还是5,不会自增
System.out.println(c);//5
System.out.println(d);//false
}
}
位运算符
//位运算
public class Demo{
/*
A = 0011 1100
B = 0000 1101
A&B = 0000 1100 如果A与B两个二进制数对应位上都为1,结果才为1,否则就是0
A|B = 0011 1101 如果A与B两个二进制数对应位上都为0,结果才为0,否则就是1
A^B = 0011 0001 如果A与B两个二进制数相对应位上相同就为0,不同就为1
~B = 1111 0010 取反
2*8怎么运算最快?2*2*2*2
0000 0000 0
0000 0001 1
0000 0010 2
0000 0011 3
0000 0100 4
...
0001 0000 16
<< *2
>> /2
*/
public static void main(String[] args){
//2*8怎么运算最快?2*2*2*2
System.out.println(2<<3);
}
}