0% found this document useful (0 votes)
2 views24 pages

IndiaBix Java Study Guide

The document is a comprehensive study guide for Java exam preparation, covering key topics such as language fundamentals, declarations and access control, and operators and assignments. It includes detailed explanations of core concepts, question-by-question analyses, and quick-reference rules for various Java programming scenarios. The guide emphasizes important patterns and common pitfalls to help learners understand Java effectively.

Uploaded by

Aarya Gharmalkar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views24 pages

IndiaBix Java Study Guide

The document is a comprehensive study guide for Java exam preparation, covering key topics such as language fundamentals, declarations and access control, and operators and assignments. It includes detailed explanations of core concepts, question-by-question analyses, and quick-reference rules for various Java programming scenarios. The guide emphasizes important patterns and common pitfalls to help learners understand Java effectively.

Uploaded by

Aarya Gharmalkar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

IndiaBix Java – Complete Study Guide Page 1

IndiaBix Java

Complete Study Guide

Topic-wise Pattern Analysis for Exam Prep

Covers: Language Fundamentals · Declarations & Access Control · Operators &


Assignments

Flow Control · Exceptions · Objects & Collections · Inner Classes · Threads

Legend
OUTPUT Outputs a value to console COMPILE ERROR Code doesn't compile

RUNTIME
Compiles but crashes at runtime NO OUTPUT Runs silently with no output
EXCEPTION

IndiaBix Java | For Exam Prep


IndiaBix Java – Complete Study Guide Page 2

TOPIC 1

Language Fundamentals
Keywords, Data Types, Default Values, Arrays, main() method

Core Concepts You Must Know

Default Values for Array / Instance Variables


• int, long, short, byte → 0
• float → 0.0f | double → 0.0
• char → '\u0000' (NOT a space!)
• boolean → false (NOT true!)
• String / any Object → null (NOT the string "null")
• Local variables have NO default – using them without initialising = compile error

Valid vs Invalid Java Keywords (frequently tested)


• ■ VALID: interface, instanceof, native, strictfp, transient, volatile, assert, goto (reserved but unused), finally, throws
• ■ NOT JAVA (C/C++): signed, unsigned, include, virtual, constant, friend
• ■■ Case traps: 'String' is a class, NOT a keyword. 'Float' is a class, 'float' is the keyword.
• ■■ 'goto' is a reserved word in Java but has no function – still counts as keyword in MCQs

Question-by-Question Analysis

Q1. What are the correct default values for array elements?

OUTPUT Answer: int→0, Dog→null, char→'\u0000', float→0.0f

String default is null (no quotes). boolean default is false, NOT true. char default is the Unicode null character \u0000, NOT a
space character.

■ Pattern: Memorise defaults: 0 for numbers, false for boolean, null for objects, \u0000 for char.

Q2. Which list contains only valid Java keywords? (goto, instanceof, native, finally, default, throws)

OUTPUT Answer: All words in that list are valid Java keywords

'goto' is reserved in Java even though it has no function. 'virtual' is C++ only. 'constant' is not a keyword (use static final).
'include' is C only. 'Int' (capital I) is not a keyword – it must be lowercase 'int'.

■ Pattern: If it ends in a capital or is a C/C++ exclusive, it is NOT a Java keyword.

Q3. Which will legally declare, construct, and initialize an array?


int[] myList = {"1","2","3"}; // option A

int[] myList = (5, 8, 2); // option B

int myList[][] = {4,9,7,0}; // option C

int myList[] = {4, 3, 7}; // option D ← CORRECT

COMPILE ERROR Answer: Only option D is legal


A: initialises int array with String literals – type mismatch. B: uses parentheses instead of curly braces. C: declares 2D array
but provides values for only one dimension.

■ Pattern: Array literal initialiser must use curly braces {}. Element types must match declared type.

IndiaBix Java | For Exam Prep


IndiaBix Java – Complete Study Guide Page 3

Q4. What is the output? (main() declared without static keyword)


