Core Java

core2Variables

Path
pkg1core/core2Variables.java
Package
pkg1core
Study order
1
Run
Single-file source launch
Command
java pkg1core/core2Variables.java
Lesson
Back to the chapter

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg1core/core2Variables.java
1package pkg1core;2 3/*4 * core2Variables.java5 * --------------6 * Declaring and using variables: local, instance, static, final, and `var`.7 *8 * EXPLANATION:9 *  - Local variables live on the stack and must be initialized before use.10 *  - Instance variables belong to an object (one per instance).11 *  - Static (class) variables are shared across all instances.12 *  - `final` makes a variable a constant (cannot be reassigned).13 *  - `var` (Java 10+) infers the type for LOCAL variables only.14 */15public class core2Variables {16 17    static int instanceCounter = 0;   // static: shared by all objects18    int id;                            // instance: one per object19    final String label;                // final: assigned once (in constructor)20 21    core2Variables(String label) {22        this.label = label;            // `this` distinguishes field from param23        this.id = ++instanceCounter;   // shared counter increments per object24    }25 26    public static void main(String[] args) {27        // Local variables with explicit types28        int age = 30;29        double price = 19.99;30        boolean active = true;31        char grade = 'A';32 33        // `var` infers the type from the right-hand side (still statically typed)34        var message = "var infers String";35        var pi = 3.14159;              // inferred as double36 37        final int MAX = 100;           // constant; reassigning is a compile error38 39        System.out.println("age=" + age + ", price=" + price + ", active=" + active + ", grade=" + grade);40        System.out.println(message + " | pi=" + pi + " | MAX=" + MAX);41 42        // Instance vs static demonstration43        core2Variables a = new core2Variables("first");44        core2Variables b = new core2Variables("second");45        System.out.println(a.label + " -> id " + a.id);46        System.out.println(b.label + " -> id " + b.id);47        System.out.println("Total created (static counter): " + instanceCounter);48    }49}