0
0
Javaprogramming~20 mins

Variable declaration and initialization in Java - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Variable Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of variable initialization with expressions
What is the output of the following Java code?
Java
public class Main {
    public static void main(String[] args) {
        int a = 5;
        int b = a * 2;
        int c = b - a / 5;
        System.out.println(c);
    }
}
A9
B10
C8
D7
Attempts:
2 left
💡 Hint
Remember the order of operations: division before subtraction.
Predict Output
intermediate
2:00remaining
Value of variable after multiple declarations
What is the value of variable num after running this code?
Java
public class Main {
    public static void main(String[] args) {
        int num = 10;
        num = num + 5;
        num = num * 2;
        System.out.println(num);
    }
}
A15
B20
C30
D25
Attempts:
2 left
💡 Hint
Follow the operations step by step.
Predict Output
advanced
2:00remaining
Output with uninitialized local variable
What error or output does this code produce?
Java
public class Main {
    public static void main(String[] args) {
        int x;
        // System.out.println(x); // Uncommenting this line causes error
        x = 5;
        System.out.println(x);
    }
}
A0
B5
CCompilation error: variable x might not have been initialized
DRuntime error
Attempts:
2 left
💡 Hint
The variable is assigned before printing.
Predict Output
advanced
2:00remaining
Output of variable shadowing in nested blocks
What is the output of this Java program?
Java
public class Main {
    public static void main(String[] args) {
        int val = 10;
        {
            int val = 20;
            System.out.println(val);
        }
        System.out.println(val);
    }
}
ACompilation error due to duplicate variable declaration
B10\n20
C20\n10
D20\n20
Attempts:
2 left
💡 Hint
Java allows redeclaring a variable in an inner block (shadowing).
🧠 Conceptual
expert
3:00remaining
Understanding default values of instance variables
Consider the following Java class. What is the output when new Test().printValues(); is called?
Java
public class Test {
    int a;
    boolean b;
    double c;
    String d;

    void printValues() {
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
        System.out.println(d);
    }
}
ACompilation error due to uninitialized variables
BGarbage values printed
C0\ntrue\n0.0\n""
D0\nfalse\n0.0\nnull
Attempts:
2 left
💡 Hint
Instance variables have default values if not initialized.