Variables & The Static Type System

ভ্যারিয়েবল ও Static Type System

Read: ~25 min Beginner 5 practice problems Live code runner

1. Java Is Statically Typed

In Java, every variable has a type known at compile time. You cannot assign a String where an int is expected — the compiler stops you before the program ever runs. This is the opposite of dynamically typed languages like Python or JavaScript, where the same mismatch would crash at runtime.

Java-তে প্রতিটি variable-এর একটি নির্দিষ্ট type থাকে যা compile time-এই ঠিক হয়ে যায়। int-এ String বসাতে গেলে compiler ধরে ফেলবে — কোড চালানোর আগেই। Python/JavaScript-এ এই ভুল runtime-এ crash করত। এতে অনেক bug আগেই ধরা পড়ে।

2. Declaration vs Initialization

Declaration announces a variable's name and type. Initialization gives it a first value. You can do both at once, or split them.

Main.java
class Main {
    public static void main(String[] args) {
        int age;              // declaration only
        age = 21;              // initialization later

        String name = "Arif"; // declare + initialize

        double balance;
        // System.out.println(balance); // compile error — not initialized

        balance = 1500.50;
        System.out.println(name + " (" + age + ") : ৳" + balance);
    }
}
Local variable ব্যবহারের আগে অবশ্যই initialize করতে হবে — না করলে compile error। Field (class-এর ভেতরে declared variable) default মান পায় (0, null, false)।

3. Scope — Where a Variable Lives

A variable's scope is the block { ... } in which it is declared. Outside that block, the name is gone.

Main.java
class Main {
    static int count = 0;     // field: visible in every method of Main

    public static void main(String[] args) {
        int x = 10;            // local to main
        if (x > 0) {
            int y = 5;          // only lives in this if-block
            System.out.println("inside: " + (x + y));
        }
        // System.out.println(y); // compile error — y out of scope
        count++;
        System.out.println("count = " + count);
    }
}
Scope মানে variable-এর জীবনকাল। if block-এর ভেতরে declared variable শুধু সেই block-এ থাকে। Class-এর সরাসরি সদস্য (field) class-এর সব method-এ ব্যবহারযোগ্য।

4. final — Write Once

A final variable can be assigned exactly once. Use it for constants, and for local values that should never change — the compiler will enforce it.

Main.java
class Main {
    static final double VAT_RATE = 0.15;  // constant — UPPER_CASE convention

    public static void main(String[] args) {
        final int hoursInDay = 24;
        // hoursInDay = 25; // compile error

        double price = 1000;
        double total = price * (1 + VAT_RATE);
        System.out.printf("%d hours, total ৳%.2f%n", hoursInDay, total);
    }
}
final মানে একবারই মান বসানো যাবে। class-level constants-এ static final ব্যবহার করুন এবং UPPER_CASE-এ নাম দিন — Java community-র convention।

5. var — Local Type Inference (Java 10+)

Since Java 10, var tells the compiler: "figure out the type from the right-hand side". The variable is still strongly typed — it's just written more concisely. var works only on local variables with an initializer.

Main.java
import java.util.*;

class Main {
    public static void main(String[] args) {
        var name = "Nila";                     // inferred String
        var age  = 22;                          // inferred int
        var scores = new ArrayList<Integer>();  // inferred ArrayList<Integer>

        scores.add(90); scores.add(85);
        System.out.println(name + "(" + age + ") " + scores);

        // var bad;          // error — no initializer, cannot infer
        // var x = null;     // error — null has no type
    }
}
Style: use var when the right-hand side makes the type obvious (var list = new ArrayList<String>();) and skip it when the type would improve readability. var is a convenience, not a command.
var মানে JavaScript-এর মতো dynamic type নয়; type compile-time-এই ঠিক হয়ে যায়, শুধু আপনাকে লিখতে হয় না। সীমা — local variable, initializer লাগবে, null দিয়ে শুরু করা যায় না।

6. Compile-time Type Safety

Java's compiler refuses to compile nonsense. This seemingly pedantic behavior catches a huge class of bugs before they ever run.

Main.java
class Main {
    public static void main(String[] args) {
        int n = 10;
        String s = "abc";

        // n = s;          // ❌ compile error
        // s = n;          // ❌ compile error

        s = Integer.toString(n);       // ✅ explicit conversion
        n = Integer.parseInt("42");      // ✅ explicit parse
        System.out.println(s + " / " + n);
    }
}
Java বলছে — এক type-এর value অন্য type-এ বসাতে চাইলে স্পষ্টভাবে রূপান্তর (conversion) দেখাতে হবে। এতে অসাবধান bug runtime-এ আটকায় না, compile time-এই ধরা পড়ে।

7. Widening vs Narrowing Conversions

