-
-
Notifications
You must be signed in to change notification settings - Fork 2
Java Notes
This guide covers all essential Java topics in a format perfect for studying and exam preparation. Each section includes explanations, examples, and common patterns.
- Variables and Data Types
- Operators
- Control Flow
- Methods
- Arrays
- Object-Oriented Programming
- Inheritance and Polymorphism
- Interfaces and Abstract Classes
- Exception Handling
- Collections Framework
- Generics
- Lambda Expressions and Streams
- Common Methods Quick Reference
- Syntax Rules Summary
- Common Errors and Fixes
Variables are containers for storing data values. Think of them as labeled boxes where you can put information. Each box has a type that tells Java what kind of data it holds.
Java has 8 primitive types that represent the most basic data:
Integer Types (Whole Numbers)
| Type | Size | Typical Use |
|---|---|---|
byte |
8 bits | Small numbers, memory-efficient |
short |
16 bits | Small integers |
int |
32 bits | Most common for whole numbers |
long |
64 bits | Very large numbers |
Example: int age = 25;
Decimal Types (Floating-Point)
| Type | Size | Typical Use |
|---|---|---|
float |
32 bits | Decimal numbers (less precise) |
double |
64 bits | Most common for decimals |
Example: double price = 19.99;
Other Types
| Type | Size | Typical Use |
|---|---|---|
boolean |
1 bit | True or false values |
char |
16 bits | Single character |
Example: boolean isActive = true;
Example: char grade = 'A';
Reference types store objects (instances of classes). The most common is String:
String name = "Alice";
String message = "Hello, World!";Basic declaration:
int number;
String text;
boolean flag;Declaration with initialization:
int count = 10;
String name = "Bob";Use final to create a constant - a value that cannot be changed:
final int MAX_SIZE = 100;
final double PI = 3.14159;Implicit (Automatic) Conversion
Java automatically converts smaller types to larger types:
int num = 100;
long bigNum = num; // int converts to long automatically
double decimal = bigNum; // long converts to doubleExplicit (Manual) Conversion
Use casting when converting larger to smaller:
double decimal = 9.99;
int whole = (int) decimal; // Result: 9 (decimal part lost)String Conversions
Converting to String:
int num = 42;
String str = String.valueOf(num); // "42"
String str2 = Integer.toString(num); // "42"
String str3 = num + ""; // "42" (quick trick)Converting from String:
String str = "123";
int num = Integer.parseInt(str); // 123
double d = Double.parseDouble("3.14"); // 3.14- Must start with a letter, underscore, or dollar sign
- Can contain letters, numbers, underscores, dollar signs
- Case sensitive (age and Age are different)
- Cannot use Java keywords
- Variables: camelCase (firstName, userAge)
- Constants: UPPER_SNAKE_CASE (MAX_SIZE, PI)
- Classes: PascalCase (Person, BankAccount)
- Methods: camelCase with verb (calculateTotal, printMessage)
These perform mathematical calculations:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ |
Addition | 5 + 3 | 8 |
- |
Subtraction | 5 - 3 | 2 |
* |
Multiplication | 5 * 3 | 15 |
/ |
Division | 5 / 3 | 1 (integer) |
% |
Modulus (remainder) | 5 % 3 | 2 |
Important Notes:
- Integer division truncates decimals:
5 / 2 = 2, not 2.5 - Use double for decimal division:
5.0 / 2 = 2.5
int result = 10 + 5; // 15
result = result - 3; // 12
result = result * 2; // 24
result = result / 4; // 6
result = result % 4; // 2int x = 5;
x++; // x is now 6 (post-increment)
++x; // x is now 7 (pre-increment)
x--; // x is now 6 (post-decrement)
--x; // x is now 5 (pre-decrement)Difference between post and pre:
int a = 5;
int b = a++; // b = 5, a = 6 (assigns then increments)
int c = 5;
int d = ++c; // d = 6, c = 6 (increments then assigns)Shorthand for combining operations:
int num = 10;
num += 5; // num = num + 5 -> 15
num -= 3; // num = num - 3 -> 12
num *= 2; // num = num * 2 -> 24
num /= 4; // num = num / 4 -> 6
num %= 5; // num = num % 5 -> 1These return boolean (true or false):
| 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 | 5 <= 3 | false |
Combine boolean values:
| Operator | Meaning | True When |
|---|---|---|
&& |
AND | Both are true |
|| |
OR | At least one is true |
! |
NOT | Value is false |
boolean a = true;
boolean b = false;
a && b // false (both must be true)
a || b // true (at least one is true)
!a // false (inverts the value)A compact if-else in one line:
// syntax: condition ? valueIfTrue : valueIfFalse
int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";
// Result: "Adult"Order of operations (PEMDAS):
- Parentheses
() - Unary
! ++ -- - Multiplicative
* / % - Additive
+ - - Comparison
< > <= >= - Equality
== != - Logical AND
&& - Logical OR
|| - Assignment
= += -= etc
Execute code based on conditions:
if (condition) {
// runs if condition is true
}
if (condition) {
// runs if true
} else {
// runs if false
}
if (grade >= 90) {
System.out.println("A");
} else if (grade >= 80) {
System.out.println("B");
} else if (grade >= 70) {
System.out.println("C");
} else {
System.out.println("F");
}Choose between multiple options:
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
default:
dayName = "Unknown";
break;
}Switch Expression (Java 14+):
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Unknown";
};Grouping Cases:
switch (grade) {
case 'A':
case 'B':
case 'C':
System.out.println("Pass");
break;
case 'D':
case 'F':
System.out.println("Fail");
break;
}Repeat code a specific number of times:
// Basic structure
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
// Output: 0, 1, 2, 3, 4Parts:
-
int i = 0- Starting point -
i < 5- Condition (run while true) -
i++- Increment after each iteration
Countdown:
for (int i = 10; i > 0; i--) {
System.out.println(i);
}Step by 2:
for (int i = 0; i <= 20; i += 2) {
System.out.println(i); // 0, 2, 4, 6... 20
}Loop through arrays or collections without index:
String[] names = {"Alice", "Bob", "Charlie"};
for (String name : names) {
System.out.println(name);
}Repeat while condition is true:
int count = 1;
while (count <= 5) {
System.out.println(count);
count++;
}Runs at least once (checks condition after):
int num = 10;
do {
System.out.println(num);
num--;
} while (num > 0);-
break- Exit the loop immediately -
continue- Skip to next iteration
// Break example - find first even number
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
System.out.println("Found: " + i);
break; // Exit loop
}
}
// Continue example - skip odd numbers
for (int i = 1; i <= 10; i++) {
if (i % 2 != 0) {
continue; // Skip to next iteration
}
System.out.println(i); // Only prints even: 2, 4, 6, 8, 10
}Methods are blocks of code that perform specific tasks. They let you reuse code without repeating it.
public static int add(int a, int b) {
return a + b;
}Parts:
-
public- Access modifier -
static- Can call without creating object -
int- Return type -
add- Method name -
(int a, int b)- Parameters -
return a + b- Return value
No return (void):
public static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
// Call: greet("Alice");With return:
public static int square(int num) {
return num * num;
}
// Call: int result = square(5); // result = 25No parameters:
public static String getMessage() {
return "Welcome!";
}Multiple parameters:
public static int calculate(int a, int b, String operation) {
if (operation.equals("add")) {
return a + b;
} else if (operation.equals("subtract")) {
return a - b;
}
return 0;
}Same method name, different parameters:
// Different parameter types
public static int add(int a, int b) {
return a + b;
}
public static double add(double a, double b) {
return a + b;
}
public static int add(int a, int b, int c) {
return a + b + c;
}
// Usage:
add(5, 3); // Calls first version
add(5.5, 3.2); // Calls second version
add(1, 2, 3); // Calls third version- Static - Call using class name, no object needed
- Instance - Must create object first
class Calculator {
static int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
}
// Static call:
int sum = Calculator.add(5, 3);
// Instance call:
Calculator calc = new Calculator();
int diff = calc.subtract(5, 3);Arrays store multiple values of the same type in a single variable.
// Method 1: Specify size
int[] numbers = new int[5]; // Array of 5 integers
// Method 2: Initialize with values
int[] numbers = {1, 2, 3, 4, 5};
// Method 3: String array
String[] names = {"Alice", "Bob", "Charlie"};Array indices start at 0:
int[] scores = {95, 87, 92, 78, 88};
scores[0] // First element: 95
scores[1] // Second element: 87
scores[4] // Fifth element: 88int[] numbers = {1, 2, 3, 4, 5};
numbers[0] = 10; // Change first element
System.out.println(numbers[0]); // 10int[] arr = {1, 2, 3, 4, 5};
System.out.println(arr.length); // 5int[] numbers = {1, 2, 3, 4, 5};
// Traditional for loop
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
// Enhanced for-loop
for (int num : numbers) {
System.out.println(num);
}Find maximum:
int[] numbers = {5, 12, 3, 8, 99, 1};
int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
System.out.println("Max: " + max); // 99Calculate sum:
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int num : numbers) {
sum += num;
}
System.out.println("Sum: " + sum); // 15Search for value:
String[] names = {"Alice", "Bob", "Charlie", "Diana"};
String searchName = "Charlie";
boolean found = false;
for (String name : names) {
if (name.equals(searchName)) {
found = true;
break;
}
}
System.out.println("Found: " + found); // trueArray of arrays (like a table):
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
grid[0][0] // First row, first column: 1
grid[1][2] // Second row, third column: 6Loop through 2D array:
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
System.out.print(grid[row][col] + " ");
}
System.out.println();
}Object-Oriented Programming organizes code around objects - things that have properties (data) and behaviors (methods). Think of real-world objects: a Car has color, speed (properties) and can drive, brake (methods).
- Encapsulation - Protecting data by controlling access
- Inheritance - Child classes inherit from parents
- Polymorphism - Same action, different behavior
- Abstraction - Hiding complex details
public class Person {
// Properties (also called fields)
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method
public void introduce() {
System.out.println("Hi, I'm " + name + " and I'm " + age + " years old.");
}
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String name) {
this.name = name;
}
}Person person = new Person("Alice", 25);
person.introduce(); // "Hi, I'm Alice and I'm 25 years old."
String name = person.getName(); // "Alice"
person.setName("Bob");Control who can access what:
| Modifier | Same Class | Same Package | Subclass | Everywhere |
|---|---|---|---|---|
public |
Yes | Yes | Yes | Yes |
protected |
Yes | Yes | Yes | No |
| default | Yes | Yes | No | No |
private |
Yes | No | No | No |
Protects data from invalid values:
public class BankAccount {
private double balance; // Private - can't access directly
public void deposit(double amount) {
if (amount > 0) {
balance += amount; // Can validate before setting
}
}
public double getBalance() {
return balance;
}
}Provide controlled access to private fields:
public class Student {
private String name;
private int grade;
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String name) {
this.name = name;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
if (grade >= 0 && grade <= 100) {
this.grade = grade;
}
}
}Inheritance lets a class (child) inherit properties and methods from another class (parent). The child gets everything from the parent automatically.
// Parent class
class Animal {
String name;
public void eat() {
System.out.println(name + " is eating");
}
public void sleep() {
System.out.println(name + " is sleeping");
}
}
// Child class
class Dog extends Animal {
String breed;
// Dog inherits eat() and sleep() automatically
public void bark() {
System.out.println("Woof woof!");
}
}
// Using inheritance
Dog dog = new Dog();
dog.name = "Buddy";
dog.eat(); // "Buddy is eating" (inherited)
dog.bark(); // "Woof woof!" (Dog-specific)super refers to the parent class:
class Animal {
String name;
public Animal(String name) {
this.name = name;
}
}
class Dog extends Animal {
String breed;
public Dog(String name, String breed) {
super(name); // Call parent constructor
this.breed = breed;
}
}Child class can change parent method behavior:
class Animal {
public void makeSound() {
System.out.println("Some sound");
}
}
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow!");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Woof!");
}
}Same method call, different behavior based on object type:
Animal animal1 = new Cat();
Animal animal2 = new Dog();
animal1.makeSound(); // "Meow!"
animal2.makeSound(); // "Woof!"This is useful for storing different objects in one collection:
Animal[] animals = new Animal[3];
animals[0] = new Cat();
animals[1] = new Dog();
animals[2] = new Bird();
for (Animal animal : animals) {
animal.makeSound(); // Each makes its own sound
}Marks a method as overriding a parent method. The compiler checks if the method actually exists in the parent:
class Parent {
public void display() { }
}
class Child extends Parent {
@Override
public void display() { } // Compiler verifies this exists in Parent
}An interface is a contract that defines what methods a class must have, but doesn't provide the implementation.
interface Drawable {
void draw(); // Abstract method - no body
default void print() { // Default method (Java 8+)
System.out.println("Printing...");
}
}
class Circle implements Drawable {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
class Square implements Drawable {
@Override
public void draw() {
System.out.println("Drawing a square");
}
}An abstract class is a class that cannot be instantiated. It can have both abstract methods (no body) and regular methods:
abstract class Animal {
String name;
// Regular method
public void eat() {
System.out.println(name + " is eating");
}
// Abstract method - must be implemented by subclasses
public abstract void makeSound();
}
class Dog extends Animal {
public Dog(String name) {
this.name = name;
}
@Override
public void makeSound() {
System.out.println("Woof!");
}
}| Feature | Interface | Abstract Class |
|---|---|---|
| Inheritance | Multiple allowed | Single only |
| Constructor | No | Yes |
| Methods | All abstract (pre-Java 8) | Can have regular methods |
| Variables | Constants only | Can have instance variables |
| Access modifiers | Public by default | Any |
Use interfaces when:
- Unrelated classes need to share behavior
- You want multiple inheritance
- You just need method signatures
Use abstract classes when:
- Classes share a common ancestor
- You want to provide some default behavior
- You need instance variables
Exceptions are errors that occur during program execution. Handling them prevents your program from crashing.
try {
// Code that might cause an error
int result = 10 / 0; // This will throw an exception
} catch (ArithmeticException e) {
// Code to handle the error
System.out.println("Cannot divide by zero!");
System.out.println("Error: " + e.getMessage());
}Handle different types of exceptions:
try {
String str = null;
System.out.println(str.length()); // NullPointerException
int[] arr = new int[5];
System.out.println(arr[10]); // ArrayIndexOutOfBoundsException
int num = Integer.parseInt("abc"); // NumberFormatException
} catch (NullPointerException e) {
System.out.println("Null reference!");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index error!");
} catch (Exception e) {
System.out.println("Something went wrong: " + e.getMessage());
}Code that always executes, whether or not an exception occurs:
try {
System.out.println("Trying...");
} catch (Exception e) {
System.out.println("Error!");
} finally {
System.out.println("This always runs!");
}Common use: closing resources like files or database connections.
Create and throw your own exceptions:
public static void divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero!");
}
System.out.println(a / b);
}| Exception | Cause |
|---|---|
NullPointerException |
Using null object |
ArrayIndexOutOfBoundsException |
Invalid array index |
ArithmeticException |
Math error (division by zero) |
ClassCastException |
Invalid casting |
NumberFormatException |
Invalid number string |
IOException |
Input/Output error |
Collections are data structures that store groups of objects. They provide better functionality than arrays.
Ordered collection that allows duplicates:
import java.util.*;
// ArrayList - most common
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Alice"); // Duplicate allowed
System.out.println(names.get(0)); // Get by index
System.out.println(names.size()); // Number of elements
names.remove("Alice"); // Remove by value
names.remove(0); // Remove by indexCollection that does not allow duplicates:
Set<Integer> numbers = new HashSet<>();
numbers.add(1);
numbers.add(2);
numbers.add(1); // Won't be added (duplicate)
System.out.println(numbers.size()); // 2TreeSet - Sorted order:
Set<String> names = new TreeSet<>();
names.add("Charlie");
names.add("Alice");
names.add("Bob");
// Output in alphabetical order: Alice, Bob, CharlieStores key-value pairs:
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);
ages.put("Charlie", 35);
System.out.println(ages.get("Alice")); // 25
System.out.println(ages.containsKey("Bob")); // true
ages.remove("Bob");List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
// For-each loop
for (String name : names) {
System.out.println(name);
}
// Using iterator
Iterator<String> it = names.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}list.add(item) // Add element
list.remove(item) // Remove element
list.size() // Get size
list.contains(item) // Check if contains
list.isEmpty() // Check if empty
list.clear() // Remove all
map.put(key, value) // Add/update
map.get(key) // Get by key
map.containsKey(key) // Check key
map.remove(key) // RemoveGenerics allow you to create classes, methods, and interfaces that work with any data type while maintaining type safety.
class Box<T> {
private T content;
public void set(T content) {
this.content = content;
}
public T get() {
return content;
}
}
// Usage
Box<String> stringBox = new Box<>();
stringBox.set("Hello");
String str = stringBox.get(); // No casting needed
Box<Integer> intBox = new Box<>();
intBox.set(42);
int num = intBox.get(); // Already an Integerpublic static <T> void printArray(T[] array) {
for (T element : array) {
System.out.println(element);
}
}
// Usage
String[] names = {"Alice", "Bob"};
Integer[] numbers = {1, 2, 3};
printArray(names); // Works with Strings
printArray(numbers); // Works with IntegersRestrict the types that can be used:
// Only allow Number types (Integer, Double, etc.)
public static <T extends Number> double sum(T a, T b) {
return a.doubleValue() + b.doubleValue();
}
// Comparable interface
public static <T extends Comparable<T>> T maximum(T a, T b) {
return (a.compareTo(b) > 0) ? a : b;
}Lambdas are concise way to represent functions. They let you pass behavior as parameters.
// Full form
(parameter) -> { statements }
// Short form for single parameter
parameter -> expression
// No parameters
() -> expression// Runnable (no params, no return)
Runnable r = () -> System.out.println("Hello");
// Consumer (one param, no return)
Consumer<String> printer = s -> System.out.println(s);
// Function (one param, returns value)
Function<String, Integer> length = s -> s.length();
// Predicate (one param, returns boolean)
Predicate<Integer> isEven = n -> n % 2 == 0;| Interface | Method | Use |
|---|---|---|
Predicate<T> |
test(T) | Returns boolean |
Function<T,R> |
apply(T) | Transforms T to R |
Consumer<T> |
accept(T) | Consumes T |
Supplier<T> |
get() | Provides T |
UnaryOperator<T> |
apply(T) | T to T |
Streams process collections in a functional style:
import java.util.stream.*;
// Create stream
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Stream<Integer> stream = numbers.stream();
// Filter - keep matching elements
List<Integer> evens = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
// Result: [2, 4]
// Map - transform each element
List<Integer> doubled = numbers.stream()
.map(n -> n * 2)
.collect(Collectors.toList());
// Result: [2, 4, 6, 8, 10]
// Reduce - combine to single value
int sum = numbers.stream()
.reduce(0, (a, b) -> a + b);
// Result: 15
// Count
long count = numbers.stream().count();
// Find first
Optional<Integer> first = numbers.stream().findFirst();Shorthand for simple lambdas:
// These are equivalent:
list.forEach(s -> System.out.println(s));
list.forEach(System.out::println);
list.stream().map(s -> s.toUpperCase());
list.stream().map(String::toUpperCase);String str = "Hello, World!";
str.length() // 13
str.charAt(0) // 'H'
str.substring(0, 5) // "Hello"
str.indexOf("o") // 4
str.replace("o", "x") // "Hellx, Wxrld!"
str.toUpperCase() // "HELLO, WORLD!"
str.toLowerCase() // "hello, world!"
str.trim() // Removes whitespace
str.split(",") // ["Hello", " World!"]
str.equals("hello") // false (case-sensitive)
str.equalsIgnoreCase("hello") // true
str.contains("World") // true
str.startsWith("Hello") // true
str.endsWith("!") // true
str.isEmpty() // falseMath.abs(-5) // 5 (absolute value)
Math.max(3, 7) // 7
Math.min(3, 7) // 3
Math.sqrt(16) // 4.0
Math.pow(2, 3) // 8.0
Math.floor(3.7) // 3.0
Math.ceil(3.2) // 4.0
Math.round(3.7) // 4
Math.random() // 0.0 to 1.0
Math.PI // 3.14159...
Math.E // 2.71828...int[] arr = {3, 1, 4, 1, 5, 9};
Arrays.sort(arr) // Sort in place
Arrays.toString(arr) // "[1, 3, 4, 5, 9]"
Arrays.fill(arr, 0) // Fill with 0
Arrays.copyOf(arr, 10) // Copy with new length
Arrays.equals(arr1, arr2) // Compare arrays
Arrays.binarySearch(arr, 5) // Search (must be sorted)
Arrays.stream(arr) // Convert to stream- Package declaration
- Import statements
- Class declaration
- Static variables
- Instance variables
- Constructors
- Methods
| Type | Convention | Example |
|---|---|---|
| Class | PascalCase | MyClass, BankAccount |
| Variable | camelCase | firstName, userAge |
| Constant | UPPER_SNAKE | MAX_SIZE, PI |
| Method | camelCase | calculateTotal() |
| Package | lowercase | com.example.myapp |
abstract, assert, boolean, break, byte, case, catch, char, class, const, continue, default, do, double, else, enum, extends, false, final, finally, float, for, goto, if, implements, import, instanceof, int, interface, long, native, new, null, package, private, protected, public, return, short, static, strictfp, super, switch, synchronized, this, throw, throws, transient, true, try, void, volatile, while
- Every statement ends with semicolon
- Curly braces define code blocks
- Arrays use square brackets
- Class names start with capital letter
- File name must match public class name
- Java is case-sensitive
Problem: Using a null reference
String str = null;
str.length(); // NullPointerException!
// Fix: Check for null
if (str != null) {
str.length();
}Problem: Accessing invalid index
int[] arr = {1, 2, 3};
arr[3]; // Index 3 doesn't exist!
// Fix: Always check bounds
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}Problem: Invalid type casting
Object obj = "Hello";
Integer num = (Integer) obj; // ClassCastException!
// Fix: Use instanceof first
if (obj instanceof Integer) {
Integer num = (Integer) obj;
}Problem: Using == instead of equals()
String a = new String("hello");
String b = new String("hello");
a == b // false (different objects)
a.equals(b) // true (same content)
// Fix: Always use .equals() for strings
if (a.equals(b)) { }Problem: Getting unexpected decimal result
int a = 5;
int b = 2;
System.out.println(a / b); // 2, not 2.5!
// Fix: Use double
System.out.println((double) a / b); // 2.5Problem: Fall-through behavior
int num = 1;
switch (num) {
case 1:
System.out.println("One");
case 2:
System.out.println("Two");
default:
System.out.println("Other");
}
// Output: One, Two, Other (no breaks!)
// Fix: Add break statements
switch (num) {
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
default:
System.out.println("Other");
}- Primitive types and their sizes
- Variable declaration and initialization
- Type conversion (implicit and explicit)
- All operators and precedence
- If-else and switch statements
- For loops and while loops
- Method structure and overloading
- Array creation and manipulation
- Class structure and access modifiers
- Encapsulation with getters/setters
- Inheritance with extends
- Method overriding
- Polymorphism
- Interface vs abstract class
- Try-catch exception handling
- List, Set, Map implementations
- Generic classes and methods
- Lambda expressions
- Stream operations
- Practice writing code by hand
- Know the difference between similar concepts (interface vs abstract class)
- Remember that arrays are 0-indexed
- Know which methods modify collections vs which return new ones
- Understand the difference between == and equals()
- Remember operator precedence
- Practice tracing through loops
- Know common exception types and when they occur
Good luck with your studies!