JAVA语言学习-Day4

异常

在程序运行过程中,意外发生的情况,背离程序本身意图的表现,都可以理解为异常

分类

  • throwable(Error,Exception)

    • Error:VirtualMachineError(虚拟机错误),OutOfMemoryError(内存溢出错误),ThreadDeath(线程锁死)

    • Exception:

      • UncheckedException(非检查异常)

        • RuntimeException:NullPointException(空指针),ArrayIndexOutOfBoundsException(数组下表越界),ArithmeticException(算数异常),ClassCastException(类型转换异常)

      • CheckedException(检查异常):IOException(IO异常)、SQLException(SQL异常)

异常处理分类

  • 抛出异常:创建异常对象

    • 异常类型

    • 异常出现时程序状态

    • ......

  • 捕获异常

    • 通过5个关键字来实现:try,catch,finally,throw,throws

System.exit(1);//终止程序运行

  • 自定义异常(继承Exception)

  • 异常链:将异常发生的原因一个一个串起来,即把底层的异常信息传给上层,这样逐层抛出来(throw Exception("",e) 或 init())

包装类

包装类可以使基本数据类型获取对象一样的特征

  • 装箱:基本数据类型 -> 包装类

    int t1 = 2;
    Interger t2 = t1;//自动装箱
    Interger t3 = new Interger(t1);//手动装箱
  • 拆箱:包装类 -> 基本数据类型

    Interger t2 = 2;
    int t4 = t2;//自动拆箱
    int t5 = t2.intValue();//手动拆箱
    1. 基本数据类型转换为字符串

      String str = Integer.toString(1);
    2. 字符串转换为基本数据类型

      int num = Integer.parseInt("1");
      int num = Integer.valueOf("1");

字符串处理类

String的常用方法

  • length();

  • indexOf();l

  • astIndexOf();

  • substring();

  • trim();

  • equals();

  • toLowerCase();

  • toUpperCase();

  • charAt();获取字符串中指定字符的位置

  • split();

  • getBytes();

字符串与byte数组间相互转换

utf-8 每个中文占3个字节

String str = "啊哈哈哈"
byte[] arr = str.getBytes(charset);
for(byte b:arr){System.out.println("b==="+b);}
String str1 = new String(arr,charset);//编码格式一致

equals和==的区别

  • equals比较字符串内容

  • ==比较内容和地址

字符串的不可变性

  1. String的对象一旦被创建,则不能修改,是不可变的

  2. 所谓的修改其实是创建了新的对象,所指向的内存空间不变

StringBuilder&StringBuffer

  • StringBuilder(性能较高):单线程推荐

  • StringBuffer(线程安全):多线程推荐

StringBuilder str = new StringBuilder("aa");
str.append("啊?");
str.append("拜拜!");
str.delete(0,2).insert(0,"AA");//删除小写,插入大写
str.replace(0,2,"AA");//直接替换
 
posted @ 2024-04-07 10:53  孟秋廿六  阅读(31)  评论(0)    收藏  举报