Java_Cheat_Sheet
Java_Cheat_Sheet
1. String Operations
- Declaration: String str = "Hello";
- Concatenation: str += " World"; or str.concat(" World");
- Length: str.length();
- Character Access: str.charAt(0);
- Substring: str.substring(1, 4);
- Replace: str.replace('a', 'b');
- Split: str.split(" ");
- Contains: str.contains("lo");
- Equals: str.equals("Hello");
- Ignore Case Comparison: str.equalsIgnoreCase("hello");
- Index Of: str.indexOf("l");
2. Array Operations
- Declaration: int[] arr = new int[5]; or int[] arr = {1, 2, 3};
- Access Elements: arr[0];
- Array Length: arr.length;
- Sort Array: Arrays.sort(arr);
- Copy Array: int[] copy = Arrays.copyOf(arr, arr.length);
- Fill Array: Arrays.fill(arr, 0);
3. ArrayList Operations
- Declaration: ArrayList<Integer> list = new ArrayList<>();
- Add Element: list.add(5);
- Get Element: list.get(0);
- Remove Element: list.remove(0);
- Size: list.size();
- Contains: list.contains(5);
- Sort: Collections.sort(list);
4. Stack Operations
- Declaration: Stack<Integer> stack = new Stack<>();
- Push: stack.push(1);
- Pop: stack.pop();
- Peek: stack.peek();
- Check Empty: stack.isEmpty();
5. Queue Operations
- Declaration: Queue<Integer> queue = new LinkedList<>();
- Add (Offer): queue.offer(1);
- Remove (Poll): queue.poll();
- Peek: queue.peek();
- Check Empty: queue.isEmpty();
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);
}
void greet() {
System.out.println("Hello, " + name);
}
}
- Inheritance:
class Student extends Person {
int grade;
Student(String name, int age, int grade) {
super(name, age);
this.grade = grade;
}
}
- Interface:
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
System.out.println("Bark");
}
}
- Polymorphism:
Animal a = new Dog();
a.sound(); // Outputs "Bark"
Result: 6
- Scanner (Input):
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
String text = sc.nextLine();