static、异常和String类型的两种声明方式

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的内存地址不同,值相同

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值