Small-to-big conversions (widening) are automatic. Big-to-small (narrowing) needs an explicit cast and may lose data.

Main.java
class Main {
    public static void main(String[] args) {
        int a = 100;
        long b = a;              // ✅ widening, automatic
        double d = a;            // ✅ int → double

        double pi = 3.14;
        // int bad = pi;         // ❌ narrowing not allowed implicitly
        int truncated = (int) pi; // ✅ explicit cast → 3

        System.out.println(b + " / " + d + " / " + truncated);
    }
}
ছোট থেকে বড় type-এ (int → long → double) auto রূপান্তর হয়। বড় থেকে ছোট-এ (double → int) explicit cast লাগবে, এবং ভগ্নাংশ / precision হারাতে পারে।

8. Vocabulary

TermMeaningবাংলায়
Static typingTypes checked at compile time.Compile-time-এ type check।
Dynamic typingTypes checked at runtime (Python, JS).Runtime-এ type check।
ScopeRegion of code where a name is visible.variable-এর দৃশ্যমান অঞ্চল।
finalVariable/parameter/field that can be assigned once.একবারই মান বসানো যাবে।
varLocal type inference (Java 10+).local variable-এ type অনুমান।
WideningSmall → large numeric conversion (implicit).ছোট থেকে বড় type-এ রূপান্তর।
NarrowingLarge → small numeric conversion (explicit cast).বড় থেকে ছোট type-এ cast।

9. Practice Problems

  1. Declare a final double constant for the USD-BDT rate = 122.50 and convert 100 USD to BDT.
    USD-BDT হার (১২২.৫০) final constant বানিয়ে ১০০ USD → BDT print করুন।
    ✨ Show Answer (উত্তর দেখুন)
    Main.java
    class Main {
        static final double USD_BDT = 122.50;
        public static void main(String[] args) {
            double usd = 100;
            System.out.printf("%.2f USD = %.2f BDT%n", usd, usd * USD_BDT);
        }
    }
  2. Use var to declare three different variables (a String, an int, and an ArrayList of String). Print all three.
    var দিয়ে তিন ধরনের variable declare করে print করুন।
    ✨ Show Answer (উত্তর দেখুন)
    Main.java
    import java.util.*;
    class Main {
        public static void main(String[] args) {
            var city = "Dhaka";
            var pop  = 22_000_000;
            var cities = new ArrayList<String>();
            cities.add("Dhaka"); cities.add("Chattogram");
            System.out.println(city + " : " + pop);
            System.out.println(cities);
        }
    }
  3. Explain: why will int x; System.out.println(x); fail to compile, but a field int x; at class level will not?
    method-এ int x;-এ compile error, কিন্তু class-এ field হিসেবে নয় — কেন?
    ✨ Show Answer (উত্তর দেখুন)

    Answer: Java only auto-initializes class fields (to 0 / null / false). Local variables have no default — the compiler's "definite assignment" check forces you to assign before use, precisely to stop you reading uninitialised memory. This was a deliberate Gosling-era design decision to close a whole category of C/C++ bugs.

  4. Write a program that truncates 7.9 to an int, and rounds 7.9 to the nearest int using Math.round. Print both.
    7.9-কে truncate এবং Math.round দিয়ে round করে দুটি মান print করুন।
    ✨ Show Answer (উত্তর দেখুন)
    Main.java
    class Main {
        public static void main(String[] args) {
            double d = 7.9;
            int trunc = (int) d;
            long rounded = Math.round(d);
            System.out.println("truncated = " + trunc);
            System.out.println("rounded   = " + rounded);
        }
    }
  5. In 2 sentences, give one advantage and one disadvantage of static typing versus dynamic typing.
    static vs dynamic typing — একটি সুবিধা ও একটি অসুবিধা।
    ✨ Show Answer (উত্তর দেখুন)

    Advantage: compile-time errors catch whole categories of bugs (typos, wrong parameter type) before the program ever runs, and the IDE can give razor-sharp auto-completion and refactoring. Disadvantage: you write more boilerplate (types, generics), and prototyping is slower because you must satisfy the type-checker for every intermediate value.

Summary — Module 06

Java is statically typed: every variable has a compile-time type, and illegal assignments are rejected before the program runs. Declaration and initialization may be separate, but local variables must be definitely assigned before use. final gives you write-once variables and the standard way to define constants. var (Java 10+) saves keystrokes without sacrificing type safety. Widening conversions are automatic; narrowing ones need an explicit cast.

Java static typing — compile time-এই type mismatch ধরা পড়ে। Local variable ব্যবহারের আগে value দিতে হবে। final একবারই assign, var type অনুমান করে। ছোট→বড় auto, বড়→ছোট cast।

Next Module → Operators — arithmetic, comparison, logical, bitwise.