2011年7月28日「Java7」正式リリース
Try&Catch 複数Exception設定可能。
try { ... } catch(IOException | ClassNotFoundException e) { //IOException or ClassNotFoundException時の処理 }
Switch 文字判断可能。
public static void main(String[] args){ String test = "test"; switch (test) { case "a": case "b": System.out.println("a or b"); break; case "test": System.out.println("test"); default: System.out.println("finish"); break; } }
ダイヤモンド演算子で型指定の省略。
List<String> list = new ArrayList<>();
file.close省略。
public class Java7Sample { public static void main(String[] args) { // FileReaderクラスとreadメソッドを使って1文字ずつ読み込み表示する try (FileReader fileReader = new FileReader(new File("Test.txt"))) { int data; while ((data = fileReader.read()) != -1) { System.out.print((char) data); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
リテラルにアンダースコア可能。
public static void main(String[] args) { long creditCardNumber = 1234_5678_9012_3456L; long socialSecurityNumber = 999_99_9999L; float pi = 3.14_15F; long hexBytes = 0xFF_EC_DE_5E; long hexWords = 0xCAFE_BABE; long maxLong = 0x7fff_ffff_ffff_ffffL; byte nybbles = 0b0010_0101; long bytes = 0b11010010_01101001_10010100_10010010; }
バイナリリテラル定義可能。
public static void main(String[] args) { int bin = 0B00001101; System.out.println(bin); }