0% found this document useful (0 votes)
3 views22 pages

Java Study Notes

The document provides a comprehensive study guide for Java programming, covering key topics such as data types, variables, operators, and control structures across multiple units. It includes a structured 14-day study plan, coding problems, and viva questions for each unit. Additionally, it outlines essential Java concepts like JDK, JRE, JVM, and the features of Java programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views22 pages

Java Study Notes

The document provides a comprehensive study guide for Java programming, covering key topics such as data types, variables, operators, and control structures across multiple units. It includes a structured 14-day study plan, coding problems, and viva questions for each unit. Additionally, it outlines essential Java concepts like JDK, JRE, JVM, and the features of Java programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

☕ JAVA PROGRAMMING

Complete Study Notes & Exam Guide

Units Covered
Unit 1 → Introduction to Java
Unit 2 → Data Types & Variables
Unit 3 → Operators
Unit 4 → Conditional Statements
Unit 5 → Loops
Unit 6 → Arrays & Enums

Includes: Notes • Study Plan • Viva Q&A • Coding Problems


📅 Study Plan
Follow this 14-day structured plan. Each day = 1–2 hours of focused study.
Day Topic What to Do Revision
Day Introduction to Read Unit 1 notes, understand —
1 Java JDK/JRE/JVM, write Hello World
Day Java Class Write 5 simple programs with Review Day
2 Structure main(), experiment with args 1
Day Primitive Data Study all 8 types, practice type Review Day
3 Types casting, explore Wrappers 2
Day Keywords & Memorise keywords, practice Review Day
4 Variables scope, access modifiers, static 3
Day Operators – Part Arithmetic, relational, logical Review Day
5 1 operators – practice 10 programs 4
Day Operators – Part Bitwise, unary, ternary, Review Day
6 2 precedence table – solve all 5
coding Qs
Day Revision Day Revise Units 1–3, attempt viva Rev Days 1–
7 questions aloud 6
Day If-Else & Switch Code all if/else patterns, switch Review Day
8 with fall-through 7
Day For & While Star patterns, sum series, nested Review Day
9 Loops loops 8
Day Do-While & For- Guess number game, array Review Day
10 Each traversal with for-each 9
Day 1D Arrays Insert, search, sort, reverse – Review Day
11 code all operations 10
Day 2D Arrays & Matrix ops, varargs programs, Review Day
12 Varargs print Pascal's triangle 11
Day Enumerations Enum with methods, constructor, Review Day
13 switch with enum 12
Day Full Revision + Answer all viva Qs, re-do 2 Rev Days 1–
14 Mock Viva coding Qs per unit 13
📘 Unit 1: Introduction to Java
1.1 History of Java
Java was created by James Gosling at Sun Microsystems in 1991 (originally called Oak). It was
publicly released in 1995. Sun Microsystems was later acquired by Oracle in 2010.
• Original name: Oak (inspired by an oak tree outside Gosling's office)
• Designed for interactive television; pivoted to internet applications
• First web browser supporting Java: HotJava (1995)
• Current major version: Java 21 (LTS)

1.2 Features of Java (SECURED PORTABLE)


Mnemonic: Simple • Object-Oriented • Platform-Independent • Secured • Robust •
Architecture Neutral • Portable • Dynamic • Interpreted • High-Performance
Feature Description
Simple Easy syntax, no pointers, automatic memory management
Object-Oriented Everything is an object (except primitives); supports 4 OOP pillars
Platform-Independent Write Once, Run Anywhere – bytecode runs on any JVM
Secured No explicit pointer, bytecode verification, sandbox model
Robust Strong type checking, exception handling, garbage collection
Multithreaded Built-in support for concurrent programming
Architecture Neutral Bytecode is not machine-specific
Portable Same behaviour across all platforms
High Performance JIT compiler converts bytecode to native code at runtime
Distributed Built-in networking via [Link] package

1.3 JDK, JRE, and JVM


Compon Full Form Purpose Contains
ent
JVM Java Virtual Machine Executes bytecode Class loader, bytecode verifier, JIT
(.class files) compiler
JRE Java Runtime Provides runtime to run JVM + libraries ([Link] etc.)
Environment Java programs
JDK Java Development Complete toolkit for JRE + javac + javap + jar + debugger
Kit developing Java
programs
Relationship: JDK ⊃ JRE ⊃ JVM (JDK is the superset)

1.4 Java Program Structure


Every Java program must follow this structure:
// 1. Package declaration (optional)
package mypackage;
// 2. Import statements (optional)
import [Link];

// 3. Class declaration
public class HelloWorld {

// 4. main() method – entry point


public static void main(String[] args) {
[Link]("Hello, World!");
}
}
main() signature: public – accessible from anywhere; static – no object needed; void – returns
nothing; String[] args – command-line arguments

1.5 Command-Line Arguments


Arguments passed to main() at program launch. Accessed via args[0], args[1], ... args are always
Strings.
// Run: java Greet Alice 25
public class Greet {
public static void main(String[] args) {
[Link]("Name: " + args[0]);
int age = [Link](args[1]);
[Link]("Age: " + age);
}
}

1.6 Viva Questions – Unit 1


[Easy] What is Java?
Ans: A high-level, class-based, object-oriented programming language designed to have as few
implementation dependencies as possible.
[Easy] What does JVM stand for and what does it do?
Ans: Java Virtual Machine. It loads, verifies, and executes Java bytecode. It provides platform
independence.
[Easy] Difference between JDK, JRE, and JVM?
Ans: JVM executes bytecode; JRE = JVM + libraries (for running); JDK = JRE + development tools like
javac (for development).
[Medium] What is bytecode?
Ans: Intermediate machine-independent code generated by the Java compiler (javac). Stored in .class files
and executed by JVM.
[Medium] Why is Java platform-independent?
Ans: Java source is compiled to bytecode (not native code). The JVM on each OS interprets this bytecode
– WORA (Write Once Run Anywhere).
[Hard] What is the role of the class loader in JVM?
Ans: Class loader is a part of JVM that loads .class files into memory. It has 3 types: Bootstrap, Extension,
and Application class loaders.
[Hard] What is JIT compiler?
Ans: Just-In-Time compiler is part of JVM that compiles frequently-used bytecode to native machine code
at runtime for performance improvement.

1.7 Coding Questions – Unit 1


Q1. Write a Java program to print 'Hello, World!'
Hint: Use [Link]() inside main()
Q2. Accept name and age from command line and print a greeting
Hint: Use args[0] and [Link](args[1])
Q3. Write a program to display the Java version at runtime
Hint: Use [Link]("[Link]")
📗 Unit 2: Data in the Cart – Data Types & Variables
2.1 Primitive Data Types
Type Size Range / Default Example
byte 1 byte -128 to 127 / 0 byte b = 100;
short 2 bytes -32,768 to 32,767 / 0 short s = 500;
int 4 bytes -2^31 to 2^31-1 / 0 int x = 42;
long 8 bytes -2^63 to 2^63-1 / 0L long l = 99L;
float 4 bytes ±3.4×10^38 / 0.0f float f = 3.14f;
double 8 bytes ±1.7×10^308 / 0.0d double d = 3.14;
char 2 bytes 0 to 65535 (Unicode) / \ char c = 'A';
u0000
boolean 1 bit true / false / false boolean flag = true;

2.2 Type Conversion


Widening (Implicit) – auto, no data loss
int i = 10;
double d = i; // int → double automatically
Order: byte → short → int → long → float → double

Narrowing (Explicit) – manual cast, possible data loss


double d = 9.99;
int i = (int) d; // i = 9 (decimal part lost)

2.3 Keywords in Java


Java has 53 reserved keywords. They cannot be used as identifiers.
Key ones to remember: abstract, assert, boolean, break, byte, case, catch, char, class, const*,
continue, default, do, double, else, enum, extends, final, finally, float, for, goto*, if, implements, import,
instanceof, int, interface, long, native, new, package, private, protected, public, return, short, static,
strictfp, super, switch, synchronized, this, throw, throws, transient, try, void, volatile, while. (* reserved
but not used)

2.4 Identifiers
• Must start with a letter, underscore _ or dollar sign $
• Cannot be a keyword
• Case-sensitive (myVar ≠ MyVar)
• No length limit (but be reasonable)
• Convention: camelCase for variables/methods, PascalCase for classes
2.5 Variables
Type Declared In Default Lifetime
Local Inside a method/block None (must init before use) Within the block
Instance Inside class (no static) Type default (0, null, false) Object lifetime
Static/Class Inside class with static Type default Class lifetime (shared)

2.6 Access Modifiers


Modifier Same Class Same Package Subclass Outside
Package
private ✓ ✗ ✗ ✗
default (no ✓ ✓ ✗ ✗
keyword)
protected ✓ ✓ ✓ ✗
public ✓ ✓ ✓ ✓

2.7 static Keyword


• static variable: shared across all objects of the class
• static method: called without creating an object; cannot access instance members
• static block: runs once when class is loaded; used for initialization
class Counter {
static int count = 0; // static variable
static { count = 100; } // static block
static void show() { [Link](count); } // static method
}

2.8 Wrapper Classes


Wrapper classes wrap primitive types into objects. Needed for Collections (which store Objects only).
Primitive Wrapper Class Useful Method
int Integer [Link](), Integer.MAX_VALUE
double Double [Link](), [Link]()
char Character [Link](), [Link]()
boolean Boolean [Link]()
long Long [Link]()

Autoboxing & Unboxing


Integer obj = 42; // Autoboxing (int → Integer)
int val = obj; // Unboxing (Integer → int)

2.9 Viva Questions – Unit 2


[Easy] What are the 8 primitive data types in Java?
Ans: byte, short, int, long, float, double, char, boolean.
[Easy] What is the default value of int, boolean, and String?
Ans: int = 0, boolean = false, String = null.
[Easy] What is widening vs narrowing conversion?
Ans: Widening: smaller to larger type, automatic. Narrowing: larger to smaller, requires explicit cast, may
lose data.
[Medium] What is a wrapper class? Give an example.
Ans: A class that wraps a primitive value into an object. Example: Integer wraps int. Used when an Object
is required (e.g., in ArrayList).
[Medium] Difference between static and instance variables?
Ans: Static variable is shared by all objects; one copy per class. Instance variable is separate for each
object.
[Medium] What is autoboxing?
Ans: Automatic conversion of primitive to corresponding wrapper class by the compiler. E.g., Integer i = 5;
(int 5 autoboxed to Integer).
[Hard] Can we override a static method?
Ans: No. Static methods belong to the class, not instances. They can be hidden (method hiding) but not
overridden.
[Hard] What is the difference between '==' and .equals() for Integer?
Ans: For Integer objects in range -128 to 127, == works due to caching. Beyond this range, == compares
references (fails); .equals() always compares values.

2.10 Coding Questions – Unit 2


Q1. Demonstrate widening and narrowing type conversion
Hint: Cast double to int and assign int to double
Q2. Create a class with static, instance, and local variables and show their scope
Hint: Use a counter with static int, instance String, local inside method
Q3. Convert a String '123' to int using wrapper class and add 7 to it
Hint: Use [Link]()
Q4. Write a program showing autoboxing and unboxing
Hint: Assign int to Integer and Integer to int
📙 Unit 3: Operators
3.1 Arithmetic Operators
Operator Name Example Result
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
/ Division 7/2 3 (integer)
% Modulus 7%2 1

3.2 Relational (Comparison) Operators


Operator Meaning Example Result
== Equal to 5 == 5 true
!= Not equal to 5 != 3 true
> Greater than 5>3 true
< Less than 5<3 false
>= Greater or equal 5 >= 5 true
<= Less or equal 3 <= 5 true

3.3 Logical Operators


Operator Name Rule Example
&& Logical AND true only if both true (5>3) && (4>2) → true
|| Logical OR true if at least one true (5>3) || (4>9) → true
! Logical NOT inverts boolean !(5>3) → false
Short-circuit: && stops at first false; || stops at first true – avoids unnecessary evaluation

3.4 Bitwise Operators


Work on individual bits of integer values.
Operator Name 5 (0101) op 3 (0011) Result
& Bitwise AND 0101 & 0011 0001 = 1
| Bitwise OR 0101 | 0011 0111 = 7
^ Bitwise XOR 0101 ^ 0011 0110 = 6
~ Bitwise NOT ~5 –6 (two's complement)
<< Left Shift 5 << 1 (multiply by 2) 10
>> Right Shift 20 >> 2 (divide by 4) 5
>>> Unsigned Right Fills with 0 (not sign bit) —
Shift
3.5 Unary Operators
Operator Name Example Effect
+ Unary plus +a Makes value positive
- Unary minus -a Negates the value
++ Increment (pre) ++a Increment first, then use
++ Increment (post) a++ Use first, then increment
-- Decrement (pre) --a Decrement first, then use
-- Decrement (post) a-- Use first, then decrement
! Logical NOT !flag Inverts boolean
~ Bitwise NOT ~a Flips all bits

3.6 Assignment Operators


Operator Equivalent To Example
= a=b a=5
+= a=a+b a += 3
-= a=a-b a -= 2
*= a=a*b a *= 4
/= a=a/b a /= 2
%= a=a%b a %= 3
&= a=a&b a &= 5
|= a=a|b a |= 3
^= a=a^b a ^= 2
<<= a = a << b a <<= 1
>>= a = a >> b a >>= 1

3.7 Ternary Operator


// Syntax: condition ? valueIfTrue : valueIfFalse
int a = 10, b = 20;
int max = (a > b) ? a : b; // max = 20
String result = (a % 2 == 0) ? "Even" : "Odd";

3.8 Operator Precedence (High → Low)


Priority Operators Associativity
1 () [] . Left to Right
(Highest)
2 ++ -- (post) ~ ! Right to Left
3 */% Left to Right
4 +- Left to Right
5 << >> >>> Left to Right
Priority Operators Associativity
6 < > <= >= instanceof Left to Right
7 == != Left to Right
8 & Left to Right
9 ^ Left to Right
10 | Left to Right
11 && Left to Right
12 || Left to Right
13 ?: Right to Left
14 = += -= *= ... Right to Left
(Lowest)

3.9 Viva Questions – Unit 3


[Easy] What is the difference between = and ==?
Ans: = is assignment operator (assigns value). == is relational/equality operator (compares two values).
[Easy] What is a ternary operator? Give syntax.
Ans: Shorthand if-else: condition ? expr1 : expr2. E.g., max = (a>b) ? a : b;
[Easy] What is the output of 5 % 2?
Ans: 1 (remainder when 5 is divided by 2).
[Medium] What is the difference between i++ and ++i?
Ans: i++ is post-increment: current value used first, then incremented. ++i is pre-increment: incremented
first, then used.
[Medium] What does the >>> operator do?
Ans: Unsigned right shift – shifts bits right, filling with 0 (even for negative numbers). Unlike >>, it doesn't
preserve the sign bit.
[Hard] What is the output of: int x = 5; [Link](x++ + ++x);?
Ans: x++ evaluates as 5 (x becomes 6), then ++x makes x=7. So 5 + 7 = 12.
[Hard] What is short-circuit evaluation?
Ans: In && operator, if left operand is false, right is NOT evaluated. In ||, if left is true, right is NOT
evaluated. Saves processing and avoids runtime errors.

3.10 Coding Questions – Unit 3


Q1. Swap two numbers without a third variable
Hint: Use arithmetic: a = a+b; b = a-b; a = a-b; OR use XOR
Q2. Check if a number is even using bitwise AND
Hint: n & 1 == 0 means even
Q3. Write a program to show pre and post increment difference
Hint: int a=5; show a++, ++a side effects
Q4. Find maximum of three numbers using ternary operator
Hint: Nest ternary: max = a>b ? (a>c ? a:c) : (b>c ? b:c)
Q5. Use all compound assignment operators on a variable
Hint: Show +=, -=, *=, /=, %= in sequence
📒 Unit 4: Conditional Statements
4.1 if Statement
if (condition) {
// executes if condition is true
}

4.2 if-else Statement


if (condition) {
// true block
} else {
// false block
}

4.3 if-else if-else (Ladder)


if (marks >= 90) {
grade = 'A';
} else if (marks >= 75) {
grade = 'B';
} else if (marks >= 60) {
grade = 'C';
} else {
grade = 'F';
}

4.4 Nested if
if (age >= 18) {
if (hasID) {
[Link]("Entry allowed");
}
}

4.5 switch-case Statement


switch (expression) { // expression must be int, char, String, or enum
case value1:
// code
break; // IMPORTANT: prevents fall-through
case value2:
// code
break;
default:
// runs if no case matches
}
Fall-through: If break is omitted, execution continues to the next case! Sometimes used
intentionally.

Switch with String (Java 7+)


String day = "MON";
switch (day) {
case "MON": case "TUE": [Link]("Weekday"); break;
case "SAT": case "SUN": [Link]("Weekend"); break;
}

Switch Expression (Java 14+)


String result = switch (score) {
case 1 -> "Bad";
case 5 -> "Good";
default -> "Average";
};

4.6 if vs switch – Comparison


Aspect if-else switch
Condition type Any boolean expression Equality checks only
Allowed types All int, char, String, enum
Range checks Yes (e.g., x > 10) No
Default else default:
Performance Evaluates each condition Jump table – faster for many cases

4.7 Viva Questions – Unit 4


[Easy] What is the purpose of the default case in switch?
Ans: It runs when no case value matches the switch expression. Similar to else in if-else.
[Easy] What types can be used in a switch expression?
Ans: byte, short, int, char, String (Java 7+), and enum. Cannot use long, float, double.
[Medium] What is fall-through in switch?
Ans: When a case does not have a break statement, execution continues to the next case automatically.
[Medium] Can we use a String in switch in Java?
Ans: Yes, from Java 7 onwards. The comparison is done using .equals() internally.
[Medium] Difference between if-else and switch?
Ans: if-else can test any boolean condition (ranges, inequalities). switch only checks equality and works
with specific types. switch can be faster for many equality checks.
[Hard] What is a switch expression (Java 14+)?
Ans: An enhanced switch that can return a value using the -> arrow syntax. Eliminates fall-through and is
more concise.

4.8 Coding Questions – Unit 4


Q1. Write a program to check if a number is positive, negative, or zero
Hint: Use if-else if-else
Q2. Grade calculator: accept marks and print A/B/C/D/F
Hint: Use if-else ladder with conditions >=90, >=75, etc.
Q3. Write a switch program to print day name from number (1–7)
Hint: Map 1→Monday, 2→Tuesday, etc., default→Invalid
Q4. Calculator: accept two numbers and operator (+,-,*,/) and print result
Hint: Use switch on char operator
Q5. Check if year is leap year using if-else
Hint: Leap: divisible by 4, not by 100 unless by 400
📓 Unit 5: Loops
5.1 for Loop
// Syntax
for (initialization; condition; update) {
// body
}

// Example: print 1 to 5
for (int i = 1; i <= 5; i++) {
[Link](i);
}

5.2 while Loop


// Syntax
while (condition) {
// body
// update inside body
}

// Example
int i = 1;
while (i <= 5) {
[Link](i);
i++;
}

5.3 do-while Loop


// Runs at least once regardless of condition
do {
// body
} while (condition);

// Example: menu-driven program


int choice;
do {
[Link]("1. Add 2. Exit");
choice = [Link]();
} while (choice != 2);

5.4 for-each Loop (Enhanced for)


// Syntax
for (dataType element : collection) {
// use element
}

// Example with array


int[] nums = {1, 2, 3, 4, 5};
for (int n : nums) {
[Link](n);
}
for-each does NOT give index access and cannot modify array elements directly.

5.5 Loop Control Statements


Statement Effect Works In
break Exits the loop immediately for, while, do-while, switch
continue Skips current iteration, moves to next for, while, do-while
return Exits the entire method Any

5.6 Loop Comparison


Feature for while do-while for-each
When to use Known count Unknown count At-least-once Iterate collection
Condition check Before iteration Before iteration After iteration Implicit
Min executions 0 0 1 0
Index access Yes Yes (manually) Yes (manually) No

5.7 Nested Loops


// Star triangle pattern
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
[Link]("* ");
}
[Link]();
}

