Java异常处理与String常用方法

一、异常分类

异常:非正常情况

异常体系:Throwable:throwable类是Java语言中所有错误和异常的超类

throwable:

Error:错误,不用程序员控制,一般虚拟机生成并脱出

Exception:异常,需要程序员通过调整代码控制解决 一旦程序遇到异常,程序将无法运行|无法继续运行

Exception

编译时异常|检查时异常:编译期间发生的异常 ,如果不处理,程序无法运行--->只能通过标准的异常处理方案 如:

InputStream is = new FileInputStream("D://test.txt");

运行时异常:异常发生在程序运行期间,如果不处理,程序无法继续运行 通过标准的异常处理方案 | 增强程序健壮性方式if

常见的五种运行异常:

1、空指针异常 java.lang.NullPointerException

2、类型转换异常 java.lang.ClassCastException

3、数组长度负数异常 java.lang.NegativeArraySizeException

4、数组索引越界异常 java.lang.ArrayIndexOutOfBoundsException

5、数学异常 java.lang.ArithmeticException

二、标准异常处理方案

异常抛出 throws:将异常抛出到方法上,有调用方法的位置处理

异常捕获:直接捕获异常,并提出处理方案

try{
    有可能出现异常的代码段;
}catch(异常类型1  引用){
    执行对应的语句体;
}catch(异常类型2 引用){
    .....
}finally{
    无论try..catch结构是否遇到异常,结束之前都会执行的代码段
}

try后的代码段如果一旦遇到异常,后续的代码不再执行,直接从上到下判断catch,执行对应catch的语句体

try后的代码段如果执行完毕都没有遇到异常,不会判断catch

多个catch,异常类型小的上面,类型大的在下面

finally中一般定义资源的关闭等相关代码

三、自定义异常:异常也是类

运行时异常需要直接或间接继承自RuntimeException

编译时异常,不能继承自RuntimeException,但是需要继承自Exception

制造异常:throw

public class Excception003 {
    public static void main(String[] args) throws AgeException {
        User u=new User();
        u.setName("zhangsan");
        int age =-15;
        /*
        运行时异常
​
        if(age>=0 && age<=30){
            u.setAge(age);
        }else {
            u.setAge(18);
        }
​
         */
        //编译时异常
        try{
            u.setAge(age);
        }catch(AgeException e){
            try{
                System.out.println("设置年龄默认值为18");
                u.setAge(18);
            }catch (AgeException ex) {
                e.printStackTrace();
            }
        }
        System.out.println(u);
​
    }
}
class AgeException1 extends Exception{
    public AgeException1(){
​
    }
    public AgeException1(String message){
        super(message);
    }
​
}
class User001 {
    private String name;
    private int age;
​
    public User001() {
    }
​
    public String getName() {
        return name;
    }
​
    public void setName(String name) {
        this.name = name;
    }
​
    public int getAge() {
        return age;
    }
​
    public void setAge(int age) throws AgeException1 {
        if (age < 0 || age > 30) {
            throw new AgeException1(age + "不合法");
        }
        this.age = age;
    }
​
    @Override
    public String toString() {
        return "User001{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

四、字符串

字符串:字符串序列

String:不可变的字符序列

StringBuilder:可变的字符序列,线程不安全|不同步

StringBuffer:可变的字符序列,线程安全|同步

执行效率:StringBuilder>StringBuffer>String

常用频率 : String > StringBuilder > StringBuffer

三者区别 : 1)是否可变 2)线程安全 3)执行效率

String : String类表示字符串

Java 程序中的所有字符串文字,例如"abc" ,都是作为此类的实例实现的。

String的对象的表示方式 :

1.字符串文字 "...." -->在字符串常量池中 String s1="";

2.new 创建String类型对象-->在堆内存中 String s2=new String("");

!!以下代码是否存在对象,存在几个,分别在内存的什么位置?

String s1 = "abc"; 1个 字符串常量池中"abc"

String s2 = new String("haha"); 2个 new->堆内存中

"haha"-->字符串常量池中

String s3 = new String("abc"); 1个 new->堆内存中 常量池中的字符串不能重复

String底层逻辑:

jdk及之前版本:private final char value[];

