Java运算符
Java语言支持如下运算符:
- 算数运算符:+,-,*,/,%,++,–
- 赋值运算符:=
- 关系运算符:<,>,<=,>=,==,!= ,instanceof
- 逻辑运算符:&&,||,!
- 位运算符:&,|,^,~,>>,<<,>>>(了解!!!)
- 条件运算符:?:
- 拓展赋值运算符:+=,-=,*=,/= (偷懒)
//二元运算符
/*
* Ctrl+D:复制当前行到下一行;
* */
int a=10;
int b=20;
int c=10;
int d=10;
System.out.println(a+b);
System.out.println(a-b);
System.out.println(a*b);
System.out.println(a/(double)b);//int(0.5)=0
long l=123456789L;
int i=123;
short s=10;
byte by=88;
double dou=3.1415926;
float flo=33.4455f;
System.out.println((String)(l+i+s+by));//long
//cannot cast 'long' to 'java.lang.String'
System.out.println((String)(i+s+by));//int
//Inconvertible types; cannot cast 'int' to 'java.lang.String'
System.out.println((String)(s+by));// short+byte=int
//cannot cast 'int' to 'java.lang.String'
System.out.println((String)(l+dou));// long+double=double
// cannot cast 'double' to 'java.lang.String'
System.out.println((String)(l+flo));// long+float=float
//cannot cast 'float' to 'java.lang.String'
//关系运算符
int a=10;
int b=20;
System.out.println(a>b); //false
System.out.println(a<b); //true
System.out.println(a==b); //false
System.out.println(a!=b); //true
//一元运算符
//++ --
int ia = 2;
int ib = ia++; /*先给ib赋值,再自增加1*/
System.out.println(ia);
System.out.println(ib);
int ic = ++ia;/*先自增加1,再给ib赋值*/
System.out.println(ic);
//逻辑或运算
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错误。行
System.out.println(d); //程序直接停止。C++不载执行
System.out.println(c);
//位运算
/*
* A=0011 1100
* B=0000 1101
*
* A&B=0000 1100 与运算(都为1,才是1,其余为0)
* A|B=0011 1101 或运算(有1就为1,)
* A^B=0011 0001 异或运算(相同为0,不同为1)
* ~B =1111 0010 非运算(按位取反)
*
*
* 面试题 如何计算2*8=16 最快
* 2*2*2*2
*
* 位运算 效率极高
* 左移 << 表示 *2
* 右移 >> 表示 /2
*
* 例如:
* 0000 0000 0
* 0000 0001 1
* 0000 0010 2 0000 0011 3
* 0000 0100 4 0000 0110 6
* 0000 1000 8
* 0001 0000 16
*/
System.out.println(2<<3); //左移3位
int ia= 10;
int ib= 20;
ia+=ib; // ia=ia+ib 10+20=30
ia-=ib; // ia=ia-ib 30-20=10
System.out.println(ia);
//面试题
//字符串连接符 “+”,String
System.out.println(""+ia+ib); //输出:1020
System.out.println(""+(ia+ib)); //输出:30
System.out.println(ia+ib+""); //输出:30
//三元运算符
//x ? y :z
//如果x为true,则结果为y,否则结果为z
int score=50;
String type=score<60 ? "不及格":"及格";
System.out.println(type);
PS:
(本文为根据狂神视频学习,所做笔记。手敲出来方便日后复习地址)