5.8 Viva Questions – Unit 5


[Easy] What is the difference between while and do-while?
Ans: while checks condition before executing; do-while executes at least once, checks condition after.
[Easy] What does break do inside a loop?
Ans: It immediately terminates the nearest loop (or switch) and transfers control to the statement after the
loop.
[Easy] What is a for-each loop? When is it used?
Ans: Enhanced for loop to iterate over arrays and collections without using an index. Used when you need
all elements sequentially.
[Medium] What does continue do?
Ans: Skips the remaining body of the current loop iteration and proceeds to the next iteration.
[Medium] Can we have an infinite loop? How?
Ans: Yes. while(true){} or for(;;){} are common ways. A break statement must exit them.
[Medium] What is the difference between for and for-each?
Ans: for gives index access and can modify array; for-each only reads elements, no index, works on
Iterable/arrays.
[Hard] What is a labeled break?
Ans: A break statement with a label that exits an outer loop from an inner loop. Syntax: outerLabel: for(…)
{ for(…){ break outerLabel; } }

5.9 Coding Questions – Unit 5


Q1. Print multiplication table of a number using for loop
Hint: for(int i=1; i<=10; i++) print n*i
Q2. Print Fibonacci series up to n terms
Hint: Use two variables prev, curr and a for loop
Q3. Reverse a number using while loop
Hint: Extract digits with % 10, build reversed = reversed*10 + digit
Q4. Print a right-angled star triangle using nested for loops
Hint: Outer loop rows, inner loop stars per row
Q5. Sum of digits of a number using do-while
Hint: do { sum += n%10; n/=10; } while(n>0)
Q6. Find factorial using for loop
Hint: for(int i=1; i<=n; i++) fact *= i
Q7. Check if a number is prime using a loop
Hint: Divide from 2 to sqrt(n), if any divides evenly, not prime
📕 Unit 6: Arrays and Enums
6.1 Array Fundamentals
An array is a fixed-size, ordered collection of elements of the same data type. Arrays in Java are
objects.
// Declaration
int[] arr;

