运算符
- 运算符: 对变量和常量进行操作的符号
- 表达式: 用运算符把常量或变量连接起来的式子
- 算数运算符: +, -, *, /,%
- 自增自减运算符: ++, –
- 赋值运算符: =, +=, -=…
- 关系运算符:<, <=, ==, >, >=
- 逻辑运算符:&&, ||, &, |, ^
- 三元运算符: (关系表达式)? 表达式1:表达式2
重点理解:
1.字符串拼接
String str=”str”;
System.out.println(3 + 4 + str + 3 +4);
输出结果为: 7str34.
计算从左往右进行,且有字符串参与的+运算为字符串拼接,所以先计算左侧3+4,再与str拼接,再分别与3和4拼接。
2.++和- -
int x = 5;
int y = x++ + ++x -x++ - --x + x++*5;
//x : 5/6 + 7/7 -7/8 – 7/7 + 7/8
//y = 5 + 7 – 7 – 7 + 7 * 5
System.out.println(x);// x=8
System.out.println(y);// y=33
++在变量的后面,先把变量做操作,然后变量再++, ++在变量的前面,先变量++, 然后再做操作
3.&&, || 与 &, |
Int x = 3;
Int y = 4;
If(x++>3 && y++>4) { }
System.out.println(x);// x=4
System.out.println(y); // y=4
If(x++>=3 || y++>4) { }
System.out.println(x); // x=5
System.out.println(y); // y=4
If(x++>3 && y++>4) { }
System.out.println(x); // x=6
System.out.println(y); // y=5
If(x++>=3 || y++>4) { }
System.out.println(x); // x=7
System.out.println(y); // y=6
只有 & ,和 | 参与的表达式,整句都会进行运算,而 && 遇到假,|| 遇到真则不再进行后续的判断,为了提高程序的运行效率,通常都会用 && 和 || .
4.三元运算符
Int x = 3;
Int y = 4;
Int z = x > y ? x : y;
System.out.println(y); // z = y
(关系表达式)?表达式1:表达式2;
如果关系表达式条件为true,就运行表达式1;如果条件为false,就运行表达式2
流程控制语句
- 顺序结构: 程序中最简单最基本的流程控制,无特定语句,按照代码先后顺序依次执行
- 选择结构: if语句, switch语句
- 循环结构: for, while, dowhile, foreach
重点理解:
- switch(表达式) 中, 表达式的取值:byte,short,int,char, JDK5以后可以是枚举类型,JDK7以后可以是String类型
- switch中不写break的情况
int num = 1;
int count = 0;
switch(num) {
case 1:
count++;
case 100:
count++;
case 102:
count++;
break;
case 200:
count++;
default:
count++;
}
count最终值为3;
当第一个case 0成立时,后面的case均不会进行判断,直接执行里面的内容,直到遇到case102中的break结束.
3. do…while循环至少会执行一次循环体,for循环和while循环只有在条件成立的时候才会去执行循环体
4. break语句:跳出当前循环 / 跳出当前的switch ;continue语句:跳出本次循环
5. 标签的使用
flag: for(int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if(j == 3) break flag;
}
}
在j = 3 时,就可以跳出flag标签所标记的for循环, continue同理.