日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java7或java8新特性

發布時間:2024/5/14 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java7或java8新特性 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

技術交流qq群: 659201069

1、jdk7,數值類型字面值可以用‘多個‘—’分隔增加可讀性

int a = 123_456;double b = 123_456e3;

2、jdk7,可以使用字符串控制switch語句

String str = "abc";switch (str){case "abc":System.out.println("abc");break;case "cef":System.out.println("abc");break;default:System.out.println("null");}

3、jdk8、可以為接口添加static方法和默認實現

public interface searchService {public int search(String key);/*** jdk8新增特性,可以為接口中的方法定義默認實現**/default String get(String aa,String bb){System.out.println("我是jdk1.8默認實現方法...");return "";}String aa="2222";/*** jdk8新增特性,可以為接口添加static方法**/static void staticmethod(){System.out.println("我是靜態方法"+aa);} }

4、jdk7,帶資源的try語句,當資源(例如文件)不再需要時能夠自行釋放

class ShowFile { public static void main(String args[]) { int i; // First, confirm that a file name has been specified. if(args.length != 1) { System.out.println("Usage: ShowFile filename"); return; } // The following code uses a try-with-resources statement to open // a file and then automatically close it when the try block is left. try(FileInputStream fin = new FileInputStream(args[0])) { do { i = fin.read(); if(i != -1) System.out.print((char) i); } while(i != -1); } catch(FileNotFoundException e) { System.out.println("File Not Found."); } catch(IOException e) { System.out.println("An I/O Error Occurred"); } } }

5、jdk7,多重捕獲異常(multi-catch),本來不同的異常是由多個catch語句塊來處理,現在可以把多個異常用一個catch語句塊來處理,用’|’來表示多個異常,也就是或的意思

class MultiCatch {public static void main(String args[]) {int a=10, b=0;int vals[] = { 1, 2, 3 };try {int result = a / b; // generate an ArithmeticException // vals[10] = 19; // generate an ArrayIndexOutOfBoundsException// This catch clause catches both exceptions.} catch(ArithmeticException | ArrayIndexOutOfBoundsException e) {System.out.println("Exception caught: " + e);}System.out.println("After multi-catch.");} }

6、jdk7,最后重新拋出異常(final-rethrow),在rethrow方法中,catch塊捕獲的異常并沒有出現在throws從句中。Java 7編譯器會分析完整的try代碼塊以檢查從catch塊中什么類型的異常被拋出和重新拋出

public class ReThrowExceptions {public static void main(String[] args) {try{rethrow("abc");}catch(FirstException | SecondException | ThirdException e){//以下賦值將會在編譯期拋出異常,因為e是final型的//e = new Exception();System.out.println(e.getMessage());}}static void rethrow(String s) throws FirstException, SecondException,ThirdException {try {if (s.equals("First"))throw new FirstException("First");else if (s.equals("Second"))throw new SecondException("Second");elsethrow new ThirdException("Third");} catch (Exception e) {//下面的賦值沒有啟用重新拋出異常的類型檢查功能,這是Java 7的新特性// e=new ThirdException();throw e;}}static class FirstException extends Exception {public FirstException(String msg) {super(msg);}}static class SecondException extends Exception {public SecondException(String msg) {super(msg);}}static class ThirdException extends Exception {public ThirdException(String msg) {super(msg);}}}

7、jdk8,lambda表達式,函數式編程

/**用lambda表達式實現Runnable // Java 8之前: new Thread(new Runnable() {@Overridepublic void run() {System.out.println("Before Java8, too much code for too little to do");} }).start();//Java 8方式: new Thread( () -> System.out.println("In Java8, Lambda expression rocks !!") ).start(); // Java 8,lambda實現迭代: List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API"); features.forEach(n -> System.out.println(n));

8、jdk8,新增@FunctionalInterface注解,屬于標記注解,用來標記被注解的接口是函數式接口。如果被注解的接口不是函數式接口,編譯將報錯。但是創建函數式接口并不需要@FunctionalInterface,這個注解只是用來提供信息,也就是更顯法的說明此接口是函數式接口。根據java8的定義任何只有一個抽像方法的接口都是函數式接口(可以包括其它變量成員和方法,只要抽像方法是一個就可以),沒有@FunctionalInterface注解,也是函數式接口。例如java8內置的Runnable接口,使用了@FunctionalInterface注解,顯示說明Runnable是函數式接口,但完全可以不用這個注解,Runnable也是函數式接口。例如下面自定義的TestInterface接口,只有一個抽像方法本身就是函數式接口,與@FunctionalInterface沒有任何關系,這個注解只是用來提供信息的,顯示的標明這是一個函數式接口而式。

@FunctionalInterface public interface Runnable {/*** When an object implementing interface <code>Runnable</code> is used* to create a thread, starting the thread causes the object's* <code>run</code> method to be called in that separately executing* thread.* <p>* The general contract of the method <code>run</code> is that it may* take any action whatsoever.** @see java.lang.Thread#run()*/public abstract void run(); } @FunctionalInterface public interface TestInterface {// 抽象方法public void sub();// java.lang.Object中的方法不是抽象方法public boolean equals(Object var1);// default不是抽象方法public default void defaultMethod(){}// static不是抽象方法public static void staticMethod(){} }

9、jdk8,增加了類型注解,在之前注解只能用于聲明,也就是方法、變量、類、接口聲明的地方,java8開始在很多使用類型的其它地方也可以使用注解,例如方法返回類型、throws子句等。下面看官方給出的例子,在大多數類型前面都可以使用注解

// Use an annotation on a type parameter. class TypeAnnoDemo<@What(description = "Generic data type") T> {// Use a type annotation on a constructor.public @Unique TypeAnnoDemo() {}// Annotate the type (in this case String), not the field.@TypeAnno String str;// This annotates the field test.@EmptyOK String test;// Use a type annotation to annotate this (the receiver).public int f(@TypeAnno TypeAnnoDemo<T> this, int x) {return 10;}// Annotate the return type.public @TypeAnno Integer f2(int j, int k) {return j+k;}// Annotate the method declaration.public @Recommended Integer f3(String str) {return str.length() / 2;}// Use a type annotation with a throws clause.public void f4() throws @TypeAnno NullPointerException {// ...}// Annotate array levels.String @MaxLen(10) [] @NotZeroLen [] w;// Annotate the array element type.@TypeAnno Integer[] vec;public static void myMeth(int i) {// Use a type annotation on a type argument.TypeAnnoDemo<@TypeAnno Integer> ob =new TypeAnnoDemo<@TypeAnno Integer>();// Use a type annotation with new.@Unique TypeAnnoDemo<Integer> ob2 = new @Unique TypeAnnoDemo<Integer>();Object x = new Integer(10);Integer y;// Use a type annotation on a cast.y = (@TypeAnno Integer) x;}public static void main(String args[]) {myMeth(10);}// Use type annotation with inheritance clause.class SomeClass extends @TypeAnno TypeAnnoDemo<Boolean> {} }

總結

以上是生活随笔為你收集整理的java7或java8新特性的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。