// Creation (allocation)
arr = new int[5]; // 5 elements, default 0

// Declaration + Creation + Initialization


int[] arr = {10, 20, 30, 40, 50};

// Access
[Link](arr[0]); // 10
[Link]([Link]); // 5 (not a method, it's a field)
Arrays are zero-indexed: first element is arr[0], last is arr[[Link] – 1]
ArrayIndexOutOfBoundsException is thrown when you access an invalid index!

6.2 Array Iteration


// Using for loop (with index)
for (int i = 0; i < [Link]; i++) {
[Link](arr[i]);
}

// Using for-each (read-only)


for (int val : arr) {
[Link](val);
}

6.3 Multi-Dimensional Arrays


// 2D array declaration
int[][] matrix = new int[3][3];

// 2D array initialization
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Access element at row 1, col 2


[Link](grid[1][2]); // 6
// Iterate 2D array
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < grid[i].length; j++) {
[Link](grid[i][j] + " ");
}
[Link]();
}

Jagged Arrays
int[][] jagged = new int[3][];
jagged[0] = new int[1];
jagged[1] = new int[3];
jagged[2] = new int[2];

6.4 Useful Array Operations


import [Link];

[Link](arr); // sort ascending


[Link](arr, 0); // fill all with 0
int[] copy = [Link](arr, 5); // copy first 5 elements
[Link]([Link](arr)); // print nicely
int idx = [Link](arr, 30); // search (array must be sorted)

