1恩静、異常:JAVA 提供的用于處理程序中錯(cuò)誤的一種機(jī)制
編譯時(shí)異常:如果程序一旦出現(xiàn)檢查時(shí)異常,程序必須要經(jīng)過(guò)處理,否則無(wú)法運(yùn)行
運(yùn)行時(shí)異常:推薦增強(qiáng)程序的健壯性就可以處理
一般運(yùn)行時(shí)異常都會(huì)直接或者間接的繼承自RuntimeException
Exception:所有異常的父類蹲坷,其子類對(duì)應(yīng)了各種各樣可能出現(xiàn)的異常事件驶乾,一般需要用戶顯示地聲明或捕獲。
????/ ? ? ? ?? \
?|???????????????????????? |???????????????????? \
Unchecked??????????Checked?????????Runtime
?Exception?????????????Exception????????Exception
3循签、運(yùn)行時(shí)異常: RuntimeException
運(yùn)行時(shí)異常假如不拋出级乐,或者拋出但不處理,不報(bào)錯(cuò)县匠,但運(yùn)行時(shí)會(huì)異常終止风科。
?????空指針? NullPointerException
????? 數(shù)組越界異常 ArrayIndexOutOfBoundsException
????負(fù)數(shù)異常|數(shù)組的長(zhǎng)度為負(fù)數(shù)異常 NegativeArraySizeException
????? 數(shù)學(xué)異常? ArithmeticException
? ?? 類型轉(zhuǎn)換異常? ClassCastException
?? ? 數(shù)字轉(zhuǎn)換異常? NumberFormatException
?public static voidmain(String[] args) { ?
?????????//1.空指針? NullPointerException ?
????????System.out.println("s是空的"); ?
????????//2.數(shù)組越界?ArrayIndexOutOfBoundsException?
?????????int[] arr=new int[3];
????????? System.out.println(arr[3]); ??
????????????//3.負(fù)數(shù)異常? NegativeArraySizeException?
????????? int[] arr2=new int[-3]; ? ??
????????? //4.數(shù)學(xué)異常|分母為0異常 ?
????????????System.out.println(2/0); ??
?????????? //5.類型轉(zhuǎn)換異常ClassCastException
?????????? Person p =new Student(); ?
?????????Teacher t=(Teacher)p; ? ??
? ? ? ? ? //6.數(shù)字轉(zhuǎn)換異常NumberFormatException ?
????System.out.println(Integer.valueOf(s));?
????? }
class Student extendsPerson{}?
class Teacher extends Person{}
is=new FileInputStream("D://test.txt");//D盤(pán)中并無(wú)此文件時(shí)
編譯時(shí)異常必須處理或者拋出再處理,否則無(wú)法通過(guò)編譯贼穆。
? 如throws Exception兰粉,將異常拋出到外面一層去故痊,然后在外層處理
? 方法的重寫(xiě) : 子類重寫(xiě)方法拋出異常<=父類方法拋出的異常
5.2、try..catch..fanally捕獲和處理異常
(FileNotFoundException e) {
如果出現(xiàn)對(duì)應(yīng)的異常執(zhí)行的代碼
(NullPointerException e){
(Exception e){
無(wú)論是否出現(xiàn)異常,一定會(huì)執(zhí)行的代碼
如果try中的代碼出現(xiàn)異常,下面的代碼不會(huì)執(zhí)行,直接執(zhí)行對(duì)應(yīng)的catch中的代碼
一個(gè)try至少存在一個(gè)或者多個(gè)catch
? 通常在finally語(yǔ)句中可以進(jìn)行資源的清除工作玖姑,如:關(guān)閉打開(kāi)的文件愕秫、刪除臨時(shí)文件
6、自定義異常類:? 要直接或者間接繼承自Exception或者它的子類
? public static voidmain(String[] args) { ? ??
????????User user=new User(); ? ?
?????????????user.setAge(-18); ??
????????????} catch(AgeException e) { ??
????????????????????e.printStackTrace(); ??
????????????}?? System.out.println("18歲"); ?
????classAgeException extends Exception{ ?
????????????????publicAgeException() {? } ?
????????????????public AgeException(String message) {?
????????????????????????? super(message+"年齡異常"); ?
????????????????private int age;?
?????????????? public intgetAge() { ?
?????????????????????????????return age; ?
?????????????????public void setAge(int age)throws AgeException {?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if(age<0) { ??
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?? throw new AgeException(); ? ??
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? }else { ? ? ? ??
????????????????????????????????????????? this.age = age; ? ??
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? }?
?????????????????????????????}?
作用:String 類代表字符串戴甩。Java 程序中的所有字符串字面值(如 "abc" )都作為此類的實(shí)例實(shí)現(xiàn)。
?StringBuilder:可變長(zhǎng)字符串 ,線程不安全,效率較高
?StringBuffer:可變長(zhǎng)字符串 ,線程安全的,效率較低
String str1="abc";
String str2="abc";
//一個(gè)對(duì)象甜孤,“abc”在常量池中?
System.out.println(str1==str2);//true
?//空構(gòu)造器String str3=new String();?
//String(String original) ?
String str4=new String("hehe");
//String(char[] value) ?
String str5=newString(new char[]{'a','b','c','d'});?
//String(char[] value, int offset, intcount) ?
String str6=new String(newchar[]{'a','b','c','d'},1,2);?
System.out.println(str6);//bc
System.out.println(new String(new char[]{22222,'2'}));
//構(gòu)建字符串//String(byte[] bytes)?
?//通過(guò)使用平臺(tái)的默認(rèn)字符集解碼指定的 byte 數(shù)組,構(gòu)造一個(gè)新的 String畏腕。
String str7=new String(new byte[]{66,67,68});?
//String(byte[]bytes, int offset, int length) ?
//通過(guò)使用平臺(tái)的默認(rèn)字符集解碼指定的 byte 子數(shù)組课蔬,構(gòu)造一個(gè)新的 String。
?String str8=new String(new byte[]{66,67,68},1,2);?
String str9="qwer";
?byte[] by=str9.getBytes();?
System.out.println(Arrays.toString(by));
Stringstr1="good good study";?
String str2=" day day up "; ? ? ?
?//1.char charAt(int index)? 返回指定索引處的 char 值二跋。
?System.out.println("charAt():"+str1.charAt(3)); //d?
//2.intcodePointAt(int index)? 返回指定索引處的字符(Unicode 代碼點(diǎn))。System.out.println("codePointAt():"+str1.codePointAt(3));? //100?
//3.int compareTo(String anotherString)按字典順序比較兩個(gè)字符串流昏。
?//相等為0 ,如果this比參數(shù)對(duì)象大返回整數(shù),否則返回負(fù)數(shù)System.out.println("compareTo():"+str1.compareTo(str2));? //3
?//4.compareToIgnoreCase(String str)按字典順序比較兩個(gè)字符串扎即,不考慮大小寫(xiě)System.out.println("abc".compareToIgnoreCase("AbcDEFgh"));? //-5?
//5.String concat(String str)?? 將指定字符串連接到此字符串的結(jié)吞获。
System.out.println("concat():"+str1.concat("!"));? //good good study!
?//6.booleancontains(CharSequence s) ? ?
//當(dāng)且僅當(dāng)此字符串包含指定的 char 值序列時(shí),返回 true谚鄙。?
System.out.println("contains():"+str1.contains("oo"));? //true
?//7.static String copyValueOf(char[]data) ?
//返回指定數(shù)組中表示該字符序列的 String各拷。
?System.out.println(String.copyValueOf(new char[]{'a','b','c'}));? //abc System.out.println(String.copyValueOf(newchar[]{'a','b','c'},1,2));? //bc
//8.boolean endsWith(String suffix) //測(cè)試此字符串是否以指定的后綴結(jié)束。 System.out.println("endsWith():"+str.endsWith("y"));? //true
?//9.boolean startsWith(Stringprefix)? //測(cè)試此字符串是否以指定的前綴開(kāi)始闷营。System.out.println("startsWith():"+str.startsWith("good"));? //true?
//10.byte[] getBytes()字符串轉(zhuǎn)字節(jié)數(shù)組System.out.println("getBytes():"+Arrays.toString(str1.getBytes())); ?
?//[103, 111, 111, 100, 32, 103, 111, 111,100, 32, 115, 116, 117, 100, 121] ?
//11.int indexOf(String str)??? //返回指定子字符串在此字符串中第一次出現(xiàn)處的索引 System.out.println("indexOf():"+str1.indexOf("o")); ?//1
?System.out.println("lastIndexOf():"+str1.lastIndexOf("o"));? //7?
//12.String replace(char oldChar, char newChar)?
//返回一個(gè)新的字符串烤黍,它是通過(guò)用 newChar 替換此字符串中出現(xiàn)的所有 oldChar 得到的。System.out.println("replace():"+str1.replace("oo","OO"));? //replace():gOOd gOOd study?
?//13.String[] split(String regex)根據(jù)給定正則表達(dá)式的匹配拆分此字符串傻盟。?
? System.out.println(str1);//good good study? String[]arr=str1.split(" "); System.out.println(Arrays.toString(arr));//[good,good, study]?
System.out.println(arr[1]);//good?
//14.String substring(intbeginIndex)? //返回一個(gè)新的字符串速蕊,它是此字符串的一個(gè)子字符串。
?//15.String substring(int beginIndex, int endIndex)?
//返回一個(gè)新字符串娘赴,它是此字符串的一個(gè)子字符串规哲。結(jié)束位置索引獲取不到System.out.println("substring():"+str1.substring(5));? //substring():good?study System.out.println("substring():"+str1.substring(5,8));? //substring():goo?
//16.char[] toCharArray()將此字符串轉(zhuǎn)換為一個(gè)新的字符數(shù)組。
System.out.println(str1.toCharArray());? //good good study ?
//17.String toLowerCase() ??
//18.String toUpperCase()? System.out.println(str1.toUpperCase());? //GOOD GOOD STUDY?
//使用默認(rèn)語(yǔ)言環(huán)境的規(guī)則將此 String 中的所有字符都轉(zhuǎn)換為大寫(xiě)诽表。 ?
//19.String trim()返回字符串的副本唉锌,忽略前導(dǎo)空白和尾部空白。
?System.out.println("trim():"+str2.trim());? //trim():day day up?
//20.static StringvalueOf(int i)?? 返回 int 參數(shù)的字符串表示形 System.out.println("valueOf():"+String.valueOf(1234)); //1234
3竿奏、StringBuffer和Stringbuilder?
StringBuilder()構(gòu)造一個(gè)其中不帶字符的字符串生成器袄简,初始容量為 16 個(gè)字符。
str=new StringBuilder();?
System.out.println(str);
str.append("qwert");?
System.out.println(str);
System.out.println(str.capacity());?
System.out.println(str.length());
//StringBuilder(int capacity)構(gòu)造一個(gè)其中不帶字符的字符串生成器泛啸,初始容量由capacity 參數(shù)指定绿语。
?str=new StringBuilder(10);?
System.out.println(str.capacity());
//StringBuilder(String str)構(gòu)造一個(gè)字符串生成器,并初始化為指定的字符串內(nèi)容平痰。 ?
str=new StringBuilder("abc");
str.append(121);?
System.out.println(str);?
//StringBuilder delete(int start, intend)?
?str.delete(3, 5);System.out.println(str);?
//StringBuilder insert(int offset, boolean b) ??
str.insert(3, false);?
System.out.println(str); ?
//StringBuilder reverse() ??
str.reverse(); system.out.println(str);
4汞舱、String與StringBuilder之間相互轉(zhuǎn)換
String->StringBuilder? 構(gòu)造器
?????????????String(StringBuffer buffer)分配一個(gè)新的字符串,它包含字符串緩沖區(qū)參數(shù)中當(dāng)前包含的字符序列宗雇。StringBuilder->String? 構(gòu)造器
?????????????????String(StringBuilder builder)
包裝類顧名思義就是將基本的數(shù)據(jù)類型以及一些輔助方法包裝到類中
?基本數(shù)據(jù)類型?????????????????????????????????????????????? 包裝類
????????byte????????????????????????????---???????????????????????Byte
????????short???????????????????????????---???????????????????????Short
????????int????????????????????????????????---???????????????????????Integer
????????long??????????????????????????????? ---???????????????????Long
? ? ? ?? char??????????????????????????????? --- ? ? ? ? ? ? ? ? ? Character
? ? ?? float?????????????????????????????? ---?????????????????????? Float
? ? ?? double???????????????????????????---???????????????????????Double
? ? ?? boolean?????????????????????? ---???????????????????? Boolean
?自動(dòng)裝箱:基本數(shù)據(jù)類型-->包裝類型
?自動(dòng)拆箱:包裝類型-->基本數(shù)據(jù)類型
//static? double Math.ceil(double a) 向上取整?
?System.out.println(Math.ceil(-3.3));? //-3.0?
//static double floor(double a)? 向下取整
System.out.println(Math.floor(-3.3));?//-4.0?
//static long max(long a, long b) //返回兩個(gè)long 值中較大的一個(gè)赔蒲。?
//static double min(double a, double b)
?//返回兩個(gè)double 值中較小的一個(gè)泌神。?
System.out.println(Math.max(5, 7));
Date() 以當(dāng)前系統(tǒng)時(shí)間構(gòu)建日期對(duì)象
Date(long date) 參數(shù)為毫秒數(shù),默認(rèn)從1970.1.1.0.0.0開(kāi)始計(jì)算
//日期對(duì)象轉(zhuǎn)為字符串 Date date=new Date(); String s=date.toString();
System.out.println(s); System.out.println(s.length());
2欢际、SimpleDateFormat 日期格式類|轉(zhuǎn)換類|轉(zhuǎn)換器???指定格式
y->年?M->月?d->日??H->24小時(shí) h->12小時(shí)? m->分? s->秒? S->毫秒
? format(Date)-->日期對(duì)象轉(zhuǎn)為字符串,可以按照指定格式,可以使用轉(zhuǎn)換器的默認(rèn)格式
? parse(String) -->把字符串轉(zhuǎn)為日期對(duì)象,按照指定格式轉(zhuǎn)換
format=new SimpleDateFormat();?
System.out.println(format.format(date));//19-5-6下午8:35?
SimpleDateFormat formatNew=newSimpleDateFormat("yyyy年MM月DD日? E a hh:mm:ss SS");
System.out.println(formatNew.format(date)); //2019年05月126日? 星期一下午08:35:57 572? Stringstr="2019/05/126/ 08:44:59 515"; ?
System.out.println(formatNew.parse(str));
編譯器將源代碼編譯為字節(jié)碼時(shí)损趋,會(huì)進(jìn)行相應(yīng)的優(yōu)化操作
如果可以確定不越界,編譯器會(huì)把多余的數(shù)組越界檢查消除掉
讓我們得到的對(duì)象或參數(shù)類型浑槽,按照要求轉(zhuǎn)成字符串的形式蒋失。
String:強(qiáng)轉(zhuǎn),簡(jiǎn)單方便但如果要轉(zhuǎn)的不是字符串的話桐玻,那么就會(huì)報(bào)錯(cuò)篙挽。
valueOf(Object obj){return?(obj==null) ??"null"?: obj.toString()};
在內(nèi)部就是做了為空的判斷的煮落,所以就不會(huì)報(bào)出空指針異常。