Java - RavikanthEragapati/Interview GitHub Wiki
- java.lang -> String, StringBuilder, StringBuffer (synchronized, slow), Math
- java.io -> File, BufferedInputStream, BufferedReader
- java.math -> BigDeciman, BigInteger, RoundingMode
- java.util -> Collections, ArrayList, HashMap, LinkedList, UUID, TimeZone, Objects
ASCII values:
-
a-z= 97 - 122 -
A-Z= 65 - 90 -
0-9= 48 - 57
var visited = new int[128];
for(int i=0; i<128;i++){
visited[i] = -1;
}
System.out.println("Has char r been visited?" + visited['r']);
System.out.println("ASCII value of char a is: " + (int) Character.valueOf('a'));-
Implicit (Widening) Casting:
AutomaticWhen converting a smaller primitive type to a larger primitive type (e.g., int to long). No data loss. -
Explicit (Narrowing) Casting:
ManualWhen converting a larger primitive type to a smaller type (e.g., double to int). Requires explicit casting syntax (targetType) and can result in data loss.
Order of Size (Narrow to Wide): byte > short > char > int > long > float > double
String Parses static methods:
- Integer.parseInt(String str) -> int;
- Long.parseLong(String str) -> long;
- Double.parseDouble(String str) -> double;
- Float.parseFloat(String str) -> float;
-
Reverse string: Use
StringBuilder.reverse();StringBufferis thread-safe and for that reason its slow. or you can also use pointer from length() to 0.
Useful String methods:
- str.toCharArray() -> char[]
- str.indexOf("m") -> int
- str.indexOf('m', 1) -> int
- str.indexOf('m', 1, 24) -> int
- str.lastIndexOf('m'); -> int
- str.startsWith("abc") -> boolean
- str.endsWith("xyz") -> boolean
- str.charAt(5)
- str.codePointAt(0) - returns ascii value of char at that index a-z = 97 - 122; A-Z = 65 - 90; 0-9 = 48 - 57
- str.toUpperCase(); -> String
- str.toLowerCase(); -> String
- str.length(); -> int
- str.hashcode();
- str.substring(int beginingIndex) -> String
- str.substring(int beginIndex, int endIndex) -> String
- str.concat("xyz") -> String
- str.replace("abc", "xyz") -> String
- str.replaceFirst(String regex, String replacement) -> String
- str.replaceAll(String regex, String replacement) -> String
- str.contains("abc") -> bool
- str.matches(String regex) -> bool
- str.isEmpty() -> bool " " -> false
- str.isBlank() -> " " -> true
- str.split(String regex, int limit) -> String[]
- str.split(String regex) -> String[]
- str.trim() -> removes spaces
- str.strip() -> removes spaces, even the unicode spaces like \u2000 (space)
- Math.random()
- Math.max(a,b)
- Math.min(a,b)
- Math.abs(-1) = 1
- Math.pow(a,b) = a^b
- Math.log()
- Math.log10()
- Math.sqrt(4) = 2
- Math.cbrt(9) = 3
- Math.round(10.45) = 10
- Math.floot(20.6) = 20
- Math.ceil(20.1) = 21
- HashSet & TreeSet (Set Interface)
Set<Character> ch = new HashSet();
ch.add('a');
ch.remove('a');
ch.contains('a');
ch.isEmpty();
ch.size();
Character[] alternative = ch.toArray(new Character[0]);- HashMap & TreeMap (Map Interface)
Map<String,String> aMap = new HashMap<>();
aMap.put("abc", "123");
aMap.get("abc");
aMap.remove("abc");
aMap.containsKey("abc");
aMap.size();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("Key: " + key + ", Value: " + value);
}- ArrayList (List Interface)
List<String> aList = new ArrayList();
aList.add("asf");
aList.get(0);
aList.getFirst();
aList.getLast();
aList.remove("asf");
aList.remove(0);
aList.removeFirst();
aList.removeLast();
aList.size();
aList.sort(null);-
LinkedList / ArrayDeque (Queue & Deque Interfaces)
-
PriorityQueue (Queue Interface)
HINTS TO REMEMBER
- Collections.swap(aList, 0, 0);
- Collections.replaceAll(null, null, null);
- Collections.max(null);
- Collections.min(null);
- Collections.copy(null, null);
- Collections.indexOfSubList(aList, alt);
Sorting:
- Collections.sort(list); — Sorts an ArrayList in natural ascending order.
- Collections.sort(list, Collections.reverseOrder()); — Sorts in descending order.
- Arrays.sort(arr); — Sorts primitive arrays efficiently (O(N \log N)).
Searching:
- Collections.binarySearch(list, key); — Fast lookup on a sorted list (O(\log N)).
Reversing & Shuffling:
- Collections.reverse(list); — Reverses elements in-place.
- Collections.frequency(list, target); — Counts occurrences of an element.
Primitive Wrapper Conversions:
- List list = Arrays.asList(1, 2, 3); (Fixed-size).
- List.of(1, 2, 3); (Java 9+, Immutable).
Read File:
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
String content = Files.readString(Path.of("input.txt"));
// OR
List<String> lines = Files.readAllLines(Path.of("input.txt"));
for (String line : lines) {
// Process each line
}Write File:
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
// Write a full string
Files.writeString(Path.of("output.txt"), "Hello, Interviewer!");
// Write a list of lines
List<String> lines = List.of("Line 1", "Line 2", "Line 3");
Files.write(Path.of("output.txt"), lines);import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class HttpPostExample {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
String jsonPayload = "{\"name\": \"Interviewee\", \"score\": 100}";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://httpbin.org/post"))
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
.build();
HttpResponse<String> response = client.send(
request,
HttpResponse.BodyHandlers.ofString()
);
System.out.println("Status Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
}
}