1.static关键字
1.1static修饰成员变量
语法格式: static 数据类型 变量名;
调用时直接使用 类名.变量名 直接调用
1.2static修饰成员方法
语法格式:public static 返回值 方法名字 (){}
调用时用 类.方法名(); 调用;
1.3static修饰代码块
语法格式
static {
语句体
}
只要静态代码块所在的这个类加载,那么静态代码块就会执行
执行顺序 :静态代码块—>构造代码块—>构造方法
2.异常
Exception: 异常,代表程序在运行过程中,发生了不可预期的事件。可以使用Java来解决,让他继续执行下去。
异常分为运行时异常和编译时异常
2.1异常的捕捉
语法格式
try {
可能会出现异常的代码
} catch (异常对象) {
//针对与异常的处理方案
}
异常类型通常用所有异常的父类Exception代替
package com.qfedu.Exception;
public class Demo02 {
public static void main(String[] args) {
// TODO Auto-generated method stub
test(5, 0);
}
public static void test(int a, int b) {
try {
System.out.println(a / b);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
try - catch -finally语法格式(无用)
try {
可能会出现异常的代码
} catch (异常对象) {
//针对异常的处理方案
} finally {
代码块//无论有没有异常,都要执行的
}
2.2异常的抛出
在方法的声明处用throws 异常类型 来抛出异常,告知调用方法者此处有异常,一旦抛出异常,则代码结束运行
throw可以在方法中抛出异常
例如
package com.qfedu.Exception;
import java.io.FileNotFoundException;
public class Demo01 {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
test(0);
}
public static void test(int a) throws FileNotFoundException {
if (a == 0) {
throw new FileNotFoundException();
}
}
}
3.String类
3.1String类型的两种声明方式
String str = "狗蛋";
String str1 = "狗蛋";
String str2 = new String("狗蛋");
String str3 = new String("狗蛋");
第一种方式字符串存在堆区的常量池中,str和str1指向"狗蛋"这个字符串,因此str和str1的内存地址和值都相同
第二中方式是在堆区分别额外开辟的内存空间,因此str2合str3的内存地址不同,值相同