Task - Control Flow Statements - Conditional Statements - Decision Making Statements - Switch with Pattern Matching #72
akash-coded
started this conversation in
Tasks
Replies: 3 comments
-
enum Status {
OPEN, WIP, REVIEW, FIX, CLOSED;
}
class StandardSwitchDemo {
public static void printNumberOfLetters() {
int numberOfLetters = -1;
Status status = Status.CLOSED;
if (status == null) {
System.out.println("Status null!");
} else {
switch (status) {
case WIP:
case FIX:
numberOfLetters = 3;
break;
case OPEN:
numberOfLetters = 4;
break;
case CLOSED:
case REVIEW:
numberOfLetters = 6;
break;
default:
throw new IllegalStateException("Invalid status: " + status);
}
}
System.out.println(numberOfLetters);
}
}
class PatternMatchingSwitchDemo {
@SuppressWarnings({ "preview", "null" })
public static void printNumberOfLetters() {
String status = null;
System.out.println(
switch (status) { // switch expression
case null -> "Status null!";
case "WIP", "FIX" -> 3; // arrow case labels
case "OPEN" -> 4;
case "CLOSED", "REVIEW" -> 6;
default -> throw new IllegalStateException("Invalid status: " + status);
});
}
}
public class SwitchPatternMatching {
public static void main(String[] args) {
System.out.println("Demonstrating standard switch-case:: ");
StandardSwitchDemo.printNumberOfLetters();
System.out.println();
System.out.println(
"Demonstrating modern switch-case with switch expression, arrow case labels, and pattern matching:: ");
PatternMatchingSwitchDemo.printNumberOfLetters();
System.out.println();
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
SwitchExamples.javapublic class SwitchExamples {
enum Color {
RED, GREEN, BLUE;
}
record Point(int x, int y) {
}
public static void main(String[] args) {
var ex = new SwitchExamples();
System.out.println("######################################");
ex.typeTester(Color.BLUE); // Color with 3 values
ex.typeTester(null);// null - Invalid Input
ex.typeTester(new Point(5, 6));// Record class: Point[x=5, y=6]
ex.typeTester(4D);// Something else
System.out.println("######################################");
System.out.println("######################################");
ex.typeTesterV2(4D);// Double Value: 4.0
ex.typeTesterV2(null);// null - Invalid Input
System.out.println("######################################");
System.out.println("######################################");
try {
ex.typeTesterV3(Color.GREEN);// GREEN
ex.typeTesterV3(null);// throw NullPointerException
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("######################################");
System.out.println("######################################");
ex.typeTesterV4(Color.GREEN);// Color is 3
ex.typeTesterV4(null);// null - Invalid Input
System.out.println("######################################");
}
void typeTester(Object obj) {
switch (obj) {
case null -> System.out.println("null - Invalid Input");
case String s -> System.out.println("String");
case Color c -> System.out.println("Color with " + c.values().length + " values");
case Point p -> System.out.println("Record class: " + p.toString());
case int[] ia -> System.out.println("Array of int values of length" + ia.length);
default -> System.out.println("Something else");
}
}
private void typeTesterV2(Double d) {
switch (d) {
case null -> System.out.println("null - Invalid Input");
case Double val -> System.out.println("Double Value: " + val);
}
}
private void typeTesterV3(Color color) {
switch (color) {
case null -> System.out.println("null - Invalid Input");
case RED -> System.out.println("RED");
case GREEN -> System.out.println("GREEN");
default -> System.out.println("Colorless");
}
}
private void typeTesterV4(Color color) {
switch (color) {
case null -> System.out.println("null - Invalid Input");
case Color obj -> System.out.println("Color is " + obj.name());
}
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
SwitchExamples.javapublic class SwitchExamples {
public static void main(String[] args) {
var ex = new SwitchExamples();
System.out.println("######################################");
System.out.println(ex.typePatternToDouble(4.98F));
System.out.println(ex.typePatternToDouble(500L));
System.out.println(ex.typePatternToDouble(657));
System.out.println(ex.typePatternToDouble("874"));
System.out.println(ex.typePatternToDouble(null));
System.out.println(ex.typePatternToDouble(List.of(5)));
System.out.println("######################################");
System.out.println("######################################");
System.out.println(ex.guardedPatternToDouble("7"));
System.out.println(ex.guardedPatternToDouble(""));
System.out.println("######################################");
System.out.println("######################################");
System.out.println(ex.parenthesizedPatternToDouble("563#"));
System.out.println(ex.parenthesizedPatternToDouble("53@"));
System.out.println(ex.parenthesizedPatternToDouble("84"));
System.out.println("######################################");
}
Double typePatternToDouble(Object obj) {
return switch (obj) {
case null -> 0D;
case String s -> Double.valueOf(s);
case Integer i -> Double.valueOf(i);
case Long val -> Double.valueOf(val);
case Float val -> Double.valueOf(val);
default -> 0D;
};
}
Double guardedPatternToDouble(Object obj) {
return switch (obj) {
case null -> 0D;
case String s -> {
if (s.length() > 0) {
yield Double.valueOf(s);
} else {
yield 0D;
}
}
case Integer i -> Double.valueOf(i);
case Long val -> Double.valueOf(val);
case Float val -> Double.valueOf(val);
default -> 0D;
};
}
Double parenthesizedPatternToDouble(Object obj) {
return switch (obj) {
case null -> 0D;
case String s && !(s.contains("@") || s.contains("#")) -> {
if (s.length() > 0) {
yield Double.valueOf(s);
} else {
yield 0D;
}
}
case Integer i -> Double.valueOf(i);
case Long val -> Double.valueOf(val);
case Float val -> Double.valueOf(val);
default -> 0D;
};
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment


Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Pattern Matching for Switch
Introduced as a preview feature in Java 17
The Java SE 17 release introduces pattern matching for switch expressions and statements (JEP 406) as a preview feature. Pattern matching provides us with more flexibility when defining conditions for switch cases.
In addition to case labels that can now contain patterns, the selector expression is no longer limited to just a few types. Before pattern matching, switch cases supported simple testing of a selector expression that needs to match a constant value exactly.
Pattern Matching
Pattern matching, in general, was first introduced as a preview feature in Java SE 14.
It was limited to only one form of a pattern – the type pattern. A typical pattern consists of a type name and the variable to bind the result to.
Applying type patterns to the instanceof operator simplifies type checking and casting. Moreover, it enables us to combine both into a single expression:
This built-in language enhancement helps us write less code with enhanced readability. Pattern matching for instanceof became a permanent feature in Java SE 16.
Patterns for Switch
With Java 17, pattern matching now also expands to switch expressions.
However, it is still a preview feature, so we need to enable preview to use it:
We have the following types of patterns:
Tasks
Type Pattern
Create a method that converts different types to
doubleusingif-elsestatements. The methods takes an argument of typeObjectand returns the converteddoubleresult. The method returns zero if the type is not supported.Then write another method that does the same using
switchstatement with pattern matching.(Hint - You can use the built-in wrapper classes such as
Integer,Float, andStringin the case labels.)Guarded Pattern
switchstatement with pattern matching, update the case with theStringlabel to check for the length of the String. Perform the conversion todouble, only if the length is greater than zero.Parenthesized Pattern
Stringlabel further to additionally check that the input String neither contains "#" nor "@".Beta Was this translation helpful? Give feedback.
All reactions