基本运算符/包机制
Java 语言支持如下运算符:
二元运算符
public class Demo01 {
public static void main(String[] args) {
int a = 10;
int b = 20;
int c = 30;
int d = 40;
System.out.println(a+b);
System.out.println(a-c);
System.out.println((double) a/d);
System.out.println(a*a);
}
}
public class Demo02 {
public static void main(String[] args) {
long a = 10000000000000L;
int b = 123;
short c = 10;
byte d = 8;
// cast 转换
System.out.println(a+b+c+d);//Long
System.out.println(b+c+d);//Int
System.out.println(c+d);//int
System.out.println(d);//Byte
}
}
public class Demo03 {
public static void main(String[] args) {
//关系运算符返回的结果:正确/错误 布尔值
int a = 10;
int b = 20;
int c = 22;
System.out.println(c%a);// c / a = 2 ... 1
System.out.println(a>b);
System.out.println(a<b);
System.out.println(a==b);
System.out.println(a!=b);
}
}
自增自减运算符(一元运算符)
- 自增 : ++ 自减 : –
- (Math 类)
public class Demo04 {
public static void main(String[] args) {
int a = 1;
int b = a++; // a = a + 1 执行完这行代码后,先给b赋值 再自增
int c = ++a; // a = a + 1 执行完这行代码前,先自增 再赋值
System.out.println(a);
System.out.println(b);
System.out.println(c);
//幂运算 2^3
double S = Math.pow(3,2);
System.out.println(S);
}
}
逻辑运算符 位运算符 条件运算符
public class Demo05 {
public static void main(String[] args) {
// 与 (and) 或 (or) 非(取反)
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));//如果是真则为假 如果是假则为真
// 短路运算:在逻辑与运算中如果前面的a为false 则跳过 b ,b被短路
int c = 5;
boolean d = (c<4)&&(++c<4);
System.out.println(d);
System.out.println(c);
}
}
public class Demo06 {
public static void main(String[] args) {
/*
A = 0011 1100
B = 0000 1111
--------------------
A&B = 0000 1100 //相同就是 0/1 不相同就是 0
A|B = 0011 1111 //相同为 0 就是 0 否则为 1
A^B = 0011 0011 //相同就是 0 不相同就是 1
~B = 1111 0000
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 1000 8
0001 0000 16
位运算效率极高!!!!
*/
System.out.println(2<<3);
}
}
public class Demo07 {
public static void main(String[] args) {
int a = 10;
int b = 20;
a+=b;//a=a+b
System.out.println(a);//30
a-=b;//a=a-b
System.out.println(a);//10
/*
字符串连接符 + ,若之前出现 String 类型 + 是连接作用
*/
//String 在前面 有影响
System.out.println(""+a+b);
//String 在后面 不影响
System.out.println(a+b+"");
}
}
三元运算符
public class Demo08 {
public static void main(String[] args) {
/*
三元运算符:x ? y : z
如果 x = true 则结果为 y
否则结果为 z
*/
int score = 30;
String type = score <60 ?"不及格":"及格";
System.out.println(type);
}
}
运算符的优先级
1、 该表中优先级按照从高到低的顺序书写,也就是优先级为1的优先级最高,优先级14的优先级最低。
2、 结合性是指运算符结合的顺序,通常都是从左到右。从右向左的运算符最典型的就是负号,例如3±4,则意义为3加-4,符号首先和运算符右侧的内容结合。
3、 instanceof作用是判断对象是否为某个类或接口类型,后续有详细介绍。
4、 注意区分正负号和加减号,以及按位与和逻辑与的区别
其实在实际的开发中,不需要去记忆运算符的优先级别,也不要刻意的使用运算符的优先级别,对于不清楚优先级的地方使用小括号去进行替代,示例代码:
int m = 12;
int n = m << 1 + 2;
int n = m << (1 + 2); //这样更直观
这样书写代码,更方便编写代码,也便于代码的阅读和维护。
java中的包机制
- 为了更好地组织类,Java提供了包机制,用于区别类名的命名空间。
- 包语句的语法格式为:
package pkg1[.pkg2[.pkg3...]];
- 一般利用公司域名倒置作为包名;
- 为了能够使用某一个包的成员,我们需要在Java程序中明确导入该包。使用’”import”语句可完成此功能