Java 11 - New Features

Hello there, aspiring Java programmers! I'm thrilled to be your guide on this exciting journey into the world of Java 11. As someone who's been teaching computer science for many years, I've seen countless students go from complete beginners to confident coders. So, don't worry if you're starting from scratch – we'll take it step by step, and before you know it, you'll be writing Java code like a pro!

Java 11 - New Features

Java Control Statements

Let's start with the basics. Control statements are like the traffic lights of programming – they direct the flow of your code. In Java 11, we have some nifty ways to control our program's execution.

If-Else Statements

The if-else statement is probably the most common control structure you'll use. It's like making a decision in real life. Here's a simple example:

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 code, we're checking if the age variable is 18 or older. If it is, we print that the person can vote. If not, we tell them they're too young. It's that simple!

Switch Statements

Switch statements are great when you have multiple conditions to check. Think of it as a more efficient way to write several if-else statements. Java 11 introduced some cool improvements to switch statements. Here's an example:

String day = "Monday";
switch (day) {
    case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> System.out.println("Weekday");
    case "Saturday", "Sunday" -> System.out.println("Weekend");
    default -> System.out.println("Invalid day");
}

This switch statement checks the day variable and prints whether it's a weekday or weekend. The arrow syntax (->) is new in Java 11 and makes the code more concise.

Object Oriented Programming

Object-Oriented Programming (OOP) is a fundamental concept in Java. It's like building with LEGO blocks – you create different objects that interact with each other to form your program.

Classes and Objects

A class is like a blueprint for creating objects. Here's a simple class representing a car:

public class Car {
    String make;
    String model;
    int year;

    public void startEngine() {
        System.out.println("Vroom! The " + year + " " + make + " " + model + " is starting.");
    }
}

Now, let's create an object from this class:

Car myCar = new Car();
myCar.make = "Toyota";
myCar.model = "Corolla";
myCar.year = 2021;
myCar.startEngine();

When you run this code, it will print: "Vroom! The 2021 Toyota Corolla is starting."

Java Built-in Classes

Java comes with a rich set of built-in classes that make our lives easier. Let's look at a few:

String Class

The String class is used to manipulate text. Here's an example:

String greeting = "Hello, World!";
System.out.println(greeting.length());  // Prints: 13
System.out.println(greeting.toUpperCase());  // Prints: HELLO, WORLD!

ArrayList Class

ArrayList is a dynamic array that can grow or shrink as needed:

import java.util.ArrayList;

ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
System.out.println(fruits);  // Prints: [Apple, Banana, Cherry]

Java File Handling

File handling is crucial for reading from and writing to files. Java 11 introduced some new methods to make this easier:

import java.nio.file.Files;
import java.nio.file.Path;

String content = "Hello, Java 11!";
Path filePath = Path.of("example.txt");
Files.writeString(filePath, content);

String readContent = Files.readString(filePath);
System.out.println(readContent);  // Prints: Hello, Java 11!

This code writes a string to a file and then reads it back. The writeString and readString methods are new in Java 11 and make file I/O much simpler.

Java Error & Exceptions

Errors and exceptions are like the bumps and potholes on the road of programming. Java helps us handle these gracefully:

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Oops! You can't divide by zero.");
} finally {
    System.out.println("This always runs, error or not.");
}

This code tries to divide by zero (which is a no-no in math), catches the resulting exception, and prints a friendly message instead of crashing.

Java Multithreading

Multithreading is like juggling – it allows your program to do multiple things at once. Here's a simple example:

class MyThread extends Thread {
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getId() + " Value " + i);
        }
    }
}

public class Main {
    public static void main(String args[]) {
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
        t1.start();
        t2.start();
    }
}

This creates two threads that run concurrently, each printing their thread ID and a value.

Java Synchronization

When multiple threads are accessing shared resources, we need to synchronize them to avoid conflicts. It's like having traffic lights at an intersection:

class Counter {
    private int count = 0;
    public synchronized void increment() {
        count++;
    }
    public int getCount() {
        return count;
    }
}

The synchronized keyword ensures that only one thread can execute the increment method at a time.

Java Networking

Java makes it easy to create networked applications. Here's a simple server that listens for connections:

