Java 25 Example: Primitive Pattern Matching
/* In java 25 you need explicit definition of class and main method, just for start it's easy to understand the execution.
* But in real Object-Oriented applications you cannot go without classes and inheritance */
void main(){
int i = 3;
char any = 'P';
oldWayOfUnBoxing(i);
oldWayOfUnBoxing(any);
checkObject(i);
checkObject(any);
}
static void oldWayOfUnBoxing(Object obj) {
if (obj instanceof Integer) {
int i = ((Integer) obj).intValue(); // First obj is boxed to Integer then unboxed to int with .intValue of Integer class
log("Primitive obj of type int is converted/unboxed to int with Integer class");
}
if (obj instanceof Character) {
char c = ((Character) obj).charValue(); // First obj is boxed to Character then unboxed to char with .charValue of Character class
log("Primitive obj of type char is converted/unboxed to char with Character class");
}
}
/* Feature: primitive types in Java’s pattern-matching framework introduced in JEP 507 */
static void checkObject(Object o){
if(o instanceof int i){ // if o is type int then bind it to i, no extra boilerplate code.
log("primitive int is converted to int without any extra unboxing");
}
if(o instanceof char c){ // if o is type char then bind it to c
log("primitive char is converted to char without any extra unboxing");
}
}
static void log(String msg){
System.out.println(msg);
}
If you face any issue to run this code, just for your information this feature in Java is still in preview — you need to enable this while compilation.
First copy the code and create a file with any name like
Place the file inside the
Then run the following commands:
Then simply run the program with:
First copy the code and create a file with any name like
PatternMatching.java
Place the file inside the
jdk-25/bin/
folder.Then run the following commands:
javac --enable-preview --release 25 PatternMatching.java
Then simply run the program with:
java --enable-preview PatternMatching
(pransukh.21@gmail.com)
Comments
Post a Comment
Thanks in anticipation.