jdk8之后:private final byte[] value;

public class Class001_String {
    public static void main(String[] args) throws UnsupportedEncodingException {
        //String()
        //初始化一个新创建的String对象,使其表示一个空字符序列。
        String s1 = new String();
        System.out.println(s1);
​
        //String(String original)
        //初始化一个新创建的String对象,使其表示与参数相同的字符序列; 换句话说,新创建的字符串是参数字符串的副本。
        //String(StringBuffer buffer)
        //分配一个新字符串,该字符串包含字符串缓冲区参数中当前包含的字符序列。
        //String(StringBuilder builder)
        //分配一个新字符串,该字符串包含字符串构建器参数中当前包含的字符序列。
        String s2 = new String("abc");
        System.out.println(s2);
​
        //String(char[] value)
        //分配一个新的String以便它表示当前包含在字符数组参数中的字符序列。
        char[] chars = {'a','b','c','d','e'};
        System.out.println(new String(chars));
​
        //String(char[] value, int offset, int count)
        //分配一个新的String ,其中包含来自字符数组参数的子数组的字符。
        System.out.println(new String(chars,0,3));
​
        //String(byte[] bytes)
        //通过使用平台的默认字符集解码指定的字节数组来构造一个新的String 。
        byte[] arr = "你好".getBytes("GBK");  //gbk->1个汉字2个字节   utf-8->1个汉字3个字节
        System.out.println(Arrays.toString(arr));
​
        System.out.println(new String(arr)); //默认UTF-8
        //String(byte[] bytes, String charsetName)
        //通过使用指定的String解码指定的字节数组来构造一个新的String 。
        System.out.println(new String(arr,"gbk"));
​
        //String(byte[] bytes, int offset, int length)
        //通过使用平台的默认字符集解码指定的字节子数组来构造一个新的String 。
        //String(byte[] bytes, int offset, int length, String charsetName)
        //通过使用指定的字符集解码指定的字节子数组来构造一个新的String 。
        System.out.println(new String(arr,2,2,"gbk"));
        
        //String的常用方法
        String str1 = "jintiannikuailema";
        String str2 = "Jintiannikuailema";
​
        //char charAt(int index 返回指定索引处的char值。
        System.out.println(str1.charAt(5));
​
        //int codePointAt(int index)
        //返回指定索引处的字符(Unicode 代码点)。
        System.out.println(str1.codePointAt(5));
​
        //int codePointBefore(int index)
        //返回指定索引之前的字符(Unicode 代码点)。
        System.out.println(str1.codePointBefore(6));
​
        /*
            x.compareTo(y)
            int compareTo(String anotherString) 按字典顺序比较两个字符串。
                返回值  :
                    0 : x=y
                   <0 : x<y
                   >0 : x>y
         */
        System.out.println(str1.compareTo(str2));
​
        //int compareToIgnoreCase(String str)
        //按字典顺序比较两个字符串,忽略大小写差异。
        System.out.println(str1.compareToIgnoreCase(str2));
​
        //String concat(String str)
        //将指定的字符串连接到此字符串的末尾。
        System.out.println(str1.concat(str2));
        System.out.println(str1);
​
        //boolean contains(CharSequence s)
        //当且仅当此字符串包含指定的 char 值序列时才返回 true。
        System.out.println("王鹏".contains("鹏"));
​
        //boolean equals(Object anObject)
        //将此字符串与指定对象进行比较。
        //boolean equalsIgnoreCase(String anotherString)
        //将此String与另一个String进行比较,忽略大小写考虑。
        System.out.println(str1.equals(str2));
        System.out.println(str1.equalsIgnoreCase(str2));
​
        //boolean endsWith(String suffix)
        //测试此字符串是否以指定的后缀结尾。
        //boolean startsWith(String prefix)
        //测试此字符串是否以指定的前缀开头。
        //boolean startsWith(String prefix, int toffset)
        //测试从指定索引开始的此字符串的子字符串是否以指定前缀开头。
        System.out.println("王鹏".startsWith("王"));
        System.out.println("张鹏王鹏".startsWith("王",2));
​
        //byte[] getBytes(String charsetName)
        //使用命名字符集将此String编码为字节序列,并将结果存储到新的字节数组中。
        //byte[] getBytes()
        //使用平台的默认字符集将此String编码为字节序列,并将结果存储到新的字节数组中。
​
        //char[] toCharArray()
        //将此字符串转换为新的字符数组。
        System.out.println(Arrays.toString(str1.toCharArray()));
​
        //void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
        //将此字符串中的字符复制到目标字符数组中。
        char[] arr = new char[10];
        System.out.println(Arrays.toString(arr));
        str1.getChars(5,8,arr,3);
        System.out.println(Arrays.toString(arr));
​
        //int indexOf(String str)
        //返回此字符串中第一次出现指定子字符串的索引。
        System.out.println(str1.indexOf("a"));
        //int indexOf(String str, int fromIndex)
        //返回此字符串中第一次出现指定子字符串的索引,从指定索引开始。
        System.out.println(str1.indexOf("a",6));
​
        //int lastIndexOf(String str)
        //返回此字符串中最后一次出现指定子字符串的索引。
        System.out.println(str1.lastIndexOf("a"));
​
        //int lastIndexOf(String str, int fromIndex)
        //返回此字符串中指定子字符串最后一次出现的索引,从指定索引开始向后搜索。
        System.out.println(str1.lastIndexOf("a",11));
​
        System.out.println("hahaabcheheabchouhouabc".lastIndexOf("abc"));
        System.out.println("hahaabcheheabchouhouabc".lastIndexOf("abc",12)); //如果正处于一个子串的中间,往前查找可以找到当前子串
​
        //int length()
        //返回此字符串的长度。
        System.out.println("abc".length());
​
        //String repeat(int count)
        //返回一个字符串,其值为该字符串重复count次的串联。
        System.out.println("abc".repeat(3));
​
        //String replace(char oldChar, char newChar)
        //返回一个字符串,该字符串是用newChar替换此字符串中所有出现的oldChar得到的。
​
        //String replace(CharSequence target, CharSequence replacement)
        //用指定的文字替换序列替换此字符串中与文字目标序列匹配的每个子字符串。
        //String replaceAll(String regex, String replacement)
        //用给定的替换替换此字符串中与给定regular expression匹配的每个子字符串。
        System.out.println(str1.replaceAll("a","A"));
        //String replaceFirst(String regex, String replacement)
        //用给定的替换替换此字符串中与给定的regular expression匹配的第一个子字符串。
        System.out.println(str1.replaceFirst("a","A"));
​
        //String[] split(String regex)
        //围绕给定regular expression的匹配拆分此字符串。
        System.out.println(Arrays.toString("name=zhangsan&pwd=123&age=18".split("&")));
​
        //String strip()
        //返回一个字符串,其值为该字符串,删除所有前导和尾随white space 。
        //String stripLeading()
        //返回一个字符串,其值为该字符串,所有前导white space已删除。
        //String stripTrailing()
        //返回一个字符串,其值为该字符串,并删除所有尾随white space 。
        //String trim() -->半角空格
        //返回一个字符串,其值为该字符串,删除了所有前导和尾随空格,其中空格定义为代码点小于或等于'U+0020' (空格字符)的任何字符。
        //全角空格了(“ ”)    半角空格(“ ”)
        System.out.println(" haha ".trim());
        System.out.println(" haha ".strip());
        System.out.println(" haha ".stripLeading());
        System.out.println(" haha ".stripTrailing());
​
        //String substring(int beginIndex)
        //返回作为此字符串的子字符串的字符串。
        //String substring(int beginIndex, int endIndex)
        //返回作为此字符串的子字符串的字符串。
        System.out.println(str1.substring(5));
        System.out.println(str1.substring(5,8));
​
        //String toLowerCase()
        //使用默认语言环境的规则将此String中的所有字符转换为小写。
        //String toUpperCase()
        //使用默认语言环境的规则将此String中的所有字符转换为大写。
        System.out.println(str1.toUpperCase());
        System.out.println(str2.toLowerCase());
​
        //static String valueOf(boolean b)
        //返回boolean参数的字符串表示形式。
        System.out.println(String.valueOf(false));;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值