static关键字
static可以修饰成员属性,成员方法,代码块;分别叫静态属性,静态方法,静态代码块;
class Person{
//静态属性
static String name;
//静态方法
public static void eat() {
System.out.println("吃大盘鸡拌面");
}
//静态代码块
static {
System.out.println("干饭时间到!!!");
}
}
public class Demo03 {
public static void main(String[] args) {
Person.name = "cxk";
System.out.println(Person.name);
Person.eat();
}
}
静态属性和静态方法使用时均使用类名.属性或方法名;
静态代码块在类加载时就运行
优先级:静态代码块>>代码块>>构造方法
对象也可以调用静态属性和静态方法;
异常
捕捉
使用try - catch,相当于if语句,没有异常就执行try,有异常就执行catch;
try - catch捕捉异常不会影响下面的代码运行;
public class Demo04 {
public static void main(String[] args) {
int ret = 0, a = 3, b = 0;
try {
ret = a / b;//可能会发生异常的代码
System.out.println(ret);
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println("我一直在");
}
}
public class Demo05 {
public static void main(String[] args) {
int ret = 0, a = 3, b = 0;
int[] arr = new int[2];
try {
ret = a / b;
arr[2] = 4;
} catch (Exception e) {
//捕捉到那种异常就到catch中执行对应得catch
System.out.println(e.getMessage());
}
}
}
public class Demo05 {
public static void main(String[] args) {
int ret = 0, a = 3, b = 0;
int[] arr = new int[2];
try {
ret = a / b;
arr[2] = 4;
} catch (Exception e) {
//捕捉到那种异常就到catch中执行对应得catch
System.out.println(e.getMessage());
}finally {
//无论有没有异常都执行
System.out.println("我一直在");
}
}
}
抛出
throw 写在方法中,在方法中抛出一个异常,自己造一个错
throws 写在方法声明处,告知此处有异常。
import java.io.IOException;
public class Demo07 {
public static void main(String[] args) {
System.out.println(1);//正常语句
try {
System.out.println(2);//try内没有抛异常时的语句,正常执行
fun();//这个方法抛出Exception异常
System.out.println(3);//因为上一句调用抛异常了,这就不执行
}catch (Exception e){//这捕获了fun()方法抛出的异常,继续执行这里
e.printStackTrace();//这个方法向System.err输出异常调用信息
System.out.println(e.getMessage());//输出e的信息
System.out.println(4);//这也执行
}//异常处理完毕,继续执行当前后面的
System.out.println(5);//因为处理了异常,正常输出5
}
public static void fun() throws Exception {
System.out.println(6);//抛出异常的方法内部,抛出异常前的语句正常执行
try{
System.out.println(7);//try内,异常前的正常执行
throw new Exception("EEEE");
//System.out.println(8); 异常后的不可到达
}catch (IOException e){//catch捕获IOException,但是抛出的Exception是它的父类,捕获不到
System.out.println(9);//没有捕获到IOE,不执行
}finally {//无论try和catch抛出什么异常,总执行
System.out.println(10);//输出10,继续向调用方法抛异常
}
System.out.println(11);//因为前面抛了异常,这不执行
}
}
String类
String的两种声明方式
public class Demo08 {
public static void main(String[] args) {
String str1 = new String();
String str2 = new String();
str1 = "DMH";
str2 = "DMH";
String str3 = new String("DMH");
//==比较的是地址
System.out.println(str1==str2);//true
System.out.println(str1==str3);//false
//equals()方法先比较地址,在比较内容,内容一样为true
System.out.println(str1.equals(str3));//true
}
}
内存分析