Java 24: Simplifying Code with New Features

Java 24 introduces several exciting features that simplify code writing and enhance developer productivity. Let’s explore some of these new additions.

JEP 495: Simple Source Files and Instance Main Methods

Java 24 allows you to write code without the traditional public class syntax. Now, you can create a HelloWorld.java file with just the following code:

void main() {
println("Hello new world");
}

This code is perfectly valid and will produce the output:

Output : Hello new world

Behind the scenes, the JDK creates a Java class and places this method into it

Overloading Main Methods

With this new feature, you can overload the main method just like any other method:

void main() {
main("New World");
}

static int main(String s) {
println("Hello " + s);
return 0;
}


Output : Hello New World

JEP 488: Primitive Types in Patterns, instanceof, and switch

Java 24 now allows primitive types to be used in patterns, instanceof, and switch statements

Switch Expressions with Primitives
Here’s an example of using primitive types in a switch expression:

public static String getAgeLevel(int age) {
return switch(age) {
case int i when i < 13 -> "Child";
case int i when i < 20 -> "Teenager";
case int i when i < 60 -> "Adult";
default -> "Senior";
};
}

instanceof with Primitives
You can now use instanceof with primitive types:

int value = 42;
if (value instanceof int i) {
println("The value " + i + " is an int");
}

JEP 494: Module Import Declarations

Java 24 introduces a new way to import multiple Java classes using module import declarations. Instead of importing individual classes, you can now import an entire module.

package com.java24.practice;

import java.util.List;
import java.util.stream.Collectors;


//above can be replaced with single line

import module java.base;

public class SimpleTest {
public static void main(String ... args) {
var words = List.of("hello", "fuzzy", "world");
var greeting = words.stream()
.filter(w -> !w.contains("z"))
.collect(Collectors.joining(", "));
System.out.println(greeting); // hello, world
}
}

This module import internally includes multiple necessary Java libraries by default, such as java.iojava.langjava.mathjava.netjava.niojava.securityjava.textjava.timejava.utiljava.crypto, and more.

Leave a comment