import java.net.*;
import java.io.*;

public class SimpleServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        System.out.println("Server is listening on port 8080");
        Socket socket = serverSocket.accept();
        System.out.println("Client connected");
    }
}

This server listens on port 8080 and prints a message when a client connects.

Java Collections

Java collections are like different types of containers for storing objects. Let's look at a few:

List

import java.util.*;

List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
System.out.println(fruits);  // Prints: [Apple, Banana]

Set

Set<Integer> numbers = new HashSet<>();
numbers.add(1);
numbers.add(2);
numbers.add(1);  // Duplicate, won't be added
System.out.println(numbers);  // Prints: [1, 2]

Map

Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);
System.out.println(ages.get("Alice"));  // Prints: 25

Java Interfaces

Interfaces are like contracts that classes can agree to follow. Here's an example:

interface Animal {
    void makeSound();
}

class Dog implements Animal {
    public void makeSound() {
        System.out.println("Woof!");
    }
}

class Cat implements Animal {
    public void makeSound() {
        System.out.println("Meow!");
    }
}

Both Dog and Cat implement the Animal interface, agreeing to provide a makeSound method.

Java Data Structures

Data structures are ways of organizing and storing data. Let's look at a simple linked list:

class Node {
    int data;
    Node next;

    Node(int d) { data = d; }
}

class LinkedList {
    Node head;

    public void add(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
        } else {
            Node current = head;
            while (current.next != null) {
                current = current.next;
            }
            current.next = newNode;
        }
    }

    public void print() {
        Node current = head;
        while (current != null) {
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println();
    }
}

public class Main {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.add(1);
        list.add(2);
        list.add(3);
        list.print();  // Prints: 1 2 3
    }
}

This code implements a simple linked list data structure.

Java Collections Algorithms

Java provides many useful algorithms for working with collections. Here's an example of sorting:

import java.util.*;

List<Integer> numbers = new ArrayList<>(Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5));
Collections.sort(numbers);
System.out.println(numbers);  // Prints: [1, 1, 2, 3, 4, 5, 5, 6, 9]

Advanced Java

As you progress, you'll encounter more advanced Java concepts. One such concept is lambda expressions, introduced in Java 8 and further improved in Java 11:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.forEach(n -> System.out.println(n * 2));

This code uses a lambda expression to multiply each number by 2 and print it.

Java Miscellaneous

Java 11 introduced several miscellaneous features. One of them is the var keyword for local variable type inference:

var message = "Hello, Java 11!";
System.out.println(message);

The compiler infers that message is a String.

Java APIs & Frameworks

Java has a vast ecosystem of APIs and frameworks. One popular framework is Spring Boot. Here's a simple "Hello World" Spring Boot application:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class HelloWorldApplication {

    public static void main(String[] args) {
        SpringApplication.run(HelloWorldApplication.class, args);
    }

    @GetMapping("/")
    public String hello() {
        return "Hello, World!";
    }
}

This creates a web application that responds with "Hello, World!" when you visit the root URL.

Java Class References

Java allows you to get references to classes at runtime. Here's an example:

Class<?> stringClass = String.class;
System.out.println(stringClass.getName());  // Prints: java.lang.String

Java Useful Resources

Here are some useful resources for learning Java:

  1. Oracle's official Java documentation
  2. Codecademy's Java course
  3. "Head First Java" book
  4. Stack Overflow for asking questions

New Features

Java 11 introduced several new features. Here's a table summarizing some of them:

Feature Description
Local-Variable Syntax for Lambda Parameters Allows var in lambda expressions
HTTP Client (Standard) Standardized HTTP client API
Launch Single-File Source-Code Programs Run Java source files directly
String Methods New methods like isBlank(), lines(), strip(), etc.
Files Methods New methods like readString(), writeString()

That's it for our whirlwind tour of Java 11! Remember, learning to code is like learning a new language – it takes practice, patience, and perseverance. Don't be discouraged if you don't understand everything right away. Keep coding, keep experimenting, and most importantly, keep having fun! Before you know it, you'll be writing complex Java applications and wondering how it all seemed so difficult at first. Happy coding!

Credits: Image by storyset