Java 14 - New Features

Hello there, aspiring Java programmers! I'm thrilled to guide you through the exciting world of Java 14 and its new features. As someone who's been teaching computer science for years, I can assure you that learning Java is like embarking on an adventure – there's always something new to discover. So, let's dive in and explore the wonders of Java 14 together!

Java 14 - New Features

Java Control Statements

Before we delve into the new features of Java 14, let's quickly recap some fundamental control statements. These are the building blocks of any Java program, and understanding them is crucial for mastering the language.

If-Else Statement

The if-else statement is like a fork in the road – it allows your program to make decisions based on certain conditions.

int age = 18;
if (age >= 18) {
    System.out.println("You can vote!");
} else {
    System.out.println("Sorry, you're too young to vote.");
}

In this example, if the age is 18 or above, the program will print "You can vote!". Otherwise, it will print "Sorry, you're too young to vote."

For Loop

The for loop is like a merry-go-round – it allows you to repeat a block of code a specified number of times.

for (int i = 1; i <= 5; i++) {
    System.out.println("Count: " + i);
}

This loop will print the numbers 1 to 5, each on a new line.

Object Oriented Programming

Java is an object-oriented programming (OOP) language, which means it's based on the concept of "objects" that contain data and code. Let's look at a simple class example:

public class Dog {
    String name;
    int age;

    public void bark() {
        System.out.println(name + " says: Woof!");
    }
}

Here, we've defined a Dog class with properties (name and age) and a method (bark). You can create and use objects of this class like this:

Dog myDog = new Dog();
myDog.name = "Buddy";
myDog.age = 3;
myDog.bark(); // Output: Buddy says: Woof!

Java Built-in Classes

Java provides many built-in classes that make our lives easier. One of the most commonly used is the String class.

String greeting = "Hello, Java 14!";
System.out.println(greeting.length()); // Output: 16
System.out.println(greeting.toUpperCase()); // Output: HELLO, JAVA 14!

Java File Handling

File handling is crucial for many applications. Here's a simple example of writing to a file:

import java.io.FileWriter;
import java.io.IOException;

public class FileWriteExample {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("output.txt");
            writer.write("Hello, Java 14!");
            writer.close();
            System.out.println("Successfully wrote to the file.");
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

This code creates a file named "output.txt" and writes "Hello, Java 14!" to it.

Java Error & Exceptions

Errors and exceptions are a part of programming life. Java provides a robust mechanism to handle them. Here's an example:

public class DivisionExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Cannot divide by zero!");
        }
    }
}

This program attempts to divide by zero, which would normally cause an error. However, we've wrapped it in a try-catch block to handle the exception gracefully.

New Features in Java 14

Now, let's explore some of the exciting new features introduced in Java 14!

Records

Records are a new kind of class in Java 14 that make it easy to create simple, immutable data carriers. They're perfect for when you just need a class to hold some data.

public record Person(String name, int age) { }

This simple declaration creates a class with two fields (name and age), a constructor, and methods like equals(), hashCode(), and toString(). It's equivalent to a much longer traditional class definition!

Pattern Matching for instanceof

Java 14 introduces an improved version of the instanceof operator that includes pattern matching. This makes your code more concise and readable.

if (obj instanceof String s) {
    // can use s as a String here
    System.out.println(s.length());
}

In this example, if obj is a String, it's automatically cast to a String and assigned to the variable s.

Switch Expressions

Switch expressions, which were previewed in earlier versions, are now standard in Java 14. They allow you to use switch as an expression and yield a value.

String dayType = switch(dayOfWeek) {
    case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Weekday";
    case SATURDAY, SUNDAY -> "Weekend";
};

This switch expression assigns "Weekday" or "Weekend" to dayType based on the value of dayOfWeek.

Helpful NullPointerExceptions

Java 14 provides more helpful NullPointerException messages, pinpointing exactly which variable was null.

Person person = null;
System.out.println(person.name);

Instead of a generic NullPointerException, you'll get a message like "Cannot invoke "Person.getName()" because "person" is null".

These are just a few of the new features in Java 14. As you continue your Java journey, you'll discover many more exciting capabilities of this powerful language. Remember, programming is a skill that improves with practice, so don't be afraid to experiment and write lots of code!

Happy coding, future Java experts!

Credits: Image by storyset