How do I choose a value using a switch expression in Java?

A switch expression selects and returns a value based on an input. You can assign the result directly to a variable.

In this example, you will convert a day number into a day name.

Source code

public class SwitchExpressionExample {
    void main() {
        int dayNumber = 3;

        String dayName = switch (dayNumber) {
            case 1 -> "Monday";
            case 2 -> "Tuesday";
            case 3 -> "Wednesday";
            case 4 -> "Thursday";
            case 5 -> "Friday";
            case 6 -> "Saturday";
            case 7 -> "Sunday";
            default -> "Unknown day";
        };

        IO.println("Day number: " + dayNumber);
        IO.println("Day name: " + dayName);
    }
}

Explanation

The variable dayNumber holds the value to check:

int dayNumber = 3;

The switch expression compares this value with each case. When it finds a match, it returns the value after the arrow (->).

For example:

case 3 -> "Wednesday";

Since dayNumber is 3, the expression returns "Wednesday". The result is assigned to dayName.

Arrow rules do not fall through to the next case, so you do not need a break statement.

The default rule handles values that do not match any listed case:

default -> "Unknown day";

A switch expression must cover every possible input. In this example, default handles integers outside the range of 1 through 7.

Notice the semicolon after the closing brace:

};

It ends the variable declaration that assigns the result of the switch expression to dayName.

The program uses void main() and IO.println(), both supported in Java 25 without preview options.

Run the example

Compile and run the file:

javac SwitchExpressionExample.java
java SwitchExpressionExample

Output

Day number: 3
Day name: Wednesday

If you change dayNumber to 9, the output becomes:

Day number: 9
Day name: Unknown day

How do I check if a number is even or odd in Java?

You can check whether an integer is even or odd using the remainder operator (%).

An even number has a remainder of zero when divided by two. An odd number has a nonzero remainder.

Source code

public class EvenOddExample {
    public static void main(String[] args) {
        int number = 27;

        if (number % 2 == 0) {
            IO.println(number + " is even.");
        } else {
            IO.println(number + " is odd.");
        }
    }
}

Explanation

The variable number stores the integer to check:

int number = 27;

The % operator returns the remainder after division. The following expression checks whether dividing number by two leaves a remainder of zero:

number % 2 == 0

If the condition is true, the program prints that the number is even. Otherwise, it prints that the number is odd.

For 27, the remainder is 1, so the program runs the else block.

This check also works with negative integers and zero:

Number Remainder when divided by 2 Result
28 0 Even
27 1 Odd
-28 0 Even
-27 -1 Odd
0 0 Even

To check directly for an odd number, use number % 2 != 0. Checking for a remainder of 1 would miss negative odd numbers.

The program displays the result using IO.println(), which is available in Java 25. No import is required for java.lang.IO.

Run the example

Compile and run the file:

javac EvenOddExample.java
java EvenOddExample

Output

27 is odd.

Change number to 28 and run the program again:

28 is even.

How do I convert a double to an int in Java?

You can convert a double value to an int using an explicit cast. This removes the fractional part of the number.

This example converts both positive and negative values so you can see how the conversion works.

Source code

public class DoubleToIntExample {
    public static void main(String[] args) {
        double positiveValue = 42.75;
        double negativeValue = -42.75;

        int positiveResult = (int) positiveValue;
        int negativeResult = (int) negativeValue;

        System.out.println("Original positive value: " + positiveValue);
        System.out.println("Converted positive value: " + positiveResult);

        System.out.println("Original negative value: " + negativeValue);
        System.out.println("Converted negative value: " + negativeResult);
    }
}

Explanation

A double can store a fractional value, while an int stores a whole number within its supported range.

To convert a double to an int, place (int) before the value:

int positiveResult = (int) positiveValue;

The cast converts 42.75 to 42. It removes the fractional part instead of rounding to the nearest integer.

For negative numbers, the conversion also removes the fractional part:

int negativeResult = (int) negativeValue;

This converts -42.75 to -42, not -43. For finite values within the int range, the conversion truncates toward zero.

Java requires an explicit cast for this assignment because converting a double to an int can lose information. Without the cast, the following statement would cause a compilation error:

int positiveResult = positiveValue;

Run the example

With JDK 25 or later installed, compile and run the file:

javac DoubleToIntExample.java
java DoubleToIntExample

Output

Original positive value: 42.75
Converted positive value: 42
Original negative value: -42.75
Converted negative value: -42

Special values and limits

An int can store values from -2147483648 to 2147483647. Casting a double does not throw an exception when the value exceeds this range.

Input Result after casting to int
A value above the maximum int value Integer.MAX_VALUE
A value below the minimum int value Integer.MIN_VALUE
Double.POSITIVE_INFINITY Integer.MAX_VALUE
Double.NEGATIVE_INFINITY Integer.MIN_VALUE
Double.NaN 0

Use an explicit cast when you want to discard the fractional part. If you need rounding to the nearest integer, use a rounding method such as Math.round() instead; its double overload returns a long.

How do I declare and use variables in Java?

A variable stores a value that your program can use. For example, you can use variables to store a person’s name, age, or membership status.

In this example, you will declare variables, update a value, and print the results.

Source code

