0% found this document useful (0 votes)
6 views16 pages

Complete Java Guide For Competitive Programming Exam

This document is a comprehensive guide for Java programming focused on competitive exams, covering essential topics such as operator precedence, control flow statements, arrays, strings, mathematical operations, bitwise operations, recursion, collections framework, exception handling, input/output, algorithms, and exam-specific patterns. It includes critical rules, common pitfalls, and practical examples to aid in understanding and application. Additionally, it provides last-minute exam tips and a quick reference for time complexities.
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)
6 views16 pages

Complete Java Guide For Competitive Programming Exam

This document is a comprehensive guide for Java programming focused on competitive exams, covering essential topics such as operator precedence, control flow statements, arrays, strings, mathematical operations, bitwise operations, recursion, collections framework, exception handling, input/output, algorithms, and exam-specific patterns. It includes critical rules, common pitfalls, and practical examples to aid in understanding and application. Additionally, it provides last-minute exam tips and a quick reference for time complexities.
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

Complete Java Guide for Competitive Programming Exam

🔥 1. OPERATORS & PRECEDENCE (MOST IMPORTANT!)


Operator Precedence (High to Low):
1. () - Parentheses
2. ++ , -- - Increment/Decrement

3. * , / , % - Multiplication, Division, Modulus


4. + , - - Addition, Subtraction

5. << , >> , >>> - Shift operators

6. < , <= , > , >= - Relational


7. == , != - Equality

8. & , ^ , | - Bitwise
9. && , || - Logical

10. ? : - Ternary
11. = , += , -= - Assignment

Critical String + Number Rules:

java

// MEMORIZE THESE PATTERNS:


[Link](10 + 20 + "30"); // "3030" (numbers first)
[Link]("30" + 10 + 20); // "301020" (string first)
[Link](10 + 20 + "30" + 40); // "303040"

Rule: Once string appears, everything becomes string concatenation!


Pre/Post Increment PATTERNS:

java

int x = 5;
[Link](x++); // Prints 5, then x becomes 6
[Link](++x); // x becomes 7, then prints 7

// Common exam pattern:


int a = 5;
int result = a++ + ++a; // 5 + 7 = 12 (a becomes 6, then 7)

Memory Trick: x++ = use then change, ++x = change then use

Logical Operators & Short Circuit:

java

// && stops if first is false


// || stops if first is true
int a = 10, b = 20;
if(a++ > 10 && ++b > 20) { } // a becomes 11, but b stays 20!

🎯 2. CONTROL FLOW STATEMENTS


Switch-Case Rules:

java
switch(value) {
case 1:
[Link]("One");
// NO BREAK = FALL THROUGH!
case 2:
[Link]("Two");
break;
default:
[Link]("Default");
}

Key Points:

No break = fall through to next case

Default can be anywhere (not just end)

Only int, char, String, enum allowed

Loop Control:

java

// LABELED BREAK/CONTINUE
outer: for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
if(i == 1 && j == 1)
break outer; // Breaks outer loop
[Link](i + "" + j + " ");
}
}
// Output: 00 01 02 10
For Loop Variations:

java

// Traditional
for(int i = 0; i < 5; i++) { }

// Enhanced (for arrays/collections)


int[] arr = {1,2,3,4,5};
for(int x : arr) { [Link](x); }

// Multiple variables
for(int i = 0, j = 10; i < j; i++, j--) { }

📊 3. ARRAYS (HIGH FREQUENCY!)


Array Basics:

java

int[] arr = new int[5]; // Creates array of size 5


int[] arr2 = {1, 2, 3, 4, 5}; // Direct initialization
[Link]([Link]); // Property (no parentheses!)

// 2D Arrays
int[][] matrix = {{1,2,3}, {4,5,6}};
[Link]([Link]); // 2 (rows)
[Link](matrix[0].length); // 3 (columns in row 0)

Array Bounds:

java
int[] arr = {1, 2, 3, 4, 5};
// Valid indices: 0, 1, 2, 3, 4
// arr[5] or arr[-1] = ArrayIndexOutOfBoundsException!

Array vs ArrayList:
Array: Fixed size, [Link]

ArrayList: Dynamic size, [Link]()

🔤 4. STRINGS (VERY IMPORTANT!)


String Methods:

java

String s = "programming";
[Link](0); // 'p' (character at index)
[Link](); // 11 (method with parentheses!)
[Link](3, 7); // "gram" (from index 3 to 6)
[Link]('r'); // 1 (first occurrence)
[Link]("programming"); // true (content comparison)

String vs StringBuilder:

java
// SLOW for multiple concatenations
String s = "";
for(int i = 0; i < 1000; i++) {
s += i; // Creates new string each time!
}

// FAST for multiple concatenations


StringBuilder sb = new StringBuilder();
for(int i = 0; i < 1000; i++) {
[Link](i);
}
String result = [Link]();

String Comparison:

java

String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");

s1 == s2; // true (same reference in string pool)


s1 == s3; // false (different references)
[Link](s3); // true (same content)

🧮 5. MATHEMATICAL OPERATIONS
Math Class Methods:

java
[Link](2, 3); // 8.0 (returns double)
[Link](16); // 4.0
[Link](3.2); // 4.0 (round up)
[Link](3.8); // 3.0 (round down)
[Link](-5); // 5 (absolute value)
[Link](10, 20); // 20
[Link](10, 20); // 10

Division Rules:

java

10 / 3; // 3 (integer division)
10.0 / 3; // 3.333... (floating division)
10 / 0; // ArithmeticException
10.0 / 0; // Infinity (no exception!)

Modulus Operator:

java

