|
| 1 | +package com.baeldung.javafeatures; |
| 2 | + |
| 3 | +import static java.lang.StringTemplate.STR; |
| 4 | + |
| 5 | +import java.sql.Connection; |
| 6 | +import java.sql.DriverManager; |
| 7 | +import java.sql.SQLException; |
| 8 | +import java.util.ArrayList; |
| 9 | +import java.util.HashMap; |
| 10 | +import java.util.List; |
| 11 | +import java.util.Map; |
| 12 | +import java.util.logging.Logger; |
| 13 | + |
| 14 | +public class UnnamedExpressions { |
| 15 | + private Logger LOGGER = Logger.getLogger(String.valueOf(UnnamedExpressions.class)); |
| 16 | + |
| 17 | + public int unnamedExpressionExampleUsingException(int someNumber) { |
| 18 | + int divided = 0; |
| 19 | + try { |
| 20 | + divided = someNumber / 0; |
| 21 | + } catch (ArithmeticException _) { |
| 22 | + System.err.println("Division by zero"); |
| 23 | + } |
| 24 | + return divided; |
| 25 | + } |
| 26 | + |
| 27 | + public Object unnamedExpressionsExampleUsingSwitch(Object obj) { |
| 28 | + switch (obj) { |
| 29 | + case Integer _ -> System.out.println("Is an integer"); |
| 30 | + case Float _ -> System.out.println("Is a float"); |
| 31 | + case String _ -> System.out.println("Is a String"); |
| 32 | + default -> System.out.println("Default"); |
| 33 | + } |
| 34 | + ; |
| 35 | + return obj; |
| 36 | + } |
| 37 | + |
| 38 | + public boolean unnamedExpressionForTryWithResources() { |
| 39 | + String url = "localhost"; |
| 40 | + String user = "user"; |
| 41 | + String pwd = "password"; |
| 42 | + try (Connection _ = DriverManager.getConnection(url, user, pwd)) { |
| 43 | + LOGGER.info(STR.""" |
| 44 | + DB Connection successful |
| 45 | + URL = \{url} |
| 46 | + usr = \{user} |
| 47 | + pwd = \{pwd}"""); |
| 48 | + } catch (SQLException e) { |
| 49 | + LOGGER.warning("Exception"); |
| 50 | + } |
| 51 | + return true; |
| 52 | + } |
| 53 | + |
| 54 | + public Map<String, List<String>> unnamedExpressionForLambda() { |
| 55 | + Map<String, List<String>> map = new HashMap<>(); |
| 56 | + map.computeIfAbsent("v1", _ -> new ArrayList<>()) |
| 57 | + .add("0.1"); |
| 58 | + return map; |
| 59 | + } |
| 60 | + |
| 61 | +} |
| 62 | + |
0 commit comments