Week 1 — Java Basics & Setup
Goal: Build bullet‑proof fundamentals so you can solve entry‑level to intermediate interview problems using
Java.
Day 1 — Install, Setup, and First Program
1) JDK vs JRE vs JVM (quick)
• JVM: Runs compiled Java bytecode.
• JRE: JVM + standard libraries (runtime only).
• JDK: JRE + compiler + tools (what you install to develop).
Install: Download an LTS JDK (e.g., 17 or 21). After install, confirm:
java -version
javac -version
You should see the installed versions.
2) Project setup (IDE or terminal)
• IntelliJ/Eclipse: Create a new “Java” project → add a class with main .
• Terminal: Save as Hello.java → javac Hello.java → java Hello .
3) First program
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}
4) Structure & naming
• Class names: PascalCase , methods/variables: camelCase .
• One public class per file, name file exactly as the public class ( Hello.java ).
• Use meaningful names and small methods.
5) Common gotchas
• File name and public class must match.
1
• main signature must be exact: public static void main(String[] args) .
• Encoding: save as UTF‑8 to avoid stray characters.
Mini‑drill 1. Print your name, today’s date, and a motivational quote. 2. Compile + run from terminal.
Day 2 — Variables, Data Types, Type Casting
1) Primitive types
Type Bits Range (approx) Example
byte 8 −128 to 127 byte b = 120;
short 16 −32k to 32k short s = 1000;
int 32 −2.1B to 2.1B int n = 42;
long 64 huge long big = 42L;
float 32 ~7 digits float f = 3.14f;
double 64 ~15 digits double d = 3.14159;
char 16 Unicode code unit char c = 'A';
boolean 1 (logical) true/false boolean ok = true;
Tip: For money, prefer BigDecimal (precision) rather than double .
2) Reference types
• String , arrays, classes, interfaces… stored as references.
• Default for objects is null . Don’t call methods on null (NullPointerException).
3) Literals & suffixes
• long needs L (e.g., 10000000000L ).
• float needs f (e.g., 1.23f ).
• Underscores for readability: int x = 1_000_000; (no leading/trailing).
4) Type casting
• Widening (safe/implicit): int → long → float → double .
• Narrowing (explicit): may overflow or truncate.
int a = 130;
byte b = (byte) a; // b becomes -126 due to overflow
2
5) Wrappers & autoboxing
• Primitives: int ; Wrapper: Integer .
• Autoboxing/unboxing happens automatically but has overhead—avoid in hot loops.
6) var (local variable type inference)
• var x = 5; // type is int . Improves readability when type is obvious.
Mini‑drill - Convert Celsius to Fahrenheit (double), print with 2 decimals. - Cast a double to int and
observe truncation.
Day 3 — Operators (Arithmetic, Logical, Comparison, Bitwise)
1) Arithmetic
+ - * / % and unary + - ++ -- .
int a = 7, b = 2;
System.out.println(a / b); // 3 (integer division!)
System.out.println(a / (double) b); // 3.5
System.out.println(-7 % 2); // -1 (sign follows dividend)
Precedence: * / % before + - . Use parentheses to be explicit.
2) Assignment
=, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, >>>=
3) Comparison
== != < <= > >= - For primitives: compares values. - For objects (e.g., String): == compares
references; use .equals() for content.
String s1 = new String("hi");
String s2 = new String("hi");
System.out.println(s1 == s2); // false
System.out.println(s1.equals(s2)); // true
4) Logical
&& (AND), || (OR), ! (NOT) - Short‑circuiting: in A && B , B not evaluated if A is false; in A || B ,
B not evaluated if A is true.
3
5) Bitwise (interview‑useful)
& | ^ ~ << >> >>>
int x = 5; // 0101
int y = 3; // 0011
System.out.println(x & y); // 1 (0001)
System.out.println(x | y); // 7 (0111)
System.out.println(x ^ y); // 6 (0110)
System.out.println(~x); // bitwise NOT
System.out.println(x << 1);// 10 (1010)
>>> is unsigned right shift. Useful in hashing/low‑level tasks.
Mini‑drill - Check if a number is even using bitwise: (n & 1) == 0 . - Swap two ints without temp (XOR
method). When to avoid? (Readability; also fails if both refer to same variable in some languages, but safe
in Java with distinct vars.)
Day 4 — Input & Output (Scanner, System.out)
1) Printing
System.out.print("No newline");
System.out.println("With newline");
System.out.printf("Pi ~ %.2f\n", Math.PI); // format specifiers
Common specifiers: %d int, %f float/double, %s string, %n platform newline.
2) Reading with Scanner
import java.util.*;
public class ReadDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter name: ");
String name = sc.nextLine();
System.out.print("Enter age: ");
int age = sc.nextInt();
System.out.printf("Hi %s, age %d%n", name, age);
// Do not close sc if you need System.in later; closing closes
4
System.in.
}
}
Gotcha: mixing nextInt() and nextLine() — the newline after the number stays in the buffer. Fix by
consuming it:
int age = sc.nextInt();
sc.nextLine(); // consume end-of-line
String name = sc.nextLine();
3) Faster input (optional)
For competitive use: BufferedReader + StringTokenizer or java.io.Console (interactive). For
Week‑1, Scanner is enough.
Mini‑drill - Read n , then read n integers and print their sum and average to 2 decimals.
Day 5 — Conditional Statements
1) if / else if / else
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else {
grade = 'C';
}
- Keep branches simple; extract methods for complex logic.
2) switch
• Works with int , char , String , enum …
• Classic switch (fall‑through)
switch (day) {
case 1:
case 2:
case 3:
case 4:
5
case 5:
System.out.println("Weekday");
break; // prevent fall-through
case 6:
case 7:
System.out.println("Weekend");
break;
default:
System.out.println("Invalid day");
}
• Switch expression (modern Java)
String type = switch (ch) {
case 'a', 'e', 'i', 'o', 'u' -> "vowel";
default -> "consonant";
};
Prefer switch expressions for concise, non‑fall‑through logic.
3) Ternary ?:
String parity = (n % 2 == 0) ? "even" : "odd";
Use for simple expressions. Avoid nesting.
Common pitfalls - Using == for String comparison (use .equals ). - Missing break in classic
switch → unintended fall‑through. - Over‑nested if chains → refactor.
Mini‑drill - Given a year, determine if it’s a leap year. - Map a numeric score to A/B/C/D/F with boundaries.
Day 6 — Loops (for, while, do‑while) + Control Flow
1) for loop
for (int i = 0; i < n; i++) {
// body
}
- Index‑based; ideal when you know counts.
6
2) Enhanced for-each
int[] arr = {2, 4, 6};
for (int v : arr) {
System.out.println(v);
}
- Read‑only iteration (no index). To modify elements, use index‑based.
3) while loop
while (condition) {
// runs 0..N times
}
Used when iterations depend on a condition that changes inside the loop.
4) do-while loop
do {
// runs at least once
} while (condition);
5) break , continue , labels
outer: for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (bad(i, j)) break outer; // exits both loops
if (skip(i, j)) continue; // skip current (i,j)
}
}
Use labels sparingly; often a refactor to a method is cleaner.
6) String concatenation in loops
• += on String creates many objects → use StringBuilder .
StringBuilder sb = new StringBuilder();
for (String s : words) sb.append(s);
String result = sb.toString();
7
Mini‑drill - Reverse an array in‑place. - Count digits of an integer without converting to String. - Print a
half‑pyramid of * of height n .
Interview‑Style Problems (with patterns & solutions)
1) FizzBuzz (control flow)
Print 1..n; multiples of 3 → "Fizz", 5 → "Buzz", both → "FizzBuzz".
for (int i = 1; i <= n; i++) {
if (i % 15 == 0) System.out.println("FizzBuzz");
else if (i % 3 == 0) System.out.println("Fizz");
else if (i % 5 == 0) System.out.println("Buzz");
else System.out.println(i);
}
2) Reverse a number
int rev = 0;
int x = n;
while (x != 0) {
rev = rev * 10 + (x % 10);
x /= 10;
}
Watch for overflow if n can be very large (use long ).
3) Palindrome string (case‑insensitive)
String s = input.toLowerCase();
int i = 0, j = s.length() - 1;
boolean ok = true;
while (i < j) {
if (s.charAt(i) != s.charAt(j)) { ok = false; break; }
i++; j--;
}
4) Prime check (trial division)
boolean isPrime(int n) {
if (n < 2) return false;
8
if (n % 2 == 0) return n == 2;
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) return false;
}
return true;
}
5) Count frequency of digits (0–9)
int[] freq = new int[10];
int x = Math.abs(n);
if (x == 0) freq[0]++;
while (x > 0) {
freq[x % 10]++;
x /= 10;
}
6) Sum of array, max/min, second largest
int sum = 0, max = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int v : arr) {
sum += v;
if (v > max) { second = max; max = v; }
else if (v > second && v != max) { second = v; }
}
7) GCD (Euclid)
int gcd(int a, int b) {
while (b != 0) {
int t = a % b;
a = b; b = t;
}
return Math.abs(a);
}
Precision, Equality, and Edge Cases (often asked)
• Floating‑point: 0.1 + 0.2 != 0.3 exactly. Compare with tolerance:
9
boolean nearlyEqual(double x, double y, double eps) {
return Math.abs(x - y) < eps;
}
• String equality: always .equals() or .equalsIgnoreCase() .
• Overflow: int overflow wraps around; use long / BigInteger if needed.
• Input pitfalls: Scanner.nextLine() after numeric reads—consume newline.
Pattern Library (how to think in interviews)
1) Two‑pointer (start/end indices for arrays/strings): reverse, palindrome. 2) Counting/Hashing: frequency
arrays/maps for membership and duplicates. 3) Accumulation: keep running sum/min/max while iterating.
4) Early exit: break as soon as the answer is known. 5) Invariant: identify what remains true each loop (e.g.,
i + j moving inward).
Quick Practice Set (try first, then see solutions above)
1. Leap year: divisible by 4, except centuries not divisible by 400.
2. Read n , then n numbers → print sum, average, max, min.
3. Print multiplication table for n up to 10.
4. Count vowels/consonants in a string (letters only).
5. Determine if an integer is an Armstrong number (3‑digit: sum of cubes equals number).
Clean Code & Performance Tips
• Prefer meaningful names and small, single‑purpose methods.
• Avoid deep nesting: return early.
• Use StringBuilder for concatenation in loops.
• Don’t overuse autoboxing; favor primitives in tight loops.
• Write unit tests for your helper methods (once you reach Week‑2+).
Rapid Reference (cheat sheet)
• Print: System.out.println(x); System.out.printf("%d %n", n);
• Input: Scanner sc = new Scanner(System.in); int n = sc.nextInt();
• If: if (a > b) {...} else {...}
• Switch: switch (s) { case "YES" -> 1; default -> 0; }
• Loops: for , while , do‑while , for‑each
• Break/Continue: exits loop / skip iteration
• String eq: a.equals(b)
10
• Even check: (n & 1) == 0
Self‑Assessment (interview‑style)
• Explain short‑circuiting with an example; why is it useful?
• What’s the difference between == and .equals() for String ?
• When would you choose switch over if‑else ?
• Why avoid concatenating strings in a loop? What to use instead?
• Show how to read a full line after reading an int with Scanner .
Next Steps
• Re‑implement all mini‑drills without looking.
• Time yourself on FizzBuzz, palindrome, prime, and GCD.
• Solve 10 pattern printing problems (pyramids, diamonds) using nested loops.
11