题一:
class Test{
int i = 0;
Test(){
try {
go1();
}catch (Exception e){
i++; //go1() 报错,所以就运行到这一步
System.out.println("Test" + i); //2、Test1
}
}
void go1() throws Exception{
go2(); //调用完 go2() 方法后就报错 go1() 方法停止运行了
i++;
System.out.println("go1" + i);
go2();
i++;
System.out.println("go1A" + i);
}
void go2() throws Exception{
System.out.println("go2" + i); //运行到这里的 i 为 0, 1、go20
throw new Exception(); //这里主动报一个错误
}
}
public class Mian {
public static void main(String[] args) {
Test test = new Test();
System.out.println("main" + test.i); //3、main1
}
}
题二:
public class Main1 {
static int a = 10;
static boolean methodT(){
a += 5;
return true;
}
static boolean methodF(){
a-= 5;
return false;
}
public static void main(String[] args) {
//这里是调用的两个方法,关于 a值 的变化是在 retrun true 或 false 之前就执行的
//所以没有短路现象
boolean b1 =methodF() && methodT();
System.out.println("a=" + a + ",b1 = " + b1); //5,false
boolean b2 =methodT() && methodF();
System.out.println("a=" + a + ",b2 = " + b2); //5
}
}
题三:
public class Main2 {
public static void main(String[] args) {
String s1 = "qaq";
String s2 = "qaq";
String s3 = new String("qaq");
//在java中字符串的值是不可改变的,相同的字符串在内存中只会存一份,所以 s1 和 s2 指向的是同一个对象
System.out.println(s1 == s2); // true
//用构造方法构建的字符串是一个的对象,所以 s1 和 s3 不是同一个对象
System.out.println(s1 == s3);// false
//用 equals 方法比较的是字符串的内容是否相同
System.out.println(s1.equals(s2));// true
System.out.println(s1.equals(s3));// true
}
}
题四:
public class Main3 {
public static void main(String[] args) {
try{
int[] it = new int[5];
it[5] = 8;
}catch (ArithmeticException e){
System.out.println("a");
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("b");
}catch (IndexOutOfBoundsException e){
System.out.println("c");
}
try {
int i = 3/0;
}catch (ArithmeticException e){ //算数异常
System.out.println("d");
}catch (RuntimeException e){ //运行时异常
System.out.println("e");
}catch (Exception e){
System.out.println("f");
}
} //b,d
}
题五:
public class Main4 {
public static void main(String[] args) {
Test4 tst = new Test4();
System.out.println("Main" + Test4.count);//3、2
}
}
class Test4{
static int count = 0;
static {
System.out.println("static" + ++count);//1、1
}
Test4(){
System.out.println("Test" + ++count); //2、2
}
}
题六:
import java.util.TreeMap;
public class Main5 {
public static void main(String[] args) {
// TreeMap 的自然排序就是升降排序
TreeMap<Integer,String> tm = new TreeMap<>();
for (int i = 5;i>0;i--)
tm.put(i,"A" + i*2);
System.out.println(tm); // {1=A2, 2=A4, 3=A6, 4=A8, 5=A10}
}
}