☕ Java for SDETs — Deep-Dive
Cheatsheet (with examples)
1) Language Basics
1.1 Primitives & literals
● Primitives: byte, short, int, long, float, double, char, boolean.
Literals:
int i = 1_000; // underscores for readability
long L = 10_000L; // L suffix
float f = 3.14f; // f suffix
double d = 3.14;
char c = 'A';
boolean ok = true;
1.2 Reference types & String
● Reference types live on heap; String is immutable.
Common String methods:
String s = "SDET";
s.length(); // 4
s.charAt(1); // 'D'
s.substring(1, 3); // "DE"
s.toUpperCase(); // "SDET"
s.equalsIgnoreCase("sdet");
s.contains("SD");
s.indexOf("DE"); // 1
" trim ".trim(); // "trim"
String.join(",", "a","b"); // "a,b"
● Gotcha: use equals() for content equality, not ==.
1.3 Operators & precedence
● Arithmetic + - * / %, relational, logical && || !, ternary cond ? a : b.
● Short-circuit &&, || stop evaluating when result is known.
1.4 Control flow
if (x > 0) { ... }
else if (x == 0) { ... }
else { ... }
switch (day) {
case 1: case 2: break;
default:
}
Java 14+ has switch expressions (optional):
int len = switch (s) {
case "a", "b" -> 1;
default -> s.length();
};
1.5 Methods & parameters
static int add(int a, int b) { return a + b; }
static int addAll(int... nums) { // varargs
int sum = 0; for (int n : nums) sum += n; return sum;
}
● Java is pass-by-value. For references, the reference value is copied; you can mutate
the object but not rebind caller’s reference.
2) Classes, Objects & OOP
2.1 Constructors, this, initializer blocks
class User {
private final String name;
private int age;
{ /* instance init block */ age = 18; }
User(String name) { this.name = name; }
User(String name, int age) { this(name); this.age = age; }
}
2.2 Encapsulation
class Account {
private int balance;
public synchronized void deposit(int amt) { balance += amt; }
public synchronized int getBalance() { return balance; }
}
2.3 Inheritance, super, overriding
class Animal { void speak(){ System.out.println("..."); } }
class Dog extends Animal {
@Override void speak(){ System.out.println("Bark"); }
}
● Dynamic dispatch: method called based on runtime type.
2.4 final, abstract, interface
abstract class Shape { abstract double area(); }
interface Drawable { void draw(); default void clear(){ } static int
dpi(){ return 96; } }
● Java 8+: default and static methods in interfaces.
Functional Interface (one abstract method) → usable with lambdas:
@FunctionalInterface interface Op { int apply(int a, int b); }
Op add = (a,b) -> a + b;
2.5 Nested types
● Static nested (no outer instance), inner (has implicit outer ref), local, anonymous.
Useful for listeners, small helpers.
3) Generics (type safety)
Parameterized types:
List<String> names = new ArrayList<>();
Generic methods:
static <T> T first(List<T> list) { return list.isEmpty()? null :
list.get(0); }
● Wildcards:
○ ? extends T (producer) — you can read as T, not safely add.
○ ? super T (consumer) — you can add T, reading yields Object.
● PECS rule: Producer Extends, Consumer Super.
4) Collections Framework (with core methods)
4.1 Interfaces & common implementations
● List (ordered, duplicates): ArrayList, LinkedList
● Set (unique): HashSet, LinkedHashSet (keeps insertion order), TreeSet (sorted)
● Map (key→value): HashMap, LinkedHashMap, TreeMap
● Queue/Deque: ArrayDeque, PriorityQueue
4.2 Common methods you’ll use a lot
List<String> list = new ArrayList<>();
list.add("a"); list.add(0, "z");
list.get(1); list.set(1, "b");
list.remove("z"); // or remove(index)
list.contains("a"); list.size(); list.isEmpty();
list.forEach(System.out::println);
Set<Integer> set = new HashSet<>();
set.add(1); set.add(1); // ignored
set.contains(1); set.remove(1);
Map<String,Integer> map = new HashMap<>();
map.put("p1", 100);
map.putIfAbsent("p1", 200); // won’t overwrite
map.get("p1"); map.getOrDefault("p2", 0);
map.containsKey("p1"); map.keySet(); map.values(); map.entrySet();
map.compute("p1", (k,v) -> v==null?1:v+1);
map.merge("p2", 1, Integer::sum);
4.3 Iteration patterns (and when)
// for-each
for (String s : list) { ... }
// Iterator (safe remove)
for (Iterator<String> it = list.iterator(); it.hasNext();) {
String s = it.next();
if (s.isEmpty()) it.remove();
}
// ListIterator (bidirectional)
ListIterator<String> li = list.listIterator(list.size());
while (li.hasPrevious()) System.out.println(li.previous());
4.4 Sorting
Collections.sort(list); // natural order (Comparable)
list.sort(Comparator.comparingInt(String::length).reversed());
● Implement Comparable<T> for natural order; use Comparator for custom orders.
4.5 Performance cheats
● ArrayList random access O(1), middle insert O(n).
● LinkedList middle insert O(1) if you have the node; traversal O(n).
● HashMap average O(1) get/put; TreeMap O(log n) sorted.
5) Streams & Lambdas (Java 8+)
5.1 Common operations
List<String> names = List.of("alice","bob","alex");
// map / filter / collect
List<String> aNames =
names.stream()
.filter(n -> n.startsWith("a"))
.map(String::toUpperCase)
.sorted()
.toList(); // Java 16+ (else collect(Collectors.toList()))
// reduce
int sum = List.of(1,2,3).stream().reduce(0, Integer::sum);
// grouping
Map<Integer, List<String>> byLen =
names.stream().collect(Collectors.groupingBy(String::length));
5.2 Optional (avoid null checks)
Optional<String> maybe = names.stream().findFirst();
String val = maybe.orElse("default");
maybe.ifPresent(System.out::println);
6) Exception Handling
6.1 Checked vs Unchecked
● Checked: must handle/declare (IOException, SQLException).
● Unchecked: runtime (NullPointerException, IllegalArgumentException).
6.2 Patterns
try {
// risky
} catch (IOException e) {
// handle
} finally {
// always
}
// try-with-resources (auto-close)
try (BufferedReader br = Files.newBufferedReader(Path.of("in.txt"))) {
System.out.println(br.readLine());
}
6.3 Custom exceptions
class BusinessException extends RuntimeException {
BusinessException(String msg) { super(msg); }
}
Guidelines: Fail fast, include context in messages, don’t swallow exceptions, prefer unchecked
for programming errors.
7) File I/O (classic & NIO.2)
7.1 java.nio.file (preferred)
Path p = Path.of("data/users.csv");
List<String> lines = Files.readAllLines(p);
Files.writeString(Path.of("out.txt"), "Hello\n",
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
// walk a directory
try (var paths = Files.walk(Path.of("logs"))) {
paths.filter(Files::isRegularFile)
.forEach(System.out::println);
}
7.2 java.io basics
try (BufferedReader br = new BufferedReader(new FileReader("in.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt",
true))) {
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
}
8) JDBC (Database)
8.1 Steps
1. Get a Connection
2. Use PreparedStatement (avoid SQL injection)
3. Execute & map ResultSet
4. Close resources (try-with-resources)
5. Transactions (commit/rollback)
8.2 Example (MySQL)
import java.sql.*;
import java.util.*;
record User(int id, String name) {}
class UserDAO {
private final String url = "jdbc:mysql://localhost:3306/testdb";
private final String user = "root";
private final String pass = "password";
List<User> findAll() {
String sql = "SELECT id, name FROM users";
List<User> result = new ArrayList<>();
try (Connection con = DriverManager.getConnection(url, user,
pass);
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
result.add(new User(rs.getInt(1), rs.getString(2)));
}
} catch (SQLException e) { throw new RuntimeException(e); }
return result;
}
void save(String name) {
String sql = "INSERT INTO users(name) VALUES (?)";
try (Connection con = DriverManager.getConnection(url, user,
pass);
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setString(1, name);
ps.executeUpdate();
} catch (SQLException e) { throw new RuntimeException(e); }
}
}
8.3 Transactions
try (Connection con = DriverManager.getConnection(url, user, pass)) {
con.setAutoCommit(false);
try (PreparedStatement a = con.prepareStatement("UPDATE acc SET
bal=bal-? WHERE id=?");
PreparedStatement b = con.prepareStatement("UPDATE acc SET
bal=bal+? WHERE id=?")) {
// withdraw
a.setInt(1, 100); a.setInt(2, 1); a.executeUpdate();
// deposit
b.setInt(1, 100); b.setInt(2, 2); b.executeUpdate();
con.commit();
} catch (SQLException e) {
con.rollback();
throw e;
}
}
9) Concurrency (SDET-level essentials)
9.1 Threads & executors
ExecutorService pool = Executors.newFixedThreadPool(4);
Future<Integer> f = pool.submit(() -> 42);
System.out.println(f.get()); // waits
pool.shutdown();
9.2 Synchronization basics
class Counter {
private int value;
synchronized void inc() { value++; }
synchronized int get() { return value; }
}
● Prefer concurrent collections (ConcurrentHashMap, BlockingQueue) and
high-level executors.
10) Testing Essentials for SDETs
10.1 JUnit 5
import org.junit.jupiter.api.*;
class CalcTest {
@Test void add_works() {
Assertions.assertEquals(5, 2+3);
}
@ParameterizedTest
@ValueSource(strings = {"", " ", "\n"})
void blank(String s) {
Assertions.assertTrue(s.trim().isEmpty());
}
}
10.2 Selenium (very brief)
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
WebElement btn = driver.findElement(By.id("submit"));
btn.click();
driver.quit();
● Apply POM: one page = one class; expose actions, not locators.
P1. Reverse words in a sentence (keep word order
reversed, not chars)
Input: "I love Java" → Output: "Java love I"
Logic-only
static String reverseWords(String s) {
// split manually
List<String> words = new ArrayList<>();
StringBuilder cur = new StringBuilder();
for (int i=0;i<s.length();i++) {
char ch = s.charAt(i);
if (ch==' ') {
if (cur.length()>0) { words.add(cur.toString());
cur.setLength(0); }
} else cur.append(ch);
if (cur.length()>0) words.add(cur.toString());
// reverse
StringBuilder out = new StringBuilder();
for (int i=words.size()-1;i>=0;i--) {
out.append(words.get(i));
if (i>0) out.append(' ');
return out.toString();
}
P2. Count vowels, consonants, digits, spaces
Logic-only
static int[] counts(String s) {
int v=0,c=0,d=0,sp=0;
for (int i=0;i<s.length();i++) {
char ch = Character.toLowerCase(s.charAt(i));
if ("aeiou".indexOf(ch)>=0) v++;
else if (ch>='a' && ch<='z') c++;
else if (ch>='0' && ch<='9') d++;
else if (ch==' ') sp++;
return new int[]{v,c,d,sp};
P3. Remove duplicate characters but keep order
Logic-only
static String dedupeKeepOrder(String s) {
boolean[] seen = new boolean[256];
StringBuilder sb = new StringBuilder();
for (int i=0;i<s.length();i++) {
char ch = s.charAt(i);
if (!seen[ch]) { seen[ch] = true; sb.append(ch); }
return sb.toString();
P4. Longest substring without repeating characters
(sliding window)
Logic-only
static int longestUnique(String s) {
int[] last = new int[256]; Arrays.fill(last, -1);
int best=0, start=0;
for (int i=0;i<s.length();i++) {
int ch = s.charAt(i);
if (last[ch] >= start) start = last[ch] + 1;
last[ch] = i;
best = Math.max(best, i - start + 1);
return best;
P5. Move all zeros to the end (stable)
Logic-only (in-place, O(1) space)
static void moveZeros(int[] a) {
int write = 0;
for (int read=0; read<a.length; read++) {
if (a[read] != 0) a[write++] = a[read];
while (write < a.length) a[write++] = 0;
P6. Binary search (sorted array)
Logic-only
static int binarySearch(int[] a, int target) {
int lo=0, hi=a.length-1;
while (lo<=hi) {
int mid = lo + (hi-lo)/2;
if (a[mid]==target) return mid;
if (a[mid] < target) lo = mid + 1; else hi = mid - 1;
return -1;
P7. Merge two sorted arrays (into new sorted array)
Logic-only (two pointers)
static int[] mergeSorted(int[] a, int[] b) {
int[] out = new int[a.length + b.length];
int i=0,j=0,k=0;
while (i<a.length && j<b.length)
out[k++] = (a[i] <= b[j]) ? a[i++] : b[j++];
while (i<a.length) out[k++] = a[i++];
while (j<b.length) out[k++] = b[j++];
return out;
P8. Maximum subarray sum (Kadane’s)
Logic-only
static int maxSubArray(int[] a) {
int best = a[0], cur = a[0];
for (int i=1;i<a.length;i++) {
cur = Math.max(a[i], cur + a[i]);
best = Math.max(best, cur);
return best;
}
P9. Sort a Map by value (descending)
Logic-only
static List<Map.Entry<String,Integer>>
sortByValueDesc(Map<String,Integer> m) {
List<Map.Entry<String,Integer>> list = new
ArrayList<>(m.entrySet());
for (int i=0;i<list.size();i++) {
for (int j=i+1;j<list.size();j++) {
if (list.get(j).getValue() > list.get(i).getValue()) {
Collections.swap(list, i, j);
return list;
P10. Validate balanced brackets ()[]{} with stack
Logic-only
static boolean balanced(String s) {
char[] st = new char[s.length()]; int top=-1;
for (char ch: s.toCharArray()) {
if (ch=='('||ch=='['||ch=='{') st[++top]=ch;
else {
if (top<0) return false;
char open = st[top--];
if
(!((open=='('&&ch==')')||(open=='['&&ch==']')||(open=='{'&&ch=='}')))
return false;
return top==-1;
1. Reverse a String
Solution 1 – Without built-in methods (manual logic):
public class ReverseString {
public static void main(String[] args) {
String str = "hello";
String rev = "";
for (int i = str.length() - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
System.out.println("Reversed String: " + rev);
}
Solution 2 – Using built-in methods:
public class ReverseStringOptimal {
public static void main(String[] args) {
String str = "hello";
String rev = new StringBuilder(str).reverse().toString();
System.out.println("Reversed String: " + rev);
👉 StringBuilder.reverse() is highly optimized compared to manual
looping.
2. Check if String is Palindrome
Solution 1 – Manual logic:
public class PalindromeCheck {
public static void main(String[] args) {
String str = "madam";
String rev = "";
for (int i = str.length() - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
}
if (str.equals(rev)) {
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
Solution 2 – Optimal using built-in:
public class PalindromeCheckOptimal {
public static void main(String[] args) {
String str = "madam";
boolean isPalindrome = new
StringBuilder(str).reverse().toString().equals(str);
System.out.println(isPalindrome ? "Palindrome" : "Not
Palindrome");
3. Factorial of a Number
Solution 1 – Without recursion, manual logic:
public class Factorial {
public static void main(String[] args) {
int num = 5;
int fact = 1;
for (int i = 1; i <= num; i++) {
fact = fact * i;
System.out.println("Factorial: " + fact);
Solution 2 – Using recursion (optimal in interviews):
public class FactorialOptimal {
static int factorial(int n) {
if (n == 0 || n == 1) return 1;
return n * factorial(n - 1);
public static void main(String[] args) {
int num = 5;
System.out.println("Factorial: " + factorial(num));
}
4. Fibonacci Series
Solution 1 – Iterative logic:
public class Fibonacci {
public static void main(String[] args) {
int n = 10;
int a = 0, b = 1, c;
System.out.print(a + " " + b);
for (int i = 2; i < n; i++) {
c = a + b;
System.out.print(" " + c);
a = b;
b = c;
Solution 2 – Recursive (shorter but less optimal):
public class FibonacciOptimal {
static int fib(int n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
public static void main(String[] args) {
int n = 10;
for (int i = 0; i < n; i++) {
System.out.print(fib(i) + " ");
5. Prime Number Check
Solution 1 – Manual logic:
public class PrimeCheck {
public static void main(String[] args) {
int num = 29;
boolean isPrime = true;
if (num <= 1) isPrime = false;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
System.out.println(isPrime ? "Prime" : "Not Prime");
Solution 2 – Optimal (check till √n):
public class PrimeCheckOptimal {
public static void main(String[] args) {
int num = 29;
boolean isPrime = num > 1;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
System.out.println(isPrime ? "Prime" : "Not Prime");
6. Find Largest Element in Array
Solution 1 – Manual logic:
public class LargestElement {
public static void main(String[] args) {
int[] arr = {10, 45, 32, 67, 23};
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
System.out.println("Largest Element: " + max);
}
Solution 2 – Optimal (using built-in):
import java.util.Arrays;
public class LargestElementOptimal {
public static void main(String[] args) {
int[] arr = {10, 45, 32, 67, 23};
int max = Arrays.stream(arr).max().getAsInt();
System.out.println("Largest Element: " + max);
7. Count Vowels in a String
Solution 1 – Manual logic:
public class CountVowels {
public static void main(String[] args) {
String str = "interview";
int count = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch
== 'u') {
count++;
System.out.println("Vowels: " + count);
Solution 2 – Using regex (optimal):
public class CountVowelsOptimal {
public static void main(String[] args) {
String str = "interview";
int count = str.replaceAll("[^aeiou]", "").length();
System.out.println("Vowels: " + count);
8. Find the factorial of a number
// 1. Logic-only (loop)
class FactorialLogic {
public static void main(String[] args) {
int n = 5;
int fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
System.out.println("Factorial: " + fact);
// 2. Optimal (recursion)
class FactorialOptimal {
static int factorial(int n) {
if (n == 0 || n == 1) return 1;
return n * factorial(n - 1);
public static void main(String[] args) {
System.out.println("Factorial: " + factorial(5));
}
}
9. Check if a number is Prime
// 1. Logic-only
class PrimeLogic {
public static void main(String[] args) {
int n = 29;
boolean isPrime = true;
if (n <= 1) isPrime = false;
else {
for (int i = 2; i <= n/2; i++) {
if (n % i == 0) {
isPrime = false;
break;
System.out.println(n + " is prime? " + isPrime);
}
// 2. Optimal (√n check)
class PrimeOptimal {
static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
return true;
public static void main(String[] args) {
System.out.println(isPrime(29));
10. Fibonacci series
// 1. Logic-only (loop)
class FibonacciLogic {
public static void main(String[] args) {
int n = 10;
int a = 0, b = 1;
System.out.print("Fibonacci: " + a + " " + b);
for (int i = 2; i < n; i++) {
int c = a + b;
System.out.print(" " + c);
a = b;
b = c;
// 2. Optimal (recursion)
class FibonacciOptimal {
static int fib(int n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.print(fib(i) + " ");
}
}
11. Check Armstrong number
// 1. Logic-only
class ArmstrongLogic {
public static void main(String[] args) {
int n = 153, temp = n, sum = 0, digits = 0;
int t = n;
while (t > 0) {
digits++;
t /= 10;
while (temp > 0) {
int d = temp % 10;
int power = 1;
for (int i = 0; i < digits; i++) power *= d;
sum += power;
temp /= 10;
}
System.out.println(n + " is Armstrong? " + (sum == n));
// 2. Optimal (Math.pow)
class ArmstrongOptimal {
public static void main(String[] args) {
int n = 153, temp = n, sum = 0, digits =
String.valueOf(n).length();
while (temp > 0) {
int d = temp % 10;
sum += Math.pow(d, digits);
temp /= 10;
System.out.println(n + " is Armstrong? " + (sum == n));
}
12. Find GCD of two numbers
// 1. Logic-only
class GCDLogic {
public static void main(String[] args) {
int a = 56, b = 98, gcd = 1;
for (int i = 1; i <= a && i <= b; i++) {
if (a % i == 0 && b % i == 0) gcd = i;
System.out.println("GCD: " + gcd);
// 2. Optimal (Euclidean algo)
class GCDOptimal {
static int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
public static void main(String[] args) {
System.out.println("GCD: " + gcd(56, 98));
}
13. Find LCM of two numbers
// 1. Logic-only
class LCMLogic {
public static void main(String[] args) {
int a = 15, b = 20, lcm;
lcm = (a > b) ? a : b;
while (true) {
if (lcm % a == 0 && lcm % b == 0) {
System.out.println("LCM: " + lcm);
break;
lcm++;
// 2. Optimal (relation with GCD)
class LCMOptimal {
static int gcd(int a, int b) {
return (b == 0) ? a : gcd(b, a % b);
static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
public static void main(String[] args) {
System.out.println("LCM: " + lcm(15, 20));
14. Find largest of three numbers
// 1. Logic-only
class LargestLogic {
public static void main(String[] args) {
int a = 10, b = 25, c = 15;
int largest = a;
if (b > largest) largest = b;
if (c > largest) largest = c;
System.out.println("Largest: " + largest);
// 2. Optimal (Math.max)
class LargestOptimal {
public static void main(String[] args) {
int a = 10, b = 25, c = 15;
int largest = Math.max(a, Math.max(b, c));
System.out.println("Largest: " + largest);
15. Check palindrome number
// 1. Logic-only
class PalindromeLogic {
public static void main(String[] args) {
int n = 121, temp = n, rev = 0;
while (temp > 0) {
int d = temp % 10;
rev = rev * 10 + d;
temp /= 10;
System.out.println(n + " is palindrome? " + (rev == n));
// 2. Optimal (String reverse)
class PalindromeOptimal {
public static void main(String[] args) {
String s = "121";
String rev = new StringBuilder(s).reverse().toString();
System.out.println(s + " is palindrome? " + s.equals(rev));
16. Count vowels and consonants
// 1. Logic-only
class VowelLogic {
public static void main(String[] args) {
String s = "Hello World";
int vowels = 0, consonants = 0;
for (int i = 0; i < s.length(); i++) {
char ch = Character.toLowerCase(s.charAt(i));
if (ch >= 'a' && ch <= 'z') {
if (ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
vowels++;
else consonants++;
System.out.println("Vowels: " + vowels + ", Consonants: " +
consonants);
// 2. Optimal (regex)
class VowelOptimal {
public static void main(String[] args) {
String s = "Hello World".toLowerCase();
long vowels = s.chars().filter(ch -> "aeiou".indexOf(ch) !=
-1).count();
long consonants = s.chars().filter(ch ->
Character.isLetter(ch) && "aeiou".indexOf(ch) == -1).count();
System.out.println("Vowels: " + vowels + ", Consonants: " +
consonants);
17. Find missing number in array (1–n)
// 1. Logic-only
class MissingNumberLogic {
public static void main(String[] args) {
int arr[] = {1,2,3,5};
int n = 5;
int sum = n*(n+1)/2, actualSum = 0;
for (int i = 0; i < arr.length; i++) {
actualSum += arr[i];
System.out.println("Missing number: " + (sum - actualSum));
}
// 2. Optimal (Streams)
import java.util.Arrays;
class MissingNumberOptimal {
public static void main(String[] args) {
int arr[] = {1,2,3,5};
int n = 5;
int sum = n*(n+1)/2;
int actualSum = Arrays.stream(arr).sum();
System.out.println("Missing number: " + (sum - actualSum));
18. Find duplicate elements in array
// 1. Logic-only
class DuplicateLogic {
public static void main(String[] args) {
int arr[] = {1,2,3,2,4,5,1};
for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if (arr[i] == arr[j]) {
System.out.println("Duplicate: " + arr[i]);
// 2. Optimal (Set)
import java.util.*;
class DuplicateOptimal {
public static void main(String[] args) {
int arr[] = {1,2,3,2,4,5,1};
Set<Integer> seen = new HashSet<>();
Set<Integer> dupes = new HashSet<>();
for (int num : arr) {
if (!seen.add(num)) dupes.add(num);
System.out.println("Duplicates: " + dupes);
}
19. Find common elements in two arrays
// 1. Logic-only
class CommonElementsLogic {
public static void main(String[] args) {
int arr1[] = {1,2,3,4};
int arr2[] = {3,4,5,6};
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
System.out.println("Common: " + arr1[i]);
// 2. Optimal (Set retainAll)
import java.util.*;
class CommonElementsOptimal {
public static void main(String[] args) {
Integer arr1[] = {1,2,3,4};
Integer arr2[] = {3,4,5,6};
Set<Integer> set1 = new HashSet<>(Arrays.asList(arr1));
Set<Integer> set2 = new HashSet<>(Arrays.asList(arr2));
set1.retainAll(set2);
System.out.println("Common: " + set1);
20. Find second largest number in array
// 1. Logic-only
class SecondLargestLogic {
public static void main(String[] args) {
int arr[] = {10, 20, 4, 45, 99};
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int num : arr) {
if (num > first) {
second = first;
first = num;
} else if (num > second && num != first) {
second = num;
System.out.println("Second Largest: " + second);
// 2. Optimal (Streams)
import java.util.*;
class SecondLargestOptimal {
public static void main(String[] args) {
int arr[] = {10, 20, 4, 45, 99};
int second = Arrays.stream(arr).distinct()
.boxed()
.sorted((a,b) -> b - a)
.skip(1)
.findFirst()
.get();
System.out.println("Second Largest: " + second);