下表整理了实际使用过程中常用的关键字,大致按照使用频率倒序。
修饰类:
| 关键字 | 作用对象 | 含义 |
|---|---|---|
| public | 类、方法、变量 | 表示一个类、方法或变量是公开的,可以在不同包中访问。 |
| protected | 类、方法、变量 | 表示一个类、方法或变量是受保护的,同包可访问,可被继承(常用) |
| private | 类、方法、变量 | 表示一个类、方法或变量是私有的,只有本类内部可访问,不可继承,不可覆盖。 |
| abstract | 类、方法 | 表示一个类、方法是抽象的,需要子类来实现,抽象类中可包含抽象和非抽象方法。 |
| final | 类、方法、变量 | 表示一个类、方法或变量是不可变的,比如包装类类,final修饰的内容不可变、不可被继承或覆盖。 |
| static | 类、方法、变量 | 表示一个类、方法或变量是静态的,即是属于类而不是类的实例的。 |
| synchronized | 方法、代码块 | 表示一个方法或代码块需要同步执行。 |
| volatile | 变量 | 常用于保证变量在多线程下的可见性。 |
语句类:
| 关键字 | 作用对象 | 含义 |
|---|---|---|
| for | 语句 | 循环 |
| return | 语句 | 方法返回 |
| try | 语句 | 包裹可能会发生异常的语句 |
| catch | 语句 | 发生异常后进行处理的语句 |
| finally | 语句 | try/catch执行完后执行的语句 |
| switch | 语句 | 分支 |
| break | 语句 | 结束循环, |
| continue | 语句 | 结束本次循环,继续下一次循环 |
| while | 语句 | 循环 |
| do | 语句 | 和while搭配使用,do{…}while(条件) |
| instanceof | 语句 | 判断某个对象是否实现了某个接口 |
数据类型类:
| 关键字 | 作用对象 | 含义 |
|---|---|---|
| int | 变量 | 整型,32位,4字节 |
| long | 变量 | 长整型,64位,8字节 |
| double | 变量 | 双精度浮点型,64位,8字节 |
| float | 变量 | 单精度浮点型 ,32位,4字节 |
| boolean | 变量 | 布尔型,true或false |
| byte | 变量 | 字节型,8位,1字节 |
| void | 方法 | 表示方法返回为空 |
用于接口、类或类之间关系的:
| 关键字 | 作用对象 | 含义 |
|---|---|---|
| class | 类 | 声明一个类 |
| interface | 接口 | 声明一个接口 |
| extends | 类、接口 | 继承一个类或者接口 |
| implements | 类 | 实现一个接口 |
当没有异常时:
public class TryCatchFinally01 {
public static void main(String[] args) {
try {
System.out.println("try");
}catch (Exception e){
System.out.println("catch");
}finally {
System.out.println("finally");
}
}
}
输出:
try
finally
当抛出异常时:
public class TryCatchFinally01 {
public static void main(String[] args) {
try {
System.out.println("try");
throw new RuntimeException("test exception");
} catch (Exception e) {
System.out.println("catch");
} finally {
System.out.println("finally");
}
}
}
输出:
try
catch
finally
当强制退出时:
public class TryCatchFinally01 {
public static void main(String[] args) {
try {
System.out.println("try");
System.exit(0);
throw new RuntimeException("test exception");
} catch (Exception e) {
System.out.println("catch");
} finally {
System.out.println("finally");
}
}
}
输出:
try
总结:
除了使用System.exit()强制退出系统时,finally都会被执行,另外即使发生Error级别的错误(如OOM),finally中的代码也会执行
看如下代码:
public class TryCatchFinally02 {
public static void main(String[] args) {
System.out.println(getValue());
}
public static int getValue() {
int n = 0;
try {
return 1 / n;
} catch (Exception e) {
return ++n;
} finally {
return ++n;
}
}
}
输出:
2
分析:
(1) 首先执行try中的1/n,除数为0,抛出异常,进入catch
(2) 然后catch中执行++n,结果为1
(3) 最后执行finally中++n,结果为2
总结:
当try、catch、finally都存在retun时,且return是可执行语句时,依次执行,执行顺序为:try中的return → catch中的return → finally中的return,最后的返回以finally中的return为准。