10 % 3; // 1 (remainder)
-10 % 3; // -1 (keeps sign of dividend)
10 % -3; // 1

🔢 6. BITWISE OPERATIONS
Basic Bitwise Operators:

java
int a = 5; // 101 in binary
int b = 3; // 011 in binary

a & b; // 1 (001) - AND


a | b; // 7 (111) - OR
a ^ b; // 6 (110) - XOR
~a; // -6 (complement)

Shift Operators:

java

8 << 1; // 16 (left shift = multiply by 2)


8 >> 1; // 4 (right shift = divide by 2)
8 >>> 1; // 4 (unsigned right shift)

Quick Patterns:

n << k = n * 2^k

n >> k = n / 2^k

a ^ b ^ b = a (XOR property)

🔄 7. RECURSION
Basic Recursion Pattern:

java
public static int factorial(int n) {
// Base case (MUST HAVE!)
if(n <= 1) return 1;

// Recursive case
return n * factorial(n - 1);
}

Common Recursive Algorithms:

java

// GCD (Euclidean Algorithm)


public static int gcd(int a, int b) {
if(b == 0) return a;
return gcd(b, a % b);
}

// Fibonacci
public static int fib(int n) {
if(n <= 1) return n;
return fib(n-1) + fib(n-2);
}

Memory: Recursion uses call stack - can cause StackOverflowError if too deep!

📦 8. COLLECTIONS FRAMEWORK
ArrayList vs Array:

java
// Array - Fixed size
int[] arr = new int[5];
[Link]; // Property

// ArrayList - Dynamic size


ArrayList<Integer> list = new ArrayList<>();
[Link](10);
[Link](); // Method
[Link](0); // Access element
[Link](0); // Remove by index

HashMap - Key-Value Pairs:

java

HashMap<String, Integer> map = new HashMap<>();


[Link]("apple", 10); // Add/Update
[Link]("apple"); // Get value (returns 10)
[Link]("apple"); // Check if key exists
[Link]("apple"); // Remove key-value pair

Time Complexities:
ArrayList: Access O(1), Insert/Delete O(n)

HashMap: Get/Put O(1) average

TreeSet/TreeMap: All operations O(log n)

⚠️ 9. EXCEPTION HANDLING
Try-Catch-Finally:

java
try {
int x = 10 / 0; // ArithmeticException
} catch(ArithmeticException e) {
[Link]("Division by zero!");
} finally {
[Link]("Always executes");
}

Common Exceptions:
ArithmeticException : Division by zero (integers only)

ArrayIndexOutOfBoundsException : Invalid array index

InputMismatchException : Scanner input type mismatch

NullPointerException : Accessing null reference

📥 10. INPUT/OUTPUT
Scanner Class:

java

Scanner sc = new Scanner([Link]);


int n = [Link](); // Read integer
double d = [Link](); // Read double
String s = [Link](); // Read word
String line = [Link](); // Read entire line

Important: nextLine() after nextInt() can cause issues due to leftover newline!

Output:

java
[Link](x); // No newline
[Link](x); // With newline
[Link]("%.2f", 3.14159); // Formatted output: 3.14

🏆 11. ALGORITHMS & PATTERNS


Searching:

java

// Binary Search (Array must be sorted!)


public static int binarySearch(int[] arr, int target) {
int left = 0, right = [Link] - 1;
while(left <= right) {
int mid = left + (right - left) / 2;
if(arr[mid] == target) return mid;
else if(arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1; // Not found
}

Sorting:

java

int[] arr = {5, 2, 8, 1, 9};


[Link](arr); // Sorts in ascending order

// For ArrayList
[Link](list);
Prime Checking:

java

public static boolean isPrime(int n) {


if(n <= 1) return false;
if(n <= 3) return true;
if(n % 2 == 0 || n % 3 == 0) return false;

for(int i = 5; i * i <= n; i += 6) {
if(n % i == 0 || n % (i + 2) == 0)
return false;
}
return true;
}

💡 12. EXAM-SPECIFIC PATTERNS


Boyer-Moore Voting (Majority Element):

java
public static int findMajority(int[] arr) {
int candidate = 0, count = 0;

// Phase 1: Find candidate


for(int num : arr) {
if(count == 0) candidate = num;
count += (num == candidate) ? 1 : -1;
}

// Phase 2: Verify (if needed)


count = 0;
for(int num : arr) {
if(num == candidate) count++;
}

return count > [Link] / 2 ? candidate : -1;


}

Leaders in Array:

java
// Element greater than all elements to its right
public static void findLeaders(int[] arr) {
int n = [Link];
int maxFromRight = arr[n-1];

[Link](arr[n-1] + " "); // Last element is always leader

for(int i = n-2; i >= 0; i--) {


if(arr[i] > maxFromRight) {
[Link](arr[i] + " ");
maxFromRight = arr[i];
}
}
}

🎯 LAST-MINUTE EXAM TIPS


Quick Mental Checklist:
1. String + Number: Remember concatenation rules!
2. ++/--: Pre vs Post increment
3. Switch: Check for missing breaks

4. Arrays: Watch for index bounds (0 to length-1)


5. Division: Integer vs floating point

6. Loops: Look for infinite loops or off-by-one errors

Common Traps:
[Link] vs [Link]()

== vs equals() for strings


Integer overflow (use long if needed)
Scanner input mismatches

Time Complexity Quick Reference:


Linear search: O(n)
Binary search: O(log n)

Sorting: O(n log n)


HashMap operations: O(1) average
ArrayList access: O(1), insert/delete: O(n)

Final Tip: Read questions carefully! Many MCQs test your ability to trace through code step by
step. Take your time and work through each line methodically.

Good luck! You've got this! 🚀

You might also like