Java Code Practice & Output Tracing
Predict outputs, spot compile errors, and trace constructors, dynamic dispatch, exceptions, and recursion step by step.
Pre/Post Increment & Operator Precedence
Trace the exact output printed by the program below without running it first.
| 1 | public class TraceOp { |
| 2 | public static void main(String[] args) { |
| 3 | int x = 2; |
| 4 | int res = x++ + x++ * --x / x++ - --x + 3 >> 1 | 2; |
| 5 | System.out.println("res = " + res); |
| 6 | System.out.println("Sum: " + 5 + 3 * 2); |
| 7 | } |
| 8 | } |
String Pool, Immutability & Enhanced For-Each
Determine the output of String comparisons and for-each mutation.
| 1 | public class StringForEachTrace { |
| 2 | public static void main(String[] args) { |
| 3 | String s1 = "KTU"; |
| 4 | String s2 = new String("KTU"); |
| 5 | s1.concat("2024"); |
| 6 | System.out.println((s1 == s2) + " " + s1.equals(s2) + " " + s1); |
| 7 | |
| 8 | int[] arr = {1, 2, 3}; |
| 9 | for (int val : arr) { |
| 10 | val = val + 10; |
| 11 | } |
| 12 | System.out.println(arr[0] + " " + arr[2]); |
| 13 | } |
| 14 | } |
Byte Promotion, Default Constructor & Varargs Order Errors
Identify all THREE compile-time errors in the following snippet.
| 1 | class Sample { |
| 2 | Sample(int x) { System.out.println(x); } |
| 3 | void log(int... nums, String label) { } // Error A |
| 4 | } |
| 5 | public class ErrorHunt1 { |
| 6 | public static void main(String[] args) { |
| 7 | byte a = 10, b = 20; |
| 8 | byte c = a + b; // Error B |
| 9 | Sample s = new Sample(); // Error C |
| 10 | } |
| 11 | } |
Unreachable Catch & Interface Visibility Error
Spot the two compile-time errors in this Module 3 code snippet.
| 1 | interface Task { |
| 2 | void execute(); |
| 3 | } |
| 4 | class Job implements Task { |
| 5 | void execute() { // Error 1 |
| 6 | try { |
| 7 | int x = 5 / 0; |
| 8 | } catch (Exception e) { |
| 9 | System.out.println("Caught"); |
| 10 | } catch (ArithmeticException ae) { // Error 2 |
| 11 | System.out.println("Math error"); |
| 12 | } |
| 13 | } |
| 14 | } |
javac rejects both Error 1 and Error 2.Multilevel Constructor Execution & `super()` Chaining
Trace the exact output order when creating new Child().
| 1 | class GrandParent { |
| 2 | GrandParent() { System.out.println("GrandParent()"); } |
| 3 | GrandParent(int x) { System.out.println("GrandParent(" + x + ")"); } |
| 4 | } |
| 5 | class Parent extends GrandParent { |
| 6 | Parent(int x) { |
| 7 | super(x); |
| 8 | System.out.println("Parent(" + x + ")"); |
| 9 | } |
| 10 | } |
| 11 | class Child extends Parent { |
| 12 | Child() { |
| 13 | super(50); |
| 14 | System.out.println("Child()"); |
| 15 | } |
| 16 | } |
| 17 | public class ConstructorOrderTrace { |
| 18 | public static void main(String[] args) { |
| 19 | new Child(); |
| 20 | } |
| 21 | } |
Combining `this(...)` and `super(...)` Across Inheritance
Trace the constructor calls carefully including this(...) chaining.
| 1 | class Base { |
| 2 | Base() { |
| 3 | System.out.print("B1 "); |
| 4 | } |
| 5 | Base(int a) { |
| 6 | this(); |
| 7 | System.out.print("B2 "); |
| 8 | } |
| 9 | } |
| 10 | class Derived extends Base { |
| 11 | Derived() { |
| 12 | super(10); |
| 13 | System.out.print("D1 "); |
| 14 | } |
| 15 | } |
| 16 | public class ThisSuperTrace { |
| 17 | public static void main(String[] args) { |
| 18 | new Derived(); |
| 19 | } |
| 20 | } |
Field Shadowing (`super.x`) vs Overridden Methods
Crucial distinction: fields are NOT polymorphic in Java, while overridden methods ARE!
| 1 | class Alpha { |
| 2 | int val = 10; |
| 3 | void display() { System.out.println("Alpha.display: " + val); } |
| 4 | } |
| 5 | class Beta extends Alpha { |
| 6 | int val = 20; |
| 7 | @Override |
| 8 | void display() { |
| 9 | System.out.println("Beta.display: this=" + val + ", super=" + super.val); |
| 10 | } |
| 11 | } |
| 12 | public class InheritanceFieldTrace { |
| 13 | public static void main(String[] args) { |
| 14 | Alpha ref = new Beta(); |
| 15 | System.out.println("ref.val = " + ref.val); |
| 16 | ref.display(); |
| 17 | } |
| 18 | } |
ref.val print vs ref.display()?Overload Resolution: Exact Match vs Widening vs Varargs
Trace which overloaded compute() version Java binds at compile time for each call.
| 1 | public class OverloadTrace { |
| 2 | static void compute(int a) { System.out.println("int: " + a); } |
| 3 | static void compute(double a) { System.out.println("double: " + a); } |
| 4 | static void compute(int... a) { System.out.println("varargs count: " + a.length); } |
| 5 | |
| 6 | public static void main(String[] args) { |
| 7 | byte b = 5; |
| 8 | compute(b); |
| 9 | compute(5.5f); |
| 10 | compute(1, 2); |
| 11 | } |
| 12 | } |
b, 5.5f, and (1, 2)?Overriding vs Static Method Hiding
Predict the output when calling an instance method vs a static method on a superclass reference.
| 1 | class Parent { |
| 2 | static void staticMsg() { System.out.println("Parent static"); } |
| 3 | void instanceMsg() { System.out.println("Parent instance"); } |
| 4 | } |
| 5 | class Child extends Parent { |
| 6 | static void staticMsg() { System.out.println("Child static"); } |
| 7 | @Override |
| 8 | void instanceMsg() { System.out.println("Child instance"); } |
| 9 | } |
| 10 | public class OverrideVsStaticHide { |
| 11 | public static void main(String[] args) { |
| 12 | Parent p = new Child(); |
| 13 | p.staticMsg(); |
| 14 | p.instanceMsg(); |
| 15 | } |
| 16 | } |
Polymorphic Array Dispatch Across Multiple Subclasses
Trace the output of iterating a superclass array containing mixed subclass objects.
| 1 | abstract class Shape { |
| 2 | abstract double perimeter(); |
| 3 | } |
| 4 | class Square extends Shape { |
| 5 | double side; |
| 6 | Square(double s) { side = s; } |
| 7 | @Override double perimeter() { return 4 * side; } |
| 8 | } |
| 9 | class Circle extends Shape { |
| 10 | double r; |
| 11 | Circle(double r) { this.r = r; } |
| 12 | @Override double perimeter() { return 2 * 3.0 * r; } // Using pi=3.0 for clean arithmetic |
| 13 | } |
| 14 | public class PolymorphicArrayTrace { |
| 15 | public static void main(String[] args) { |
| 16 | Shape[] shapes = { new Square(5), new Circle(4), new Square(2.5) }; |
| 17 | for (Shape s : shapes) { |
| 18 | System.out.println("Perimeter: " + s.perimeter()); |
| 19 | } |
| 20 | } |
| 21 | } |
shapes?Tracing `try-catch-finally` with Nested `throw`
Trace the exact output sequence through explicit throw, catch, and finally.
| 1 | public class ExceptionTraceDemo { |
| 2 | static int testFlow(boolean fail) { |
| 3 | try { |
| 4 | System.out.print("1 "); |
| 5 | if (fail) throw new IllegalStateException("Boom"); |
| 6 | System.out.print("2 "); |
| 7 | return 10; |
| 8 | } catch (IllegalStateException e) { |
| 9 | System.out.print("3 "); |
| 10 | return 20; |
| 11 | } finally { |
| 12 | System.out.println("4"); |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | public static void main(String[] args) { |
| 17 | System.out.println("Ret A = " + testFlow(false)); |
| 18 | System.out.println("Ret B = " + testFlow(true)); |
| 19 | } |
| 20 | } |
testFlow(false) and testFlow(true) print?Recursive Digit Sum & Stack Unwinding Trace
Trace the return value and printed unwinding sequence of mystery(3).
| 1 | public class RecursionPracticeTrace { |
| 2 | static int mystery(int n) { |
| 3 | if (n <= 0) return 0; |
| 4 | System.out.print(n + " "); |
| 5 | int res = n + mystery(n - 1); |
| 6 | System.out.print("(" + res + ") "); |
| 7 | return res; |
| 8 | } |
| 9 | |
| 10 | public static void main(String[] args) { |
| 11 | int ans = mystery(3); |
| 12 | System.out.println("-> Final: " + ans); |
| 13 | } |
| 14 | } |
Write a Custom Exception Class for Bank Withdrawal
Write a complete short Java program defining InsufficientFundsException and throwing it when withdraw() exceeds balance.
| 1 | class InsufficientFundsException extends Exception { |
| 2 | public InsufficientFundsException(String msg) { |
| 3 | super(msg); |
| 4 | } |
| 5 | } |
| 6 | |
| 7 | public class BankWithdrawProgram { |
| 8 | private double balance = 1000.0; |
| 9 | |
| 10 | public void withdraw(double amount) throws InsufficientFundsException { |
| 11 | if (amount > balance) { |
| 12 | throw new InsufficientFundsException("Requested " + amount + " exceeds balance " + balance); |
| 13 | } |
| 14 | balance -= amount; |
| 15 | System.out.println("Withdrawn " + amount + ". Remaining: " + balance); |
| 16 | } |
| 17 | |
| 18 | public static void main(String[] args) { |
| 19 | BankWithdrawProgram acct = new BankWithdrawProgram(); |
| 20 | try { |
| 21 | acct.withdraw(400); |
| 22 | acct.withdraw(800); |
| 23 | } catch (InsufficientFundsException e) { |
| 24 | System.out.println("Transaction failed: " + e.getMessage()); |
| 25 | } |
| 26 | } |
| 27 | } |
Short Program: Interface Reference Dispatch
Write a clean Java program using an interface Payable implemented by CardPay and UpiPay accessed via a Payable reference.
| 1 | interface Payable { |
| 2 | void pay(double amount); |
| 3 | } |
| 4 | |
| 5 | class CardPay implements Payable { |
| 6 | @Override |
| 7 | public void pay(double amount) { |
| 8 | System.out.println("Paid Rs." + amount + " via Card"); |
| 9 | } |
| 10 | } |
| 11 | |
| 12 | class UpiPay implements Payable { |
| 13 | @Override |
| 14 | public void pay(double amount) { |
| 15 | System.out.println("Paid Rs." + amount + " via UPI"); |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | public class PaymentInterfaceProgram { |
| 20 | public static void main(String[] args) { |
| 21 | Payable p = new CardPay(); |
| 22 | p.pay(500); |
| 23 | p = new UpiPay(); |
| 24 | p.pay(250); |
| 25 | } |
| 26 | } |