6.5 Varargs (Variable Arguments)


Allows a method to accept any number of arguments of the same type. Must be the last parameter.
// Syntax
public static int sum(int... nums) {
int total = 0;
for (int n : nums) total += n;
return total;
}

// Can be called as:


sum(1, 2);
sum(1, 2, 3, 4, 5);
sum(); // zero arguments is valid
Internally, varargs is treated as an array. Only one varargs parameter allowed per method,
and it must be last.

6.6 Enumerations (enum)


An enum is a special class that represents a group of constants (fixed set of values).
// Basic enum
enum Day {
MON, TUE, WED, THU, FRI, SAT, SUN
}
Day d = [Link];
[Link](d); // MON
[Link]([Link]()); // 0 (position)
[Link]([Link]()); // "MON"

Enum with Fields and Constructor


enum Planet {
MERCURY(3.303e+23, 2.4397e6),
EARTH(5.976e+24, 6.37814e6);

private final double mass;


private final double radius;

Planet(double mass, double radius) {


[Link] = mass;
[Link] = radius;
}

public double getMass() { return mass; }


}

Enum with switch


Day d = [Link];
switch (d) {
case SAT: case SUN:
[Link]("Weekend!"); break;
default:
[Link]("Weekday");
}

Enum Methods
Method Description
values() Returns array of all enum constants
ordinal() Returns position (0-based index)
name() Returns name as String
valueOf(String) Returns enum constant with given name
compareTo() Compares by ordinal position