public class VariablesExample {
    public static void main(String[] args) {
        String name = "Alice";
        int age = 25;
        double heightInMeters = 1.68;
        boolean member = true;

        // Update an existing variable.
        age = age + 1;

        // Let the compiler infer the type from the initial value.
        var greeting = "Hello, " + name + "!";

        // A final variable cannot be reassigned.
        final int monthsInYear = 12;

        System.out.println(greeting);
        System.out.println("Age: " + age);
        System.out.println("Height: " + heightInMeters + " m");
        System.out.println("Member: " + member);
        System.out.println("Months in a year: " + monthsInYear);
    }
}

Explanation

To declare a variable with an explicit type, write the type, a name, and an optional initial value:

int age = 25;

Here, int is the type, age is the variable name, and 25 is its initial value. The = operator assigns the value to the variable.

The example uses these types:

Type Variable Purpose
String name Stores text
int age Stores a whole number
double heightInMeters Stores a floating-point number
boolean member Stores true or false

You can assign a new value to an existing variable without repeating its type:

age = age + 1;

This statement reads the current value of age, adds one, and stores the result back in age. Its value changes from 25 to 26.

For a local variable, you can also use var:

var greeting = "Hello, " + name + "!";

The compiler infers that greeting has the type String. Its type stays fixed after the declaration. A variable declared with var must have an initial value from which the compiler can determine its type. See the Java SE 25 specification on local variable declarations.

Use final when a variable should not be reassigned:

final int monthsInYear = 12;

Assigning another value to monthsInYear later would cause a compilation error.

Finally, System.out.println() prints each result on a separate line. The + operator joins text with the variable values.

Run the example

With JDK 25 or later installed, compile and run the file:

javac VariablesExample.java
java VariablesExample

Output

Hello, Alice!
Age: 26
Height: 1.68 m
Member: true
Months in a year: 12

All variables in this example are local variables because they are declared inside the main() method. Initialize local variables before reading their values, and choose names that make their purpose clear.

How do I Initialize Fields Before Calling super() in Java 25?

Java 25 includes JEP 513: Flexible Constructor Bodies. This feature changes a long-standing rule: before Java 22, the call to super(...) or this(...) had to be the very first statement in a constructor. Starting with Java 25, you can execute statements before the explicit constructor invocation — including initializing your own instance fields.

This is especially useful when a field’s value must be ready before the superclass constructor runs (for example, if the superclass calls an overridden method that reads that field).


The Old Restriction (Pre-Java 22)

public class Child extends Parent {
    private final int value;

    public Child(int input) {
        // Compile error before Java 22:
        // "call to super must be first statement in constructor"
        this.value = input * 2;
        super(computeSomething(input));
    }
}

The Java 25 Way: Prologue Before super(...)

With flexible constructor bodies, the constructor is split into two regions:

  1. Prologue — statements that run before super(...) or this(...).
  2. Epilogue — the usual constructor body that runs after.

Example 1: Initializing a Field Before super()

public class Parent {
    public Parent() {
        // Calls a method that subclasses may override
        describe();
    }

    protected void describe() {
        System.out.println("Parent describing");
    }
}

public class Child extends Parent {
    private final String label;

    public Child(String label) {
        // Java 25: initialize field BEFORE super()
        this.label = label;
        super();
    }

    @Override
    protected void describe() {
        // Safe: 'label' is already assigned, no NPE
        System.out.println("Child label = " + label);
    }
}

Before Java 25, label would still be null when Parent‘s constructor called the overridden describe(). Now you can assign it first.


The Prologue Rules You Must Follow

Inside the prologue (code before super(...) / this(...)), the compiler enforces strict rules to keep things safe:

Allowed Not Allowed
Assign to fields declared in this class Read fields of this
Validate / transform constructor arguments Call instance methods on this
Compute values, throw exceptions, use if, switch, loops, try Use this or super as a value
Call static methods Access inherited (superclass) fields

Example 2: Combining Validation and Field Init

public class Rectangle {
    protected final int area;

    public Rectangle(int area) {
        this.area = area;
    }
}

public class Square extends Rectangle {
    private final int side;

    public Square(int side) {
        // Prologue: validate, then initialize own field, then call super
        if (side <= 0) {
            throw new IllegalArgumentException("side must be positive");
        }
        this.side = side;          // assigning own field is allowed
        super(side * side);        // explicit constructor invocation
        // Epilogue starts here — 'this' is fully available
        System.out.println("Created Square with side=" + side + ", area=" + area);
    }
}

Example 3: Why This Matters — Fixing the “Leaked this” Problem

public abstract class Shape {
    public Shape() {
        render(); // calls subclass override during construction
    }
    protected abstract void render();
}

public class Circle extends Shape {
    private final double radius;

    public Circle(double radius) {
        this.radius = radius; // set before super() runs render()
        super();
    }

    @Override
    protected void render() {
        // Now 'radius' has its intended value, not 0.0
        System.out.println("Rendering circle with radius " + radius);
    }
}

Compiling and Running on Java 25

Since JEP 513 is a final feature in Java 25, no --enable-preview flag is required:

javac --release 25 Child.java Parent.java
java Child

Key Takeaways

  • You can now place statements — including assignments to your own fields — before super(...) or this(...).
  • The prologue cannot read this or call instance methods; it can only write to fields of the current class.
  • Exactly one explicit constructor invocation (super(...) or this(...)) is still required (implicitly or explicitly).
  • This feature is final in Java 25 — no preview flags needed.

This cleanly resolves cases where a subclass field needed to exist before the parent constructor ran, without resorting to static helpers or awkward factory methods.