Java versions
versions2Java7Features
- Path
- pkg2versions/versions2Java7Features.java
- Package
- pkg2versions
- Study order
- 2
- Run
- Single-file source launch
- Command
- java pkg2versions/versions2Java7Features.java
- Version in the filename
- Java 7
- Example
- Java 7 example
- Requires
- Java 7
- Lesson
- Back to the chapter
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg2versions;2 3/*4 * versions2Java7Features.java (2011) "Project Coin"5 * ------------------------------------------6 * FEATURES & WHY:7 * - try-with-resources : auto-close resources, less boilerplate, no leaks.8 * - Diamond operator <> : infer generic type on the right side.9 * - Strings in switch : cleaner branching on strings.10 * - Multi-catch : handle multiple exception types in one block.11 * - Numeric underscores: readable literals (1_000_000).12 * - Binary literals : 0b1010.13 */14import java.util.*;15 16public class versions2Java7Features {17 18 static class Resource implements AutoCloseable {19 public void close() { System.out.println("resource closed"); }20 void doWork() { System.out.println("working"); }21 }22 23 public static void main(String[] args) {24 // Diamond operator: the compiler fills in <String, List<Integer>>25 Map<String, List<Integer>> map = new HashMap<>();26 List<Integer> numbers = new ArrayList<>();27 numbers.add(1);28 map.put("a", numbers);29 System.out.println("diamond map: " + map);30 31 // try-with-resources32 try (Resource r = new Resource()) {33 r.doWork();34 }35 36 // Strings in switch37 String cmd = "start";38 switch (cmd) {39 case "start":40 System.out.println("starting...");41 break;42 case "stop":43 System.out.println("stopping...");44 break;45 default:46 System.out.println("unknown");47 }48 49 // Multi-catch50 try {51 if (cmd.equals("start")) throw new IllegalStateException("boom");52 } catch (IllegalStateException | IllegalArgumentException e) {53 System.out.println("multi-catch: " + e.getMessage());54 }55 56 // Numeric underscores + binary literals57 int million = 1_000_000;58 int bits = 0b1010_1010;59 System.out.println("million=" + million + " binary=" + bits);60 }61}