< API >

本文详细介绍了Java API中的异常处理机制,包括异常分类、捕获与处理,以及如何自定义异常。同时,深入探讨了Math类的常用方法,如随机数、开方和次幂。此外,还讲解了String和StringBuilder/StringBuffer的区别及使用场景,以及包装类的作用。文章最后提到了集合框架的基础概念,如List、ArrayList、LinkedList、Set和HashSet等。
摘要由CSDN通过智能技术生成

API (application programming interface)


第一章 概述

api 分成以下几个包讲解 :

1.java.lang (异常类, String , Math , StringBuffer,StringBuilder , 包装类 ,Object ,Class 反射 )

2.java.util (日期类,日期转换 ,工具类,BigDecimal , 集合类...)

3.java.io (文件类 文件读写类...)

4.java.net(了解)

5.多线程(lang 重点)

6.java.awt(了解)

7.jdk8+ api (了解API的特性 Stream流)


第二章 异常类

2.1 什么是异常?

程序编译或运行当中,出现的问题,统称为异常。异常分为: 程序异常Exception和错误Error。

异常根类: Throwable

程序异常类: Exception 由于程序员疏忽,设计不合理导致的问题,需要解决

程序错误类: Error 程序中出现致命问题如 虚拟机崩溃,内存溢出,堆栈溢出... 不需要在程序中解决

2.2 Exception的分类

1.编译时异常: 在程序编译时发生了异常,如果不解决,无法编译

例如: IOException (IO 异常) SQLException(数据库异常) FileNotFoundException(文件未找到异常) ....

2.运行时异常 : 编译时没有问题,运行时抛出异常(RuntimeException)

例如:

异常类含义示例
ArrayIndexOutofBoundsException数组下标越界异常int[] a = new int[4]; System.out.println(a[4]);
NullPointerException空引用异常String str = null; System.out.println(str.length());
ArithmeticException数学异常10 / 0
ClassCastException类型转换异常Son s = (Son)new Father();
NumberFormatException数字转换异常Integer.parseInt("ys")

 public class TestException1 {
     public static void main(String[] args) {
         //数学异常
         //System.out.println(10 / 0);
         //数组越界
 //      int[] a = new int[4];
 //      System.out.println(a[4]);
         //空引用
 //      String str = null;      
 //      System.out.println(str.length());
         //类型转换
 //      Son s = (Son)new Father();
         //数字转换
         System.out.println(Integer.parseInt("ys") + 10);
     }
 }

2.3 出现异常后的反应

1.系统打印错误信息

2.程序终止,突然中断

3.分配对象信息资源不变,可能资源泄露

总结:异常在程序中亟待解决的

2.4 异常捕获机制