public class F0091 {

public void main(String[] args) { // missing static!

[Link]("Hello" + args[0]);

// Run: java F0091 world

RUNTIME
Answer: Exception in thread "main" [Link]: main
EXCEPTION

The JVM looks specifically for 'public static void main(String[])'. Without 'static', the method signature doesn't match – NOT a
compile error, but fails at runtime.

■ Pattern: Missing 'static' on main() → NoSuchMethodError at RUNTIME (not compile time!).

Q5. What is the output? (2D array with uninitialised inner dimension)
Dog[][] theDogs = new Dog[3][];

[Link](theDogs[2][0].toString());

RUNTIME
Answer: NullPointerException at runtime
EXCEPTION

new Dog[3][] only allocates the outer array (3 slots, each null). The inner arrays are never created. Accessing theDogs[2][0]
dereferences null → NPE.

■ Pattern: new T[n][] allocates ONLY the outer dimension. Inner arrays are null until explicitly created.

Q6. What is the output? (signed int keyword)


public static void main(String[] args) {

signed int x = 10; // ← PROBLEM

for (int y=0; y<5; y++, x--)

[Link](x + ", ");

COMPILE ERROR Answer: Compilation fails – 'signed' is not a Java keyword

Java has no 'signed'/'unsigned' modifiers. All numeric primitives in Java are signed. This is a C/C++ concept. The code won't
even reach the loop.

■ Pattern: Whenever you see 'signed' or 'unsigned' in Java code → ALWAYS compile error.

Quick-Reference Rules Table


Code / Situation What Happens & Why

int[] a = {1,2,3}; ■ Valid short-hand initialisation

int a[] = {1,2,3}; ■ Valid ([] after name is also OK)

int[] a = new int[]{1,2,3}; ■ Valid anonymous array

int[] a = (1,2,3); ■ Compile error – use {} not ()

int[] a = {"1","2"}; ■ Type mismatch – String in int array

boolean b; if(b){...} ■ Local var uninitialized – compile error

static boolean b; if(b){...} ■ Instance/static default = false

IndiaBix Java | For Exam Prep


IndiaBix Java – Complete Study Guide Page 4

signed int x = 5; ■ 'signed' not a Java keyword

String s; → default? null (instance var), error (local var)

IndiaBix Java | For Exam Prep


IndiaBix Java – Complete Study Guide Page 5

TOPIC 2

Declarations and Access Control


Modifiers, Inheritance, Constructors, Interface rules

Access Modifier Hierarchy

Access Levels (most restrictive → least restrictive)


• private → accessible ONLY within the same class
• default → accessible within the same package only
• protected → same package + subclasses in ANY package
• public → accessible everywhere
• For subclasses in ANY package: use protected (not default, not private)
• Interface methods are implicitly public – overriding method MUST be public

final, abstract, static – Key Rules


• final method → cannot be overridden in subclass (trying to → compile error)
• final class → cannot be extended
• final variable → can only be assigned once
• abstract method → no body; must be overridden in concrete subclass
• abstract class → can implement some or none of an interface's methods
• static variable inside a method → ILLEGAL (local vars have no modifiers)
• Inner class members can't be static unless the class itself is static nested

Question-by-Question Analysis

Q7. What is the output? (overriding a final method)


class A {

final public int GetResult(int a, int b) { return 0; }

class B extends A {

public int GetResult(int a, int b) { return 1; } // tries to override

COMPILE ERROR Answer: Compilation fails – cannot override a final method

A method marked 'final' cannot be overridden by any subclass. The compiler detects this immediately and refuses to compile.

■ Pattern: final method = locked. Any attempt to override in subclass → ALWAYS compile error.

Q8. What is the output? (void method with same name as class)
public class A {

void A() { // This is a METHOD, not a constructor!

[Link]("Class A");

public static void main(String[] args) {

new A(); // calls DEFAULT constructor (no-arg)

IndiaBix Java | For Exam Prep


IndiaBix Java – Complete Study Guide Page 6

NO OUTPUT Answer: No output – the method A() is never called

A constructor has NO return type. 'void A()' is a regular method named A, not a constructor. new A() calls the
compiler-generated default no-arg constructor. The method void A() is never invoked, so nothing prints.

■ Pattern: Constructor = class name + NO return type. void ClassName() is just a method, never auto-called.

Q9. What is the output? (super class has only parameterised constructor)
class Super {

public Super(String text) { i = 1; } // only constructor

class Sub extends Super {

public Sub(String text) { // missing super(text) call!

i = 2;

COMPILE ERROR Answer: Compilation fails


When a superclass defines ONLY a parameterised constructor, Java does NOT create a default no-arg constructor. The
subclass constructor must explicitly call super(text) as its FIRST statement. Without it the compiler tries to call super() (no-arg)
which doesn't exist.

■ Pattern: If superclass has NO default constructor, subclass MUST explicitly call super(...) first.

Q10. What is the output? (static variable inside a method)


public int aMethod() {

static int i = 0; // ← ILLEGAL

i++;

return i;

COMPILE ERROR Answer: Compilation fails – 'static' is not allowed for local variables

Local variables (inside methods) cannot have access or non-access modifiers. You cannot use static, public, private, or
protected on a local variable.

■ Pattern: Rule: Local variables NEVER have modifiers. static/public/private on a local var = compile error.

Q11. Which access modifier is most restrictive for subclass access from any package?

OUTPUT Answer: protected

private blocks all outside access. default allows same-package only (misses 'any package'). protected = same package +
subclasses from any package. public is less restrictive than protected.

■ Pattern: Subclass access from ANY package = protected. Same package only = default.

Interface Rules – Must Know


Code / Situation What Happens & Why

interface X implements Y ■ Interfaces EXTEND other interfaces, not implement

abstract class X extends Interface ■ Classes IMPLEMENT interfaces, don't extend them

IndiaBix Java | For Exam Prep


IndiaBix Java – Complete Study Guide Page 7

abstract class X implements Y {} ■ Abstract class can implement 0 methods of interface

Interface method visibility Implicitly public – override MUST be public

Interface variables Implicitly public static final

class declared private ■ Top-level class can't be private

IndiaBix Java | For Exam Prep


IndiaBix Java – Complete Study Guide Page 8

TOPIC 3

Operators and Assignments


Pass by value/reference, Bit shifts, Type casting, Operators

The Most Important Concept: Pass By Value vs Reference

How Arguments Work in Java


• PRIMITIVES (int, boolean, char, double…) → passed by VALUE. Method gets a COPY. Changing the copy has NO effect
on the original.
• OBJECTS & ARRAYS → the REFERENCE is passed by value. Method gets a copy of the reference. Both caller and
method point to the SAME object → modifying object state AFFECTS the original.
• STRING SPECIAL CASE: Strings are immutable. s = s + 'x' inside method creates a NEW String object. The caller's
reference still points to the OLD value.
• ARRAY ELEMENTS: modifying a[i] = x inside method DOES change the original array.

Question-by-Question Analysis

Q12. What is the output? (array passed to method, element modified)


long[] a1 = {3, 4, 5};

long[] a2 = fix(a1); // a2 and a1 point to SAME array

long[] fix(long[] a3) {

a3[1] = 7; // modifies shared array

return a3; // returns same reference

// a1 = {3,7,5} a2 = {3,7,5} (same object!)

print(a1[0]+a1[1]+a1[2]); // 3+7+5 = 15

print(a2[0]+a2[1]+a2[2]); // 3+7+5 = 15

OUTPUT Answer: 15 15

a1, a2, and a3 all reference the SAME long array object. When fix() sets a3[1]=7, it modifies the shared object. Both a1 and a2
see the change. Numeric addition: 3+7+5 = 15.

■ Pattern: Array passed to method → caller's array IS modified. Numeric args add; watch for + on numbers.

Q13. What is the output? (boolean primitive passed to method)


boolean b1 = false;

boolean b2 = fix(b1);

boolean fix(boolean b1) {

b1 = true; // only the LOCAL copy changes

return b1;

print(b1 + " " + b2);

OUTPUT Answer: false true

The boolean b1 in fix() is a completely separate variable (copy of the value). Setting it to true does NOT affect the b1 in start().
b2 gets the returned value true.

IndiaBix Java | For Exam Prep


IndiaBix Java – Complete Study Guide Page 9

■ Pattern: Primitives are ALWAYS copied. Modifying inside method NEVER affects the caller's variable.

Q14. What is the output? (String passed to method, concatenation performed)


String s1 = "slip";

String s2 = fix(s1);

String fix(String s1) {

s1 = s1 + "stream"; // NEW String "slipstream" – caller unaffected

print(s1 + " "); // prints: slipstream

return "stream";

print(s1 + " " + s2); // prints: slip stream

OUTPUT Answer: slipstream slip stream

Strings are immutable. Inside fix(), s1 = s1+"stream" creates a brand new String object and points fix()'s local s1 to it. The
caller's s1 still refers to "slip". Full output: first the print inside fix() outputs 'slipstream ', then 'slip stream'.

■ Pattern: String concatenation inside method = NEW object. Caller's String NEVER changes.

Q15. What is the output? (unsigned right shift on negative number)


int x = 0x80000000; // = -2147483648

[Link](x + " and ");

x = x >>> 31;

[Link](x);

OUTPUT Answer: -2147483648 and 1

0x80000000 has the MSB set → represents -2147483648 in two's complement. >>> is the UNSIGNED right shift – it always
fills with 0 from the left. Shifting 31 places: the MSB (1) moves to position 0, all other bits become 0 → result = 1. print() always
shows integers in base 10, never hex.

■ Pattern: >>> (unsigned shift): fills with 0 regardless of sign. Can change negative to positive.

Q16. What is the output? (assignment operator used instead of ==)


int x = 100;

double y = 100.1;

boolean b = (x = y); // ← uses = not ==

COMPILE ERROR Answer: Compilation fails

The expression (x = y) tries to assign a double to an int (x), which is a lossy conversion requiring explicit cast. Even if fixed,
assigning to int returns an int, not a boolean. The correct form would be (x == y) which is a boolean comparison.

■ Pattern: = assigns (returns the value), == compares (returns boolean). In boolean context, use == not =.

Shift Operators Quick Reference


Code / Situation What Happens & Why

x >> n Signed right shift: fills left with sign bit. Negative stays negative

x >>> n Unsigned right shift: fills left with 0. Can flip sign (neg→pos)

x << n Left shift: fills right with 0. Equivalent to x * 2^n

print(0x80000000) Always prints in base-10: -2147483648 (not hex)

IndiaBix Java | For Exam Prep


IndiaBix Java – Complete Study Guide Page 10

IndiaBix Java | For Exam Prep


IndiaBix Java – Complete Study Guide Page 11

TOPIC 4

Flow Control
if-else, switch/fall-through, loops, break/continue, boolean rules

The Biggest Trap: Switch Fall-Through

Switch Statement – Critical Rules


• Once a case MATCHES, ALL subsequent cases execute until a break is encountered.
• No break = fall-through: case 3 matches → cases 3, 4, 5, default all execute.
• default can appear ANYWHERE but executes if no case matches (or when falling through).
• Valid switch types: byte, short, char, int, String (Java 7+), enum.
• INVALID for switch: long, float, double, Boolean (wrapper Long, Short also invalid).
• Case labels must be COMPILE-TIME CONSTANTS. final static values are OK.

Question-by-Question Analysis

Q17. What is the output? (switch with no break statements, final static variable in case)
final static short x = 2;

for (int z=0; z < 3; z++) {

switch (z) {

case x: print("0 "); // case 2

case x-1: print("1 "); // case 1

case x-2: print("2 "); // case 0

OUTPUT Answer: 2 1 2 0 1 2

z=0: matches case x-2 (=0) → prints '2' (no more cases below, exits). z=1: matches case x-1 (=1) → prints '1 ', falls through to
print '2 '. z=2: matches case x (=2) → prints '0 ', falls through '1 ', falls through '2 '. Result: 2 [space] 1 2 [space] 0 1 2

■ Pattern: NO BREAK = fall-through. Trace from matched case downward. final values OK in case labels.

Q18. What is the output? (switch with sequential cases, no break, switchIt(4) called)
int switchIt(int x) {

int j = 1;

switch (x) {

case 1: j++;

case 2: j++;

case 3: j++;

case 4: j++; // matches here for x=4

case 5: j++; // falls through

default: j++; // falls through

return j + x; // j + 4

IndiaBix Java | For Exam Prep


IndiaBix Java – Complete Study Guide Page 12

OUTPUT Answer: value = 8

x=4: matches case 4. Then falls through to case 5 (j++), then default (j++). j starts at 1, gets incremented 3 times → j=4. return
j+x = 4+4 = 8.

■ Pattern: Count fall-throughs carefully. From matched case to end of switch, count each j++.

Q19. What is the output? (if/else with impossible branch)


public void foo(boolean a, boolean b) {

if (a) { print("A"); }

else if (a && b) { print("A && B"); } // UNREACHABLE when a=true

else {

if (!b) print("notB");

else print("ELSE");

// Called with a=true, b=true

OUTPUT Answer: A
When a=true, the first if(a) is true → prints 'A' and SKIPS all else branches. The 'else if (a && b)' can NEVER execute when
a=true because it's only reached when a=false. Called with a=false, b=true: goes to else → b is true, not !b → prints 'ELSE'.

■ Pattern: Once any if/else-if matches, ALL remaining branches are SKIPPED. Dead code trap.

Q20. What is the output? (do-while with break and pre-increment in condition)
int i=1, j=10;

do {

if (i > j) break;

j--;

} while (++i < 5);

print("i=" + i + " j=" + j);

OUTPUT Answer: i = 5 and j = 6

Trace: (i=1,j=10)→ j-- →(1,9); check ++i<5 → i=2, 2<5 true. (2,9)→j-- →(2,8); ++i=3<5 true. (3,8)→j-- →(3,7); ++i=4<5 true.
(4,7)→j-- →(4,6); ++i=5<5 false → loop exits. i=5, j=6.

■ Pattern: do-while: body runs FIRST, condition checked AFTER. ++i increments BEFORE comparison.

Q21. Why does 'if(odd)' or 'while(1)' fail to compile in Java?


int odd = 1;

if (odd) { ... } // ← COMPILE ERROR

while (1) { ... } // ← COMPILE ERROR

COMPILE ERROR Answer: Compilation fails – condition must be boolean type

Unlike C/C++, Java requires EXACTLY a boolean expression in if/while/for conditions. You cannot use an integer as a
boolean. This is C syntax, not valid Java.

■ Pattern: Java if/while/for conditions MUST be boolean. if(1) or while(1) → always compile error.

Q22. What is the output? (assignment in if condition: b2 = true)


static boolean b1, b2; // defaults: false, false

// ...

IndiaBix Java | For Exam Prep


IndiaBix Java – Complete Study Guide Page 13

b1 = true; x++;

else if (b2 = true) // ASSIGNMENT, not comparison!

x = x + 100;

else if (b1 | b2)

x = x + 1000;

OUTPUT Answer: 101

(b2 = true) assigns true to b2 AND evaluates to true – this is VALID Java! It's not == but = which is a legal boolean expression
here. So the else-if succeeds: x (=1) + 100 = 101. The last else-if is skipped.

■ Pattern: b2 = true in an if condition ASSIGNS and evaluates to true. Common exam trick!

Flow Control Quick-Reference Rules


Code / Situation What Happens & Why

switch(long x) or switch(float) ■ long/float/double not valid switch types

switch(byte/short/char/int) ■ Valid switch types

case with non-final variable ■ Case labels must be compile-time constants

case with final static var ■ Allowed – evaluated at compile time

if(integer_value) ■ Java needs boolean, not int

while(true) ■ Infinite loop – correct Java

(b = true) in if condition ■■ Valid assignment AND evaluates to true

IndiaBix Java | For Exam Prep


IndiaBix Java – Complete Study Guide Page 14

TOPIC 5

Exceptions
try-catch-finally, Exception hierarchy, Error vs Exception, catch order

Exception Hierarchy – Most Critical for Exams

Throwable Hierarchy (memorise this!)


• Throwable
• ■■■ Exception ← catch(Exception e) catches this and all subclasses
• ■ ■■■ IOException (checked)
• ■ ■■■ RuntimeException (unchecked)
• ■ ■■■ ArithmeticException (e.g. divide by 0)
• ■ ■■■ NullPointerException
• ■ ■■■ ArrayIndexOutOfBoundsException
• ■ ■■■ ClassCastException
• ■■■ Error ← NOT caught by catch(Exception e)!
• ■■■ StackOverflowError
• ■■■ OutOfMemoryError
• KEY: Error is NOT a subclass of Exception. catch(Exception) won't catch an Error!

The finally Block – Rules


• finally ALWAYS executes, even if return is inside try.
• finally runs after a caught exception before continuing.
• finally runs even when an exception is NOT caught (before propagating up).
• finally does NOT run only in 3 cases: [Link](), JVM crash, thread death.
• Order: try → (exception thrown?) → matching catch → finally → code after try-catch.

Question-by-Question Analysis

Q23. What is the output? (return inside try with finally block)
try {

return;

} finally {

[Link]("Finally");

OUTPUT Answer: Finally

Even when return is executed inside the try block, the finally block runs BEFORE the method actually returns. This is one of
Java's absolute guarantees.

■ Pattern: finally ALWAYS runs – even before a return statement completes. No exceptions (almost).

Q24. What is the output? (catch(Exception) placed before catch(ArithmeticException))


try {

int x = 0;

int y = 5 / x; // ArithmeticException

IndiaBix Java | For Exam Prep


IndiaBix Java – Complete Study Guide Page 15

catch (Exception e) { // broader catch FIRST

print("Exception");

catch (ArithmeticException ae) { // ← already caught above

print("Arithmetic");

COMPILE ERROR Answer: Compilation fails

ArithmeticException IS-A Exception (subclass). When Exception is caught first, the ArithmeticException catch block can
NEVER be reached. Java compiler detects unreachable catch blocks and refuses to compile. RULE: Catch MORE specific
exceptions BEFORE less specific ones.

■ Pattern: Catch order: subclass BEFORE superclass. Exception before RuntimeException → compile error.

Q25. What is the output? (Error thrown, only catch(Exception) present)


try {

badMethod(); // throws new Error()

print("A");

catch (Exception ex) { // Error is NOT a subclass of Exception!

print("B");

finally {

print("C");

print("D");

OUTPUT Answer: C is printed, then exits with error message

Error is NOT caught by catch(Exception) because Error extends Throwable directly, not Exception. The catch block is skipped.
finally runs (prints C). Then the Error propagates up and crashes the program. D never executes.

■ Pattern: Error ≠ Exception. catch(Exception) CANNOT catch an Error. Only finally runs before crash.

Q26. What is the output? (RuntimeException caught, code after try-catch continues)
try {

print("hello "); throwit();

catch (Exception re) { print("caught "); }

finally { print("finally "); }

print("after ");

OUTPUT Answer: hello throwit caught finally after

throwit() prints 'throwit ' then throws RuntimeException. The catch(Exception re) catches it (RuntimeException IS-A Exception)
→ prints 'caught '. finally runs → prints 'finally '. Since exception was caught, execution continues → 'after '.

■ Pattern: Exception CAUGHT → execution continues normally after try-catch block. Code after runs.

Q27. What is the output? (RuntimeException caught in first of two catch blocks)
try { badMethod(); print("A"); }

catch (RuntimeException ex) { print("B"); } // matches!

IndiaBix Java | For Exam Prep


IndiaBix Java – Complete Study Guide Page 16

catch (Exception ex1) { print("C"); } // skipped

finally { print("D"); }

print("E");

OUTPUT Answer: BDE

badMethod() throws RuntimeException. First catch matches → prints B. Second catch is skipped (exception already handled).
finally runs → prints D. Code after → prints E.

■ Pattern: Only ONE catch block executes per exception. After matching catch, rest are skipped.

try-catch-finally Output Pattern Summary


Code / Situation What Happens & Why

try{...} catch{B} finally{D} + E after Exception caught → B, then D, then E

try{return} finally{D} D prints, then method returns

throw new Error(), catch(Exception) Error NOT caught, finally runs, then crash

Specific before General catch order ■ Correct – subclass first

General before Specific catch order ■ Compile error – unreachable catch

[Link](0) inside try finally does NOT run

IndiaBix Java | For Exam Prep


IndiaBix Java – Complete Study Guide Page 17

TOPIC 6

Objects and Collections


String pool, equals vs ==, Collections API, instanceof, NullPointer

String Behaviour – Tricky in Every Exam

String Pool and Immutability


• Strings created with literals ("hello") go into the String Pool – shared.
• Strings created with new String("hello") are on the heap – NOT in the pool.
• s1 == s2 compares REFERENCES (memory address), NOT content.
• [Link](s2) compares CONTENT – what you almost always want.
• Strings are IMMUTABLE: s = s + "x" creates a BRAND NEW String object.
• NULL keyword is lowercase: null (not NULL). NULL is undefined → compile error.
• StringBuffer does NOT override equals() or hashCode() – uses Object's default.

Collections – Key Facts

Collection Interface Summary


• ArrayList: indexed, ordered, NOT synchronized, allows duplicates
• LinkedHashMap: iteration order = insertion order
• TreeMap: sorted by natural key order (ascending)
• HashMap: no guaranteed order
• Set: no duplicates, use TreeSet for natural order
• Hashtable: implements Map (not Collection)
• iterator() on ArrayList returns Iterator (not ListIterator or List)
• listIterator() returns a ListIterator (bidirectional)

Question-by-Question Analysis

Q28. What is the output? (java Test red green blue → accessing args[3])
// Run: java Test red green blue

String foo = args[1]; // "green"

String bar = args[2]; // "blue"

String baz = args[3]; // ← DOES NOT EXIST! (only 0,1,2)

print("baz = " + baz);

RUNTIME
Answer: ArrayIndexOutOfBoundsException
EXCEPTION

args[0]='red', args[1]='green', args[2]='blue'. There is no args[3]. Arrays are ZERO-BASED. Accessing args[3] with only 3
elements → ArrayIndexOutOfBoundsException.

■ Pattern: args[] is zero-based. 'java Class a b c' → args[0]='a', args[1]='b', args[2]='c'.

Q29. What is the output? (String str = NULL;)


String str = NULL;

print(str);

COMPILE ERROR Answer: Compilation fails

IndiaBix Java | For Exam Prep


IndiaBix Java – Complete Study Guide Page 18

The null literal in Java is lowercase 'null'. 'NULL' is not defined anywhere, so the compiler treats it as an identifier and fails
because NULL is not declared.

■ Pattern: null is always lowercase in Java. NULL → compile error (undefined identifier).

Q30. What is the output? (array declared but NOT initialised with new)
private static int[] x; // declared, NOT initialised

print(x[0]); // accessing element of null array

RUNTIME
Answer: NullPointerException at runtime
EXCEPTION

Declaration 'int[] x' only creates a reference variable, initialised to null (static). 'new int[5]' is what actually creates the array in
memory. Accessing x[0] on a null reference → NullPointerException.

■ Pattern: Declaring int[] x only creates null reference. You MUST do x = new int[n] before using it.

Q31. instanceof test: [Link]() – is it List? Iterator? ListIterator?


Object i = new ArrayList().iterator();

print(i instanceof List); // ?

print(i instanceof Iterator); // ?

print(i instanceof ListIterator); // ?

OUTPUT Answer: false, true, false

iterator() returns an object that implements Iterator (forward-only). It does NOT implement List or ListIterator. listIterator() is the
method that returns a ListIterator (bidirectional).

■ Pattern: iterator() → Iterator only. listIterator() → ListIterator. Know the difference!

Collections Comparison Table


Code / Situation What Happens & Why

ArrayList vs Vector ArrayList: not synchronized (faster). Vector: synchronized (legacy)

HashMap vs LinkedHashMap HashMap: no order. LinkedHashMap: insertion order

HashMap vs TreeMap TreeMap: sorted ascending by key

Set: no duplicates TreeSet: sorted. HashSet: no order. LinkedHashSet: insertion order

Hashtable implements Map (NOT Collection directly)

[Link]() Uses [Link]() – compares references, NOT content

IndiaBix Java | For Exam Prep


IndiaBix Java – Complete Study Guide Page 19

TOPIC 7

Inner Classes
Member inner class, static nested, local inner, anonymous inner class

Types of Inner Classes

Four Types of Inner Classes – Quick Summary


• 1. MEMBER INNER CLASS: defined inside class body (not in method). Has access to all outer class members including
private.
• 2. STATIC NESTED CLASS: declared with 'static'. Does NOT need outer instance. Cannot access non-static members of
outer class (like a static method).
• 3. METHOD-LOCAL INNER CLASS: defined inside a method. Can be abstract. Cannot be public, private, protected, or
static (like local variables).
• 4. ANONYMOUS INNER CLASS: no name, created with 'new' inline. Can extend ONE class OR implement ONE
interface (never both, never multiple).

Anonymous Inner Class Syntax Rules


• Runnable r = new Runnable() { public void run() { } }; ← CORRECT
• Must override all abstract/interface methods if interface is used.
• Cannot have explicit constructor (anonymous class has no name).
• new Runnable() { } ← missing run() implementation → compile error
• For polymorphism: Boo f = new Bar() { }; is valid (Bar extends Boo)

Question-by-Question Analysis

Q32. Which is true about an anonymous inner class?

OUTPUT Answer: It can extend exactly one class OR implement exactly one interface

Anonymous inner class syntax only allows ONE type name after 'new'. That type is either a class (then the anon class extends
it) OR an interface (then the anon class implements it). Never both. Never multiple interfaces.

■ Pattern: Anonymous class: extend ONE class OR implement ONE interface. Never both, never multiple.

Q33. Which creates an anonymous inner class from within class Bar (extends Boo)?
Boo f = new Boo(24) { }; // A – int 24, no matching Boo constructor

Boo f = new Bar() { }; // B ← CORRECT

Bar f = new Boo(String s) { }; // C – wrong polymorphism direction

Boo f = new [Link](String s){ }; // D – invalid syntax

OUTPUT Answer: B: Boo f = new Bar() { };

B is correct: Bar extends Boo, so polymorphism allows Boo reference to point to Bar instance. A fails: Boo has no int
constructor. C fails: cannot assign superclass to subclass reference. D is invalid syntax.

■ Pattern: Anonymous class follows normal polymorphism: superclass reference = subclass anonymous instance.

Q34. Which is true about a method-local inner class?

OUTPUT Answer: It can be marked abstract

IndiaBix Java | For Exam Prep


IndiaBix Java – Complete Study Guide Page 20

Method-local inner classes CAN be abstract (meaning a subclass must be created to use them). They CANNOT be marked
public, private, protected, or static – just like local variables. They don't HAVE to be final (though it's allowed).

■ Pattern: Method-local inner class modifiers: only abstract or final allowed. NO access modifiers.

Q35. Which is true about a static nested class?

OUTPUT Answer: It does not have access to non-static members of the enclosing class

A static nested class has no connection to any instance of the enclosing class. Like a static method, it can only access static
members of the outer class. You can create a static nested class WITHOUT an instance of the outer class.

■ Pattern: Static nested class = like a static method. No outer instance needed. No non-static access.

Q36. Instantiating an inner class from a static method – what works?


class Outer {

public void someOuterMethod() { new Inner(); } // Line 5 – instance context

public class Inner { }

public static void main(String[] argv) {

Outer ot = new Outer();

// new Inner(); // ← FAILS: non-static context needed

// new [Link](); // ← FAILS: not valid syntax

// new [Link](); // ← FAILS: non-static context

OUTPUT Answer: Only 'new Inner()' at line 5 (inside instance method) compiles

Inside an instance method, 'new Inner()' works because there's an implicit 'this' reference. In a static context (main), you need
an outer instance: [Link] Inner(). new [Link]() is not valid syntax. new [Link]() fails – still needs outer instance.

■ Pattern: Member inner class from static context: [Link] Inner(). Not [Link]().

Inner Class Rules Summary


Code / Situation What Happens & Why

new Inner() from instance method ■ Implicit outer 'this' available

new Inner() from static method ■ No outer instance – compile error

[Link] Inner() ■ Correct way to create inner class from static

static nested class accessing field ■ Cannot access non-static outer members

Anonymous class: 2 interfaces ■ Can only implement ONE interface

Method-local: public modifier ■ Local classes can't have access modifiers

Method-local: abstract modifier ■ Allowed

IndiaBix Java | For Exam Prep


IndiaBix Java – Complete Study Guide Page 21

TOPIC 8

Threads
Thread lifecycle, Runnable vs Thread, synchronized, wait/notify

Thread Fundamentals

Two Ways to Create a Thread


• WAY 1: Extend Thread class → override run() method → call start()
• WAY 2: Implement Runnable interface → override run() → pass to new Thread(runnable) → call start()
• IMPORTANT: Calling start() launches a new thread and internally calls run().
• Calling run() directly does NOT start a new thread – it just calls the method normally!
• start() can only be called once per Thread object. Calling twice → IllegalThreadStateException

Thread Methods – Object class vs Thread class


• Object class methods (require monitor lock): wait(), notify(), notifyAll()
• Thread class instance methods: start(), run(), interrupt(), isInterrupted(), join()
• Thread class static methods: sleep(), yield(), currentThread()
• synchronized is a KEYWORD, not a method – synchronized() is NOT a method call
• Valid Thread constructors: Thread(), Thread(Runnable r), Thread(Runnable r, String name)
• INVALID: Thread(int priority), Thread(Runnable r, int priority), Thread(Runnable r, ThreadGroup g) – wrong arg order

Thread Lifecycle States

Thread States & Transitions


• NEW → created with new Thread() but not yet started
• RUNNABLE → after start() called, waiting for CPU or executing
• BLOCKED → waiting to acquire a synchronized lock
• WAITING → after wait() or join() with no timeout – indefinite
• TIMED_WAITING → after sleep(n), wait(n), or join(n) – with timeout
• TERMINATED → run() method has finished
• notify() wakes ONE waiting thread. notifyAll() wakes ALL waiting threads.
• setPriority() does NOT cause thread to stop – it's just a hint to the scheduler

Question-by-Question Analysis

Q37. What method starts a thread? init()? start()? run()? resume()?

OUTPUT Answer: start()

start() causes the JVM to call run() in a new thread. run() alone does NOT start a new thread – it's just a method call. init()
doesn't exist in Thread. resume() is deprecated and resumes a suspended thread.

■ Pattern: ALWAYS call start() to begin thread execution. run() alone = regular method call, no new thread.

Q38. Which two are valid Thread constructors?


1. Thread(Runnable r, String name)

2. Thread()

3. Thread(int priority)

4. Thread(Runnable r, ThreadGroup g) // reversed order of 4 actual

IndiaBix Java | For Exam Prep


IndiaBix Java – Complete Study Guide Page 22

5. Thread(Runnable r, int priority)

OUTPUT Answer: 1 and 2

Thread() with no args is valid. Thread(Runnable r, String name) is valid. Thread doesn't accept int priority in constructor (you
use setPriority() method). The actual constructor is Thread(ThreadGroup g, Runnable r) – reversed args from option 4.
Thread(Runnable, int) doesn't exist.

■ Pattern: Valid Thread constructors: Thread(), Thread(Runnable), Thread(Runnable, String). No int/priority.

Q39. Which three are methods of the Object class (not Thread)?
1. notify() 2. notifyAll() 3. isInterrupted()

4. synchronized() 5. interrupt()

6. wait(long msecs) 7. sleep(long msecs) 8. yield()

OUTPUT Answer: 1, 2, 6 (notify, notifyAll, wait)

notify(), notifyAll(), wait() are Object class methods – they deal with the monitor lock. isInterrupted() and interrupt() are Thread
instance methods. sleep() and yield() are Thread STATIC methods. synchronized is a KEYWORD (not a method at all).

■ Pattern: Object: wait/notify/notifyAll. Thread static: sleep/yield. Thread instance: interrupt/isInterrupted.

Q40. Which code correctly starts a thread using the Runnable interface?
class X implements Runnable {

public void run() {}

// Option A: Thread t = new Thread(X); // class not instance

// Option B: Thread t = new Thread(X); [Link](); // class not instance

// Option C: X run = new X(); Thread t = new Thread(run); [Link](); // CORRECT

// Option D: Thread t = new Thread(); [Link](); // just calls method

OUTPUT Answer: Option C

C is correct: create an instance of the Runnable (X run = new X()), pass it to Thread constructor, then call start(). A and B:
Thread constructor needs an instance, not a class name. D: calling run() directly doesn't start a new thread.

■ Pattern: Runnable pattern: new Thread(runnableInstance).start(). Class name ≠ instance.

Q41. Which method CANNOT directly cause a thread to stop executing?


A. Calling setPriority() on a Thread

B. Calling wait() on an object

C. Calling notify() on an object

D. Calling read() on an InputStream

OUTPUT Answer: C: notify()

notify() WAKES UP a waiting thread – it doesn't stop one. setPriority() just hints to scheduler. wait() pauses the calling thread.
read() on InputStream is a blocking call that can pause the thread if no data is ready.

■ Pattern: notify() = wake up a sleeping thread. It CANNOT stop/pause a running thread.

Thread Method Quick Reference


Code / Situation What Happens & Why

[Link]() Starts new thread, JVM calls run() in new thread

IndiaBix Java | For Exam Prep


IndiaBix Java – Complete Study Guide Page 23

[Link]() Just calls run() as normal method – NO new thread

[Link](n) Static. Current thread sleeps n milliseconds

[Link]() Static. Hints scheduler to let other threads run

[Link]() Object method. Releases lock and waits for notify

[Link]() Object method. Wakes ONE waiting thread

[Link]() Object method. Wakes ALL waiting threads

[Link]() Thread instance method. Interrupts a waiting thread

[Link]() Thread instance method. Checks interrupt status

[Link](n) Sets priority (1-10). Does NOT stop thread

synchronized keyword NOT a method – it's a Java keyword

IndiaBix Java | For Exam Prep


IndiaBix Java – Complete Study Guide Page 24

MASTER QUICK-REFERENCE
MASTER QUICK-REFERENCE

3-Step Method for ANY Output Question

Step 1 – Will it COMPILE? Check for: illegal modifiers (signed/unsigned), wrong types in conditions (if(int)), catch order
(general before specific), missing static on main, final method being overridden, local var with modifier, interface syntax errors
(implements instead of extends). → If compile error, answer is 'Compilation fails'.

Step 2 – Will it throw RUNTIME EXCEPTION? Check: array index out of bounds (especially args[] zero-based!), null pointer
(uninitialised array, null object method call), divide by zero (ArithmeticException), uncaught Error, ClassCastException. → If
runtime exception, answer is 'An exception is thrown at runtime'.

Step 3 – TRACE the output. For switch: trace fall-through from matched case downward. For finally: always runs. For arrays:
check if it's a shared reference. For Strings: immutable – concatenation = new object. For pass-by-value: primitives
unchanged, array elements changed. For threads: start() vs run(). For exceptions: is it caught? does code continue?

Topic-wise Most Tested Patterns

Topic Most Tested Pattern Key Rule

Language Fund. default values, signed keyword, main() static boolean=false, char=\u0000, signed not
valid

Declarations final method, constructor vs method, interface void ClassName() is a METHOD not
syntax constructor

Operators pass by value/ref, String immutability, bit shift String s+x = new String; array elements
shared

Flow Control switch fall-through, if(int) compile error No break = fall-through. if/while need
boolean

Exceptions finally always runs, Error vs Exception, catch Error NOT caught by catch(Exception)
order

Objects & Coll. null vs NULL, args[] zero-based, uninit array null lowercase. int[] x not initialised →
NPE

Inner Classes anonymous can only extend 1 or implement 1 Method-local: abstract OK, no access
modifiers

Threads start() vs run(), Object methods vs Thread notify() wakes thread, doesn't stop one
methods

Final Tip: The four most common answer options on IndiaBix are: (1) a specific output value, (2) Compilation fails, (3) An
exception is thrown at runtime, (4) No output / runs with no output. Apply the 3-step method above and you will eliminate 3 of 4
options almost instantly. Good luck! You have got this.

IndiaBix Java | For Exam Prep

You might also like