🧠 Java Quiz

Java Variables

Containers for data — typed, named, and scoped.

Declaring a variable

In Java, every variable has a type declared upfront. The compiler enforces it.

Declaration syntax
int age = 28;
String name = "Raman";
double salary = 75000.50;
boolean isActive = true;
char grade = 'A';

Declaration vs initialization

You can split declaration and assignment:

Two-step declaration
int count;          // declared, not initialized
count = 10;            // assigned later

String message = "Hello";  // declared and initialized

Local variables must be initialized before use

Inside methods, a variable that's never been assigned will fail to compile if you try to read it. This is a good thing — it catches bugs early.

Won't compile
int x;
System.out.println(x);  // Error: variable x might not have been initialized

Constants — final variables

Use final for values that shouldn't change after assignment:

final keyword
final double PI = 3.14159;
final int MAX_RETRIES = 3;

PI = 3.14;  // Compile error: cannot assign a value to final variable PI

Type inference with var (Java 10+)

Modern Java lets the compiler infer the type from the right-hand side using var:

var keyword
var name = "Raman";        // inferred as String
var age = 28;               // inferred as int
var prices = new ArrayList<Double>();  // inferred as ArrayList<Double>

Variable scope

A variable is only accessible inside the block where it's declared:

Scope
public class ScopeDemo {
    static int classLevel = 10;       // class scope (static field)

    public static void main(String[] args) {
        int methodLevel = 20;             // method scope

        if (methodLevel > 0) {
            int blockLevel = 30;          // block scope only
            System.out.println(blockLevel);
        }

        // blockLevel is no longer accessible here — compile error if used
    }
}

Naming rules

Names are documentation A method named calculateMonthlyInterest() tells the reader what it does without comments. calc() needs a comment and a sigh.