异常的处理: 异常的捕获机制 (try catch finally

语法规则:

 //监视器
 try{
     //代码监视器,有可能发生异常的代码块
 }catch(异常类型  变量名){
     //异常捕获器,处理问题    
 }catch(异常类型  变量名){
     //异常捕获器    
 } //...
 finally{
     //清理块,无条件执行的语句块
 }

注意:

1.try 监视器,不可以单独出现,需要配合catch(可以处理异常)或finally(不会处理异常)

2.catch可以有,捕获不同类型的异常,类似多条分支结果,n选1个,类型不要重复

3.因此将catch(Exception e) {} 放到catch的最后

4.finally 可以写也可以不写,无条件执行,除非退出虚拟机,包括return

 public class SystemCode {
     
     public static void main(String[] args) {
         System.out.println("以下张雨代码....");
         try {
             System.out.println("..........");
             System.out.println(10 / 0);
         }
         catch(ArithmeticException e) {
             System.out.println("你发生了数学错误,赶紧改正");
             //return;
             //退出虚拟机
             System.exit(0);
         }
         catch(Exception e) {
             //保底
         }
         finally {
             System.out.println("无条件执行");
         }
         System.out.println("张雨代码结束....");
         
         
         System.out.println("以下义民代码....");
         
         System.out.println("..........");
                 
         System.out.println("义民代码结束....");
     }
 }

运行顺序:

 

情况1:

     try {
             System.out.println(10 / 0);
         } 
         catch (Exception e) {
             
             System.out.println("数学异常");
         }
         finally {
             System.out.println("执行finally");
         }
         
         System.out.println("执行该语句");
         
 /**
 数学异常
 执行finally
 执行该语句
 */

情况2:

     try {
             System.out.println(10 / 10);
         } 
         catch (Exception e) {
             
             System.out.println("数学异常");
         }
         finally {
             System.out.println("执行finally");
         }
         
         System.out.println("执行该语句");
 /**
 1
 执行finally
 执行该语句
 */
 ​

情况3:

         try {
             System.out.println(10 / 0);
         } 
         finally {
             System.out.println("执行finally");
         }
         
         System.out.println("执行该语句");
 ​
 /**
 执行finally
 */

情况4:

     try {
             System.out.println(10 / 0);
         } 
         catch (Exception e) {
             
             System.out.println("数学异常");
             return;
         }
         finally {
             System.out.println("执行finally");
         }
         
         System.out.println("执行该语句");
 ​
 /**
 数学异常
 执行finally
 */

注意: 先执行finally ,再执行return

情况5:

     try {
             System.out.println(10 / 0);
         } 
         catch (Exception e) {
             
             System.out.println("数学异常");
             System.exit(0);
         }
         finally {
             System.out.println("执行finally");
         }
         
         System.out.println("执行该语句");
 ​
 /**
 数学异常
 */

2.5 异常的抛出

throw和throws

2.5.1 throws

方法内有异常发生,不解决,难以解决时,将方法内的异常向外抛出,使用throws。

语法:

 控制权限  返回值  方法名(参数类型 参数变量) throws 异常类型1, 异常类型2... {
     
     //有异常
     
 }

注意:

  1. 方法的异常抛给方法的调用者,调用者必须解决或继续抛,直到主方法,主方法抛给虚拟机

 public class TestThrows {
     //方法向外抛出异常
     public static void test1() throws NullPointerException,ArithmeticException{     
         System.out.println(10 / 0);
     }
     //调用后不解决,继续抛
     public static void test2() throws Exception{        
         test1();
     }
     public static void main(String[] args) {
         try {
             //调用者
             test1();
         } catch (Exception e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
 }
  1. 方法重写时,子类不允许抛出更大类型异常

 public class A {
     public void test() throws NullPointerException{
         
     }
 }
 ​
 class B extends A{
     //重写不能抛出更大类型
 //  public void test() throws Exception{
 //      
 //  }
     //重载不限制
     public void test(int a) throws Exception{
         
     }
 }
  1. 一般都是编译时异常抛出

  2. throws 抛出异常类

2.5.2 throw

当程序员需要手动创造一个异常,并且抛出去。自己构建一个异常。

语法:

 //1 创建一个异常对象
 Exception 对象名  = new Exception("异常的问题");
 //2 throw抛出
 throw 对象名;

例子:

 public class TestThrow {
     public static void main(String[] args) {
         //使用检测年龄方法
         checkAge(9);
         
         System.out.println("继续编码代码");
     }
     
     /**
      * 检测年龄是否合法
      */
     public static void checkAge(int age) {
         if(age > 0 && age < 150) {
             System.out.println("年龄合法");
         
         }else {
             //构建异常
             RuntimeException e = new RuntimeException("年龄不合法,不能超出(1-150)");
             //手动抛出异常
             throw e;
         }
     }
 }

throws 和 throw 区别?

throwsthrow
方法向外自动抛出异常手动创建异常抛出
异常类异常对象
方法后面方法里

2.6 自定义异常

程序员自己构建一个异常类型,需要继承异常父类: RuntimeException或者Exception。

 public class AgeException extends Exception{
 ​
     /**
      * 序列号
      */
     private static final long serialVersionUID = 1L;
 ​
     public AgeException() {
         super();
         // TODO Auto-generated constructor stub
     }
 ​
     public AgeException(String message) {
         super(message);
         // TODO Auto-generated constructor stub
     }
     
 }
 ​
 /**
      * 检测年龄是否合法
      * @throws AgeException 
      */
     public static void checkAge(int age) throws AgeException {
         if(age > 0 && age < 150) {
             System.out.println("年龄合法");
         
         }else {         
             throw new AgeException("年龄非法");
         }
     }

第三章 Math

Math 类包含用于执行基本数学运算的方法。

注意:

  1. Math是final修饰的类,并不能拓展子类

  2. Math构造方法是私有的,所有属性和方法全是静态的 Math.属性 Math.方法

构造:构造被私有化

属性:

属性
PI圆周率public static final double
E自然底数public static final double

方法:

方法含义返回值或参数
random()随机数[a,b] : (int)((b - a + 1) * Math.random() + a)
ceil(double)向上取整获得比当前参数稍微大的整数,如果就是整数返回自己
floor(double)向下取整获得比当前参数稍微小的整数,如果就是整数返回自己
round(double)四舍五入返回四舍五入结果(整数位),注意:Math.floor(a + 0.5f)
sqrt(double)开平方根NaN : not a number
pow(a,b)a的b次幂b个a相乘

案例1:随机生产 四个大写字母(验证码)

 char [] code = new char[4];
         for (int i = 0; i < code.length; i++) {
             code[i] = (char)((90 - 65 + 1) * Math.random() + 65);
             for (int j = 0; j < i; j++) {
                 if(code[j] == code[i]) {
                     i --;
                     break;
                 }
             }
     
         }
 System.out.println(Arrays.toString(code));

案例2: 猜数游戏

 public class TestMath{
     public static void main(String[] args) {
         int num = (int) ((100 - 50 + 1) * Math.random() + 50);
         Scanner sc = new Scanner(System.in);
         int s = 50, e = 100;
         for (int i = 0; i < 5; i++) {
             System.out.println("第" + (i + 1) + "次机会请输入你猜的数字(" + s + "-" + e + ")");
             int m = sc.nextInt();
             if (num > m) {
                 System.out.println("猜小了");
                 s = m;
             } else if (num < m) {
                 System.out.println("猜大了");
                 e = m ;
             } else {
                 System.out.println("Win");
                 return;
             }
         }
         System.out.println("机会用完了,数字是:" + num);
     }
 }

取整和四舍五入的案例:

         //向上取整
         System.out.println(Math.ceil(12.5));//13.0
         System.out.println(Math.ceil(12));//12.0
         System.out.println(Math.ceil(-8.01));//-8.0
         System.out.println(Math.ceil(-7.92)); // -7.0
         System.out.println("-----------------");
         //向下取整
         System.out.println(Math.floor(12.98)); //12.0
         System.out.println(Math.floor(-12.98));//-13.0
         System.out.println(Math.floor(14));//14.0
         //Math.floor(a + 0.5f) 
         //四舍五入
         System.out.println(Math.round(12.67));  //13
         System.out.println(Math.round(-12.67)); // -13
         System.out.println(Math.round(12.27));  //12
         System.out.println(Math.round(2.5));//3
         //特殊的
         System.out.println(Math.round(-2.5));//-2

开方和次幂:

         //开平方
         System.out.println(Math.sqrt(25));
         System.out.println(Math.sqrt(-36));//NaN    
         //求次幂
         System.out.println(Math.pow(3, 4));// 3 * 3 * 3 * 3

第四章 String和StringBuilder,StringBuffer

4.1 String

不可变字符串,一经定义不能改变。 " "括起来的,原样的。

注意: 字符串对象和字符串常量"abc" 都认为是对象型

         String s = "abc123中";
         //字符串常量也是对象
         System.out.println(s.length());
         System.out.println("abcd".length());

构造方法:

 new String();
 new String("abc");
 new String(StringBuilder sbl); //将可变字符串Builder转为String

 //一共创建三个对象
 String s1 = new String("abc");
 String s2 = new String("abc");
         
 String s3 = "abc";
 String s4 = "abc";
 System.out.println(s1 == s2);//false
 System.out.println(s3 == s4);//true

 

方法:

使用方法名含义返回值
长度字符串.length()字符串长度,汉字按照1个返回字符个数
查找单个字符串.charAt(下标)字符串有下标,从0,对应下标的一个字符一个字符
截取字符串.substring(下标)从下标截取到最后截取的新的子串
截取区间字符串.substring(起始下标,结束下标)从起始下标截取到结束下标-1同上
分割字符串.split(切割符号)字符串分割,注意特殊符号要加转义字符串数组
查找子串字符串.indexOf(子串)从字符串中查找是否存在子串(左向右)返回第一次下标,不存在返回-1
查找子串字符串.lastIndexOf(子串)从字符串中查找是否存在子串返回最后一次下标,不存在返回-1
比较内容字符串.equals(参数串)参数串和字符串内容相同,不管地址boolean
比较顺序字符串.compareTo(参数串)比较字典顺序0 (相同)负的 正的
替换字符串.replace(old,new)将old替换成new新串
正则校验字符串.matches(正则)匹配正则表达式
字符串.endsWith()
字符串.startsWith()
字符串.trim()去掉两端空白

截取案例:

 public class TestString2 {
     public static void main(String[] args) {
         String str = "abcd中国人";
         //长度
         //System.out.println("abcd中".length());
 ​
         //获得一个字符
         //System.out.println(str.charAt(4));        
         //System.out.println(str);
         
         //截取
         String s1 = str.substring(4);
         System.out.println(s1); 
         System.out.println(str.substring(0, 4));        
         System.out.println(str);
     }   
 }

分割和查找案例:

 public class TestString3 {
     public static void main(String[] args) {
         String city = "大连|本溪|丹东|辽阳";
         //分割
         String[] citys = city.split("\\|");
         
         for (String c : citys) {
             System.out.println(c);
         }
         
         String str = "abacdabddfgr";
         //字符串查找
         //第一次出现位置
         System.out.println(str.indexOf("ys"));
         //最后一次出现位置
         System.out.println(str.lastIndexOf("ab"));
     }
 }

字符串比较:

 public class TestString4 {
     public static void main(String[] args) {
         String str = "abcdabff";
         //字符串替换
         System.out.println(str.replace("ab", "*"));
         
         System.out.println(str);
         
         String s1 = "bdc";
         String s2 = new String("bdcd");
         //字符串比较内容
         //System.out.println(s1 == s2);//false
         //System.out.println(s1.equals(s2));//true
         
         //字符串比较顺序
         System.out.println(s1.compareTo(s2));
     }
 }

matches() 和正则联系: 正则表达式

正则表达式: 相当于定义了一个规范格式,匹配的模型,衡量标准。

 字符串.matches(正则表达式); // 满足返回true 否则返回false

1.正则的开始 ^

2.正则的结束 $

3.正则的内容 区间 [abc] a,b,c任选一个 [a-z] a-z任选一个 直接匹配: @qq.com 0411-

4.正则的位数 {n} 就是n位 {n,m} n到m位 {n,} n位以上

5.简化 \d [0-9] \w [0-9a-zA-Z_]

6.特殊位数: + ? *

7.或者 |

正则案例:

 public class TestPartten2 { 
     /**
      * 1.  正则检测账号 :  首位必须字母,其余是字母数字_  8-10位
      */ 
     public static boolean checkNo(String no) {  
         return no.matches("^[a-zA-Z]{1}\\w{7,9}$"); 
     }   
     /**
      * 2. 正则检测身份证
      * @param no
      * @return
      */
     public static boolean checkCard(String id) {        
         return id.matches("^[1-8]{1}\\d{16}[0-9X]$");   
     }   
     /**
      *  检测手机号
      * @param args
      */
     public static boolean checkTel(String tel) {        
         return tel.matches("^(138\\d{8})|(159\\d{8})$");    
     }   
     public static void main(String[] args) {
         //System.out.println(checkCard("210283200205091013"));
     }
 }

4.2 StringBuilder,StringBuffer

可变字符串,在原字符串基础上,增删改,字符串的缓冲。

总结:

String: 不可变字符串,不能改变

StringBuffer 可变字符串,线程安全,同步的,效率低

StringBuilder可变字符串,线程不安全,不同步,效率高,推荐。

4.2.1 StringBuilder

可变的字符序列,相当于字符串的缓冲区,可以改变的。

构造方法:

 new StringBuilder(); //创建默认的字符串缓冲区  16字符
 new StringBuilder(int);// 创建指定容量的缓冲区
 new StringBuilder(String);// 创建字符串缓冲区,存入默认字符串,将String变成Builder

 public class TestBuilder {
     public static void main(String[] args) {
         StringBuilder b1 = new StringBuilder();//16     
         StringBuilder b2 = new StringBuilder(10);//25       
         StringBuilder b3 = new StringBuilder("abc");//
         //字符串长度
         System.out.println(b1.length());
         System.out.println(b2.length());
         System.out.println(b3.length());        
         //缓冲区容量
         System.out.println(b1.capacity());
         System.out.println(b2.capacity());
         System.out.println(b3.capacity());
     }
 }

常用方法:

方法名含义返回值
length()字符串长度,内容个数int
capacity()缓冲区大小,容量int
append(字符串)在原串尾部追加字符串StringBuilder
insert(下标,字符串)在该下标前插入字符串StringBuilder
deleteCharAt(下标)根据下标删除一个字符StringBuilder
delete(s,e)从s删除到e-1StringBuilder
setCharAt(下标,修改字符)对应下标修改一个StringBuilder
reverse()翻转StringBuilder

追加:

 //粘贴26个字母
 StringBuilder bul = new StringBuilder();
 for (char i = 'a'; i <= 'z'; i++) {
     bul.append(i);
 }
 System.out.println(bul);

其余方法:

 public class TestBuilder3 {
     public static void main(String[] args) {
         
         StringBuilder bul = new StringBuilder("中国人");       
         //下标1左侧插入华人民
         bul.insert(1, "华人民");   
         bul.insert(bul.indexOf("国"), "共和"); 
         
         //删除最后一个
         bul.deleteCharAt(bul.length() - 1);
         
         //删除区间
         //bul.delete(0, 4);
         //人修改为义
         bul.setCharAt(2, '义');
         
         //翻转
         bul.reverse();
         System.out.println(bul);
         
         
     }
 }

使用翻转做回文数:

 public static boolean isHui(String str) {
         StringBuilder bul = new StringBuilder(str);
          //判断翻转的和原来是否对等
         if(str.equals(bul.reverse().toString())) {
             return true;
         }else {
             return false;
         }
     }

第五章 包装类

5.1 包装类

八个类和八个基本数据类型对应的类,将每个离散的数据类型包装成类型。

包装类基本类型
Bytebyte
Shortshort
Integerint
Longlong
Floatfloat
Doubledouble
Characterchar
Booleanboolean

5.2 包装类和基本类型转换

装箱: 将基本数据类型转化为包装类

 //手动装箱(JDK5-)
 //new Integer(int);
 ​
 //自动装箱(JDK5+)
 int a = 10;
 Integer i = a;
 //注意,不能用自动转换
 //Long l = a;//错误的用法
 //自动装箱时,必须满足左右两侧一致

拆箱: 将包装类转化为基本数据类型

 //手动拆箱(JDK5-)
 //对象.intValue();
 //自动拆箱(JDK5+)
 Integer i = 10;
 int a = i;

5.3 包装/基本类型和String转换

1.其他类型转化为String

 //1.拼接 +  concat()
 int a = 10;
 System.out.println(a + "");
 //2.转化为包装对象
 Integer i = a;
 System.out.println(i.toString());
 //3 valueOf()
 String.valueOf(d)

2.String转化为其他类型(开发中需要使用)

 String s = "10";
 Integer.parseInt(s);//转int
 String s2 = "10.3";
 Double.parseDouble(s2); //转double

第六章 Object

第七章 集合类

java.util.*

7.1 集合的概念

集合作为JAVA中数据存储介质,和数组不同的是:

  1. 集合中的元素类型可以不一样(默认每个元素Object)

  2. 集合的大小可变,可以扩容的,方便增删改

7.2 集合的分类(重点)

系列1:

Collection接口: 存储

List子接口: 有下标,0开始,顺序

ArrayList 实现类 线性存储结构,元素挨着, 适合查询,不适合更新,线程不安全,效率高,不同步,速度快

LinkedList 实现类 链式存储结构,元素不挨着,适合更新,不适合查找

Vector 实现类 线程安全,效率低,同步

Set子接口: 没有下标,不能保证顺序,吞并重复元素

HashSet 实现类 : 哈希表存储 自动去重

TreeSet 实现类 : 红黑树存储 可以自然排序

系列2:

Map接口:存键值对

HashMap 实现类: 线程不安全,效率高,不同步,速度快

Hashtable 实现类: 线程安全,效率低,同步

TreeMap 实现类 : 自然排序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值