6.7 Viva Questions – Unit 6


[Easy] What is an array in Java?
Ans: A fixed-size collection of elements of the same data type stored in contiguous memory. Indexed from
0.
[Easy] What is the default value of array elements?
Ans: int/short/byte → 0; float/double → 0.0; boolean → false; String/Object → null.
[Easy] What is a jagged array?
Ans: A 2D array where each row can have a different number of columns.
[Medium] What is varargs?
Ans: Variable-length arguments. Allows a method to receive any number of arguments of the same type.
Internally treated as an array.
[Medium] What is an enum in Java?
Ans: A special type that defines a fixed set of named constants. Implicitly extends [Link].
[Medium] Can enum have a constructor?
Ans: Yes, but the constructor must be private (or package-private). It is called when each constant is
defined.
[Medium] Difference between Array and ArrayList?
Ans: Array: fixed size, can store primitives, faster. ArrayList: dynamic size, stores only objects, part of
Collections Framework.
[Easy] What happens if you access arr[-1] or arr[[Link]]?
Ans: ArrayIndexOutOfBoundsException is thrown at runtime.
[Hard] How does [Link]() work internally?
Ans: For primitives it uses Dual-Pivot Quicksort. For objects it uses TimSort (merge + insertion). Both are
from [Link].
[Hard] Can an enum implement an interface?
Ans: Yes. An enum can implement interfaces but cannot extend other classes (it already implicitly extends
[Link]).
[Hard] What is the difference between ordinal() and compareTo() in enum?
Ans: ordinal() returns the 0-based position. compareTo() returns the difference in ordinals between two
enum constants.

