Java Cheat Sheet for OOP and Basic Algorithms
1. String Operations
- Declaration: String str = "Hello";
- Concatenation: str += " World"; or [Link](" World");
- Length: [Link]();
- Character Access: [Link](0);
- Substring: [Link](1, 4);
- Replace: [Link]('a', 'b');
- Split: [Link](" ");
- Contains: [Link]("lo");
- Equals: [Link]("Hello");
- Ignore Case Comparison: [Link]("hello");
- Index Of: [Link]("l");
2. Array Operations
- Declaration: int[] arr = new int[5]; or int[] arr = {1, 2, 3};
- Access Elements: arr[0];
- Array Length: [Link];
- Sort Array: [Link](arr);
- Copy Array: int[] copy = [Link](arr, [Link]);
- Fill Array: [Link](arr, 0);
3. ArrayList Operations
- Declaration: ArrayList<Integer> list = new ArrayList<>();
- Add Element: [Link](5);
- Get Element: [Link](0);
- Remove Element: [Link](0);
- Size: [Link]();
- Contains: [Link](5);
- Sort: [Link](list);
4. Stack Operations
- Declaration: Stack<Integer> stack = new Stack<>();
- Push: [Link](1);
- Pop: [Link]();
- Peek: [Link]();
- Check Empty: [Link]();
5. Queue Operations
- Declaration: Queue<Integer> queue = new LinkedList<>();
- Add (Offer): [Link](1);
- Remove (Poll): [Link]();
- Peek: [Link]();
- Check Empty: [Link]();
6. Basic Algorithms
- For Loop: for (int i = 0; i < n; i++) {}
- While Loop: while (condition) {}
- If-Else: if (condition) {} else {}
- Recursion:
int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
7. Object-Oriented Programming (OOP)
- Class Declaration:
class Person {
String name;
int age;
Person(String name, int age) {
[Link] = name;
[Link] = age;
}
void greet() {
[Link]("Hello, " + name);
}
}
- Inheritance:
class Student extends Person {
int grade;
Student(String name, int age, int grade) {
super(name, age);
[Link] = grade;
}
}
- Interface:
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
[Link]("Bark");
}
}
- Polymorphism:
Animal a = new Dog();
[Link](); // Outputs "Bark"
8. Tracking Table for Functions
Example Function:
int sumDigits(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
Tracking Table for sumDigits(123)
Step | n | sum | n % 10 | n / 10
1 |123 | 0 | 3 | 12
2 | 12 | 3 | 2 | 1
3 | 1| 5 | 1 | 0
4 | 0| 6 | - | -
Result: 6
9. Common Utility Classes
- Math: [Link](a, b); [Link](a, b); [Link](a);
- Random:
Random rand = new Random();
int n = [Link](10); // 0 to 9
- Scanner (Input):
Scanner sc = new Scanner([Link]);
int num = [Link]();
String text = [Link]();