Variables & The Static Type System
ভ্যারিয়েবল ও Static Type System
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.
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.
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);
}
}
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.
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);
}
}
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.
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.
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
}
}
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.
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);
}
}
7. Widening vs Narrowing Conversions
Small-to-big conversions (widening) are automatic. Big-to-small (narrowing) needs an explicit cast and may lose data.
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);
}
}
int → long → double) auto রূপান্তর হয়। বড় থেকে ছোট-এ (double → int) explicit cast লাগবে, এবং ভগ্নাংশ / precision হারাতে পারে।
8. Vocabulary
| Term | Meaning | বাংলায় |
|---|---|---|
| Static typing | Types checked at compile time. | Compile-time-এ type check। |
| Dynamic typing | Types checked at runtime (Python, JS). | Runtime-এ type check। |
| Scope | Region of code where a name is visible. | variable-এর দৃশ্যমান অঞ্চল। |
| final | Variable/parameter/field that can be assigned once. | একবারই মান বসানো যাবে। |
| var | Local type inference (Java 10+). | local variable-এ type অনুমান। |
| Widening | Small → large numeric conversion (implicit). | ছোট থেকে বড় type-এ রূপান্তর। |
| Narrowing | Large → small numeric conversion (explicit cast). | বড় থেকে ছোট type-এ cast। |
9. Practice Problems
-
Declare a
final doubleconstant for the USD-BDT rate = 122.50 and convert 100 USD to BDT.USD-BDT হার (১২২.৫০) final constant বানিয়ে ১০০ USD → BDT print করুন।✨ Show Answer (উত্তর দেখুন)
Main.javaclass 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); } } -
Use
varto declare three different variables (a String, an int, and an ArrayList of String). Print all three.var দিয়ে তিন ধরনের variable declare করে print করুন।✨ Show Answer (উত্তর দেখুন)
Main.javaimport 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); } } -
Explain: why will
int x; System.out.println(x);fail to compile, but a fieldint 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. -
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.javaclass 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); } } -
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.
final একবারই assign, var type অনুমান করে। ছোট→বড় auto, বড়→ছোট cast।