6.8 Coding Questions – Unit 6


Q1. Find the largest and smallest element in an array
Hint: Iterate with a loop, track max and min
Q2. Reverse an array in place
Hint: Swap arr[i] and arr[n-1-i] for i from 0 to n/2
Q3. Check if an array is sorted
Hint: Iterate and check arr[i] <= arr[i+1] for all i
Q4. Matrix multiplication of two 3×3 arrays
Hint: Triple nested loop: result[i][j] += A[i][k] * B[k][j]
Q5. Write a method using varargs to find the sum of any number of integers
Hint: public static int sum(int... nums)
Q6. Create an enum for Seasons with a method getDescription()
Hint: enum Season { SUMMER, WINTER, MONSOON, SPRING } with description()
Q7. Use [Link]() and [Link]() on an integer array
Hint: Sort first, then binarySearch for a value
Q8. Print diagonal elements of a 2D square matrix
Hint: Print grid[i][i] for i from 0 to n-1
⚡ Quick Reference Cheat Sheet
Data Types at a Glance
Type Size Range
byte 1B -128 to 127
short 2B -32,768 to 32,767
int 4B -2.1B to 2.1B
long 8B -9.2Q to 9.2Q (use L suffix)
float 4B ~7 decimal digits (use f suffix)
double 8B ~15 decimal digits
char 2B Unicode 0–65535
boolean 1bit true / false

Operator Precedence (Quick)


() > ++ -- (post) > * / % > + - > << >> > < > <= >= > == != > & > ^ > | > && > || > ?: > =

Loop Choice Guide


Situation Use
Known number of iterations for loop
Condition-based, may not execute while loop
Must execute at least once do-while loop
Iterate array/collection for-each loop

Common Mistakes to Avoid


• Forgetting break in switch → fall-through bug
• Using == to compare Strings → use .equals()
• Accessing arr[[Link]] → ArrayIndexOutOfBoundsException
• Integer division: 7/2 = 3 (not 3.5) → use 7.0/2 for double
• Using float without 'f' suffix: float f = 3.14 → compile error (is double)
• Declaring local variable without initialization → compile error
• Putting varargs parameter before other parameters → compile error

All the best for your exam! 🚀 Study smart, code daily.

You might also like