1. What is Java?
A high-level, object-oriented programming language, e.g., platform-independent via JVM.
2. What is the JVM?
Java Virtual Machine, executes bytecode, e.g., `java MyClass`.
3. What is bytecode?
Intermediate code generated by Java compiler, e.g., stored in `.class` files.
4. What is the JDK?
Java Development Kit, includes compiler and tools, e.g., `javac`.
5. What is the JRE?
Java Runtime Environment, runs Java programs, e.g., includes JVM.
6. How do you compile a Java program?
Use `javac`, e.g., `javac MyClass.java` creates `MyClass.class`.
7. How do you run a Java program?
Use `java`, e.g., `java MyClass` executes the program.
8. What is a Java class?
A blueprint for objects, e.g., `class MyClass { }`.
9. What is the `main` method?
Program entry point, e.g., `public static void main(String[] args) { }`.
10. What is a variable in Java?
A named storage location, e.g., `int x
11. What are primitive data types in Java?
`byte`, `short`, `int`, `long`, `float`, `double`, `char`, `boolean`, e.g., `int x
12. What is the default value of an `int`?
0, e.g., `int x;` initializes to 0.
13. What is the range of a `byte`?
-128 to 127, e.g., `byte b
14. What is a `String` in Java?
An immutable sequence of characters, e.g., `String s
15. How do you declare a constant in Java?
Use `final`, e.g., `final int MAX
16. What is an operator in Java?
Performs operations, e.g., `+` in `x + y`.
17. What is the assignment operator?
`
18. What are arithmetic operators?
`+`, `-`, `*`, `/`, `%`, e.g., `x * y`.
19. What is the modulus operator?
`%`, e.g., `10 % 3` returns 1.
20. What are relational operators?
21. What are logical operators?
`&&`, `||`, `!`, e.g., `x > 0 && y < 10`.
22. What is the ternary operator?
`?:`, e.g., `int max
23. What is a control structure?
Directs program flow, e.g., `if`, `while`.
24. What is an `if` statement?
Conditional execution, e.g., `if (x > 0) { System.out.println(\"Positive\"); }`.
25. What is an `else` clause?
Alternative branch, e.g., `else { System.out.println(\"Non-positive\"); }`.
26. What is a `switch` statement?
Multi-way branch, e.g., `switch (x) { case 1: break; }`.
27. What is a `break` statement?
Exits a loop or switch, e.g., `break;`.
28. What is a `continue` statement?
Skips to next iteration, e.g., `continue;`.
29. What is a `while` loop?
Repeats while condition is true, e.g., `while (x < 5) { x++; }`.
30. What is a `do-while` loop?
Executes at least once, e.g., `do { x++; } while (x < 5)`.
31. What is a `for` loop?
Iterates with counter, e.g., `for (int i
32. What is an enhanced `for` loop?
Iterates over arrays/collections, e.g., `for (int x : arr) { }`.
33. What is a method in Java?
A block of code with a name, e.g., `void myMethod() { }`.
34. What is a return type?
Method’s output type, e.g., `int` in `int add()`.
35. What is a parameter in a method?
Input to a method, e.g., `void print(int x)`.
36. What is method overloading?
Multiple methods with same name, different parameters, e.g., `void print(int x)`, `void print(String s)`.
37. What is the `static` keyword?
Belongs to class, not instance, e.g., `static int count`.
38. What is a `package` in Java?
Groups related classes, e.g., `package com.example`.
39. What is the `import` statement?
Accesses classes from packages, e.g., `import java.util.Scanner`.
40. What is the `Scanner` class?
Reads input, e.g., `Scanner sc
41. How do you read an integer using `Scanner`?
Use `nextInt()`, e.g., `int x
42. How do you read a string using `Scanner`?
Use `nextLine()`, e.g., `String s
43. What is type casting?
Converts one type to another, e.g., `int x
44. What is implicit casting?
Automatic widening, e.g., `double d
45. What is explicit casting?
Manual narrowing, e.g., `int x
46. What is the `Math` class?
Provides mathematical functions, e.g., `Math.sqrt(16)`.
47. How do you generate a random number?
Use `Math.random()`, e.g., `double r
48. What is the `System.out.println()` method?
Prints to console, e.g., `System.out.println(\"Hello\")`.
49. What is a comment in Java?
Non-executable text, e.g., `// Single-line` or `/* Multi-line */`.
50. What is a literal in Java?
A fixed value, e.g., `5`, `\"Hello\"`, `true`.
51. What is the `boolean` data type?
Represents `true` or `false`, e.g., `boolean b
52. What is the `char` data type?
Represents a single character, e.g., `char c
53. What is the `double` data type?
Represents floating-point numbers, e.g., `double d
54. What is the `void` keyword?
Indicates no return value, e.g., `void method()`.
55. What is the `public` access modifier?
Accessible everywhere, e.g., `public int x`.
56. What is the `private` access modifier?
Accessible only within class, e.g., `private int x`.
57. What is the `protected` access modifier?
Accessible within package and subclasses, e.g., `protected int x`.
58. What is the default access modifier?
Package-private, e.g., `int x` (no modifier).
59. What is a constructor in Java?
Initializes objects, e.g., `MyClass() { }`.
60. What is the default constructor?
Parameterless constructor, e.g., `MyClass() { }` (auto-provided if none defined).
61. What is a parameterized constructor?
Constructor with parameters, e.g., `MyClass(int x) { }`.
62. What is the `this` keyword?
Refers to current object, e.g., `this.x
63. What is a local variable?
Declared in a method, e.g., `int x
64. What is an instance variable?
Declared in a class, e.g., `int x` outside methods.
65. What is a class variable?
Declared with `static`, e.g., `static int count`.
66. What is the `new` keyword?
Creates objects, e.g., `MyClass obj
67. What is the `null` keyword?
Represents no reference, e.g., `MyClass obj
68. What is a wrapper class?
Wraps primitive types, e.g., `Integer` for `int`.
69. How do you convert a string to an integer?
Use `Integer.parseInt()`, e.g., `int x
70. What is autoboxing?
Automatic primitive to wrapper conversion, e.g., `Integer x
71. What is unboxing?
Automatic wrapper to primitive conversion, e.g., `int x
72. What is the `equals()` method?
Compares object content, e.g., `s1.equals(s2)` for strings.
73. What is the `
Compares references, e.g., `obj1
74. What is a labeled loop?
Loop with a name, e.g., `outer: for (int i
75. How do you break a labeled loop?
Use `break label`, e.g., `break outer`.
76. What is the `instanceof` operator?
Checks object type, e.g., `obj instanceof MyClass`.
77. What is the `final` keyword?
Prevents modification, e.g., `final int x
78. What is a `static` block?
Initializes static variables, e.g., `static { count
79. What is the `StringBuilder` class?
Mutable string, e.g., `StringBuilder sb
80. How do you append to a `StringBuilder`?
Use `append()`, e.g., `sb.append(\"World\")`.
81. What is the `toString()` method?
Returns string representation, e.g., `obj.toString()`.
82. What is a command-line argument?
Passed to `main()`, e.g., `String[] args` in `main(String[] args)`.
83. How do you access command-line arguments?
Use `args` array, e.g., `String first
84. What is the `System` class?
Provides system utilities, e.g., `System.out`, `System.in`.
85. What is the `Object` class?
Parent of all classes, e.g., defines `toString()`, `equals()`.
86. What is the `hashCode()` method?
Returns object’s hash code, e.g., `obj.hashCode()`.
87. What is a unary operator?
Operates on one operand, e.g., `++x`.
88. What is a binary operator?
Operates on two operands, e.g., `x + y`.
89. What is the increment operator?
`++`, e.g., `x++` increases `x` by 1.
90. What is the decrement operator?
`--`, e.g., `x--` decreases `x` by 1.
91. What is the bitwise AND operator?
`&`, e.g., `x & y` performs AND on bits.
92. What is the bitwise OR operator?
`|`, e.g., `x | y` performs OR on bits.
93. What is the bitwise XOR operator?
`^`, e.g., `x ^ y` performs XOR on bits.
94. What is the bitwise NOT operator?
`~`, e.g., `~x` inverts bits of `x`.
95. What is the left shift operator?
`<<`, e.g., `x << 2` shifts bits left by 2.
96. What is the right shift operator?
`>>`, e.g., `x >> 2` shifts bits right by 2.
97. What is the unsigned right shift operator?
`>>>`, e.g., `x >>> 2` shifts with zero fill.
98. What is the `var` keyword (Java 10+)?
Local variable type inference, e.g., `var x
99. // Object-Oriented Programming: What is OOP in Java?
Programming paradigm using objects, e.g., encapsulation, inheritance.
100. What is a class in Java?
A template for objects, e.g., `class Person { }`.
101. What is an object in Java?
Instance of a class, e.g., `Person p
102. What is encapsulation?
Hiding data with access control, e.g., `private int age; public int getAge()`.
103. What is inheritance?
Class inherits from another, e.g., `class Student extends Person`.
104. What is polymorphism?
Multiple forms, e.g., method overriding, overloading.
105. What is abstraction?
Hiding implementation details, e.g., using `abstract` classes.
106. What is an abstract class?
Cannot be instantiated, e.g., `abstract class Animal { }`.
107. What is an abstract method?
Declared without body, e.g., `abstract void sound()`.
108. What is an interface in Java?
Defines methods for classes, e.g., `interface Movable { void move(); }`.
109. How do you implement an interface?
Use `implements`, e.g., `class Car implements Movable { public void move() { } }`.
110. What is the `extends` keyword?
Inherits a class, e.g., `class Dog extends Animal`.
111. What is the `implements` keyword?
Implements an interface, e.g., `class Car implements Movable`.
112. What is method overriding?
Subclass redefines method, e.g., `@Override void sound() { }`.
113. What is the `@Override` annotation?
Ensures method override, e.g., `@Override void toString()`.
114. What is the `super` keyword?
Refers to superclass, e.g., `super.method()`.
115. How do you call a superclass constructor?
Use `super()`, e.g., `super(name)` in constructor.
116. What is a final class?
Cannot be extended, e.g., `final class MyClass`.
117. What is a final method?
Cannot be overridden, e.g., `final void method()`.
118. What is method hiding?
Static method redefined in subclass, e.g., `static void print()`.
119. What is the `Object` class?
Root of all classes, e.g., defines `toString()`, `equals()`.
120. What is a constructor in OOP?
121. What is constructor overloading?
Multiple constructors with different parameters, e.g., `MyClass()`, `MyClass(int x)`.
122. What is the `this()` constructor call?
Calls another constructor, e.g., `this(x)` in constructor.
123. What is a getter method?
Accesses private field, e.g., `public int getAge() { return age; }`.
124. What is a setter method?
Modifies private field, e.g., `public void setAge(int age) { this.age
125. What is a static method?
Belongs to class, e.g., `static void print()`.
126. What is a static variable?
Shared by all instances, e.g., `static int count`.
127. What is an instance method?
Belongs to object, e.g., `void print()`.
128. What is an instance variable?
Unique to each object, e.g., `int age`.
129. What is the difference between `
130. What is a package-private class?
Default access, e.g., `class MyClass` (no modifier).
131. What is a nested class?
Class within another, e.g., `class Outer { class Inner { } }`.
132. What is an inner class?
Non-static nested class, e.g., `class Inner { }`.
133. What is a static nested class?
Static class within another, e.g., `static class Nested { }`.
134. What is an anonymous class?
Unnamed class, e.g., `new Runnable() { public void run() { } }`.
135. What is a local class?
Class in a method, e.g., `void method() { class Local { } }`.
136. What is the `default` keyword in interfaces (Java 8+)?
Provides method implementation, e.g., `default void method() { }`.
137. What is a functional interface?
Interface with one abstract method, e.g., `interface MyFunc { void run(); }`.
138. What is the `@FunctionalInterface` annotation?
Ensures single abstract method, e.g., `@FunctionalInterface interface MyFunc`.
139. What is a lambda expression (Java 8+)?
Anonymous function, e.g., `() -> System.out.println(\"Hello\")`.
140. How do you use a lambda with a functional interface?
Assign to interface, e.g., `Runnable r
141. What is a method reference (Java 8+)?
Shorthand for lambda, e.g., `System.out::println`.
142. What is single inheritance in Java?
Class extends one superclass, e.g., `class Dog extends Animal`.
143. What is multiple inheritance via interfaces?
Class implements multiple interfaces, e.g., `class Car implements Movable, Drivable`.
144. What is the `instanceof` operator in OOP?
Checks object type, e.g., `obj instanceof Dog`.
145. What is dynamic method dispatch?
Calls overridden method at runtime, e.g., `Animal a
146. What is the `final` keyword in OOP?
Prevents inheritance or overriding, e.g., `final class MyClass`.
147. What is a covariant return type?
Subclass return type in override, e.g., `Dog clone() { return new Dog(); }`.
148. What is an interface default method conflict?
Multiple defaults with same signature, e.g., resolved by overriding.
149. How do you resolve interface default method conflict?
Override or call specific, e.g., `Interface1.super.method()`.
150. What is a sealed class (Java 17+)?
Restricts subclasses, e.g., `sealed class Shape permits Circle`.
151. What is a record class (Java 16+)?
Immutable data class, e.g., `record Point(int x, int y)`.
152. What is a component in a record?
Field of a record, e.g., `x` in `Point`.
153. What is the `toString()` in a record?
Auto-generated, e.g., `Point[x
154. What is a canonical constructor in a record?
Initializes components, e.g., `Point(int x, int y) { this.x
155. What is an enum in Java?
Special class for constants, e.g., `enum Day { MONDAY, TUESDAY }`.
156. How do you access an enum constant?
Use name, e.g., `Day d
157. What is the `values()` method in an enum?
Returns all constants, e.g., `Day[] days
158. What is the `valueOf()` method in an enum?
Returns enum constant, e.g., `Day d
159. What is a constructor in an enum?
Initializes enum constants, e.g., `Day(String desc) { }`.
160. What is a marker interface?
Interface with no methods, e.g., `Serializable`.
161. What is the `Cloneable` interface?
Allows cloning, e.g., `class MyClass implements Cloneable`.
162. How do you clone an object?
Use `clone()`, e.g., `MyClass copy
163. What is the `Serializable` interface?
Enables serialization, e.g., `class MyClass implements Serializable`.
164. What is the `Comparable` interface?
Defines natural ordering, e.g., `class Person implements Comparable`.
165. What is the `compareTo()` method?
Compares objects, e.g., `public int compareTo(Person p)`.
166. What is the `Comparator` interface?
Custom ordering, e.g., `Comparator byAge
167. What is the `compare()` method in `Comparator`?
Compares two objects, e.g., `int compare(Person p1, Person p2)`.
168. What is an aggregation in OOP?
“Has-a” relationship, e.g., `Car` has `Engine`.
169. What is composition in OOP?
Strong “has-a” relationship, e.g., `House` owns `Room`.
170. What is association in OOP?
Relationship between classes, e.g., `Teacher` and `Student`.
171. What is a dependency in OOP?
Class uses another, e.g., `method(ClassB b)`.
172. What is the `hashCode()` method in OOP?
Returns object’s hash, e.g., `int hash
173. What is the `equals()` contract?
`equals()` must be reflexive, symmetric, transitive, consistent.
174. What is the `hashCode()` contract?
Equal objects must have same hash code, e.g., `if a.equals(b), then a.hashCode()
175. What is a shallow copy?
Copies object references, e.g., `clone()` without deep copying fields.
176. What is a deep copy?
Copies object and fields, e.g., custom `clone()` copying nested objects.
177. What is the `protected` keyword in inheritance?
Accessible in package and subclasses, e.g., `protected int x`.
178. What is an immutable class?
Cannot be modified, e.g., `final class MyClass` with `final` fields.
179. How do you create an immutable class?
Use `final` class, `final` fields, no setters, e.g., `final class Point`.
180. What is the `instance` initializer block?
Runs during object creation, e.g., `{ x
181. What is a static initializer block?
Runs during class loading, e.g., `static { count
182. What is the `Class` class?
Represents a class, e.g., `Class> c
183. How do you get a class’s name?
Use `getName()`, e.g., `c.getName()` returns `\"MyClass\"`.
184. What is reflection in Java?
Inspects classes at runtime, e.g., `Class.forName(\"MyClass\")`.
185. What is a private constructor?
Restricts instantiation, e.g., `private MyClass() { }`.
186. What is a singleton class?
Single instance, e.g., `public static MyClass getInstance()`.
187. How do you implement a singleton?
Private constructor, static instance, e.g., `private static MyClass instance
188. What is a factory method?
Creates objects, e.g., `static MyClass create() { return new MyClass(); }`.
189. What is a static import?
Imports static members, e.g., `import static java.lang.Math.PI`.
190. What is a diamond problem?
Ambiguity in multiple inheritance, e.g., resolved by interfaces in Java.
191. What is a superinterface?
Interface extended by another, e.g., `interface B extends A`.
192. What is a tagged interface?
Another term for marker interface, e.g., `Serializable`.
193. What is the `instanceof` pattern matching (Java 16+)?
Combines type check and cast, e.g., `if (obj instanceof String s) { }`.
194. What is the `strictfp` keyword?
Ensures floating-point precision, e.g., `strictfp class MyClass`.
195. What is a varargs parameter?
Variable arguments, e.g., `void method(String... args)`.
196. How do you access varargs?
Treat as array, e.g., `for (String s : args) { }`.
197. What is a type parameter?
Generic type, e.g., `` in `class Box`.
198. What is a generic class?
Uses type parameters, e.g., `class Box { T value; }`.
199. What is a bounded type parameter?
Restricted type, e.g., ``.
200. What is a wildcard in generics?
`?`, e.g., `List> list`.
201. What is an upper-bounded wildcard?
`? extends Type`, e.g., `List extends Number>`.
202. What is a lower-bounded wildcard?
`? super Type`, e.g., `List super Integer>`.
203. What is type erasure?
Removes generic types at runtime, e.g., `List` becomes `List`.
204. What is a raw type?
Generic type without parameters, e.g., `List` instead of `List`.
205. // Arrays and Strings: What is an array in Java?
A fixed-size collection, e.g., `int[] arr
206. How do you declare an array?
Use `[]`, e.g., `int[] arr`.
207. How do you initialize an array?
Use `new` or literals, e.g., `int[] arr
208. How do you access an array element?
Use index, e.g., `arr[0]`.
209. What is the length of an array?
Use `length`, e.g., `int size
210. What is an ArrayIndexOutOfBoundsException?
Thrown for invalid index, e.g., `arr[10]` for `arr[5]`.
211. How do you iterate over an array?
Use for loop, e.g., `for (int i
212. How do you use an enhanced for loop with arrays?
Use `for`, e.g., `for (int x : arr)`.
213. What is a multi-dimensional array?
Array of arrays, e.g., `int[][] matrix
214. How do you declare a 2D array?
Use `[][]`, e.g., `int[][] matrix`.
215. How do you initialize a 2D array?
Use literals, e.g., `int[][] matrix
216. How do you access a 2D array element?
Use indices, e.g., `matrix[0][1]`.
217. What is a jagged array?
Array with varying row lengths, e.g., `int[][] jagged
218. How do you copy an array?
Use `Arrays.copyOf()`, e.g., `int[] copy
219. What is the `Arrays` class?
Provides array utilities, e.g., `Arrays.sort(arr)`.
220. How do you sort an array?
Use `Arrays.sort()`, e.g., `Arrays.sort(arr)`.
221. How do you search an array?
Use `Arrays.binarySearch()`, e.g., `int index
222. How do you fill an array?
Use `Arrays.fill()`, e.g., `Arrays.fill(arr, 0)`.
223. How do you compare arrays?
Use `Arrays.equals()`, e.g., `Arrays.equals(arr1, arr2)`.
224. How do you convert an array to a string?
Use `Arrays.toString()`, e.g., `Arrays.toString(arr)`.
225. What is a `String` in Java?
Immutable sequence of characters, e.g., `String s
226. How do you concatenate strings?
Use `+` or `concat()`, e.g., `s1 + s2`.
227. How do you get the length of a string?
Use `length()`, e.g., `int len
228. How do you access a character in a string?
Use `charAt()`, e.g., `char c
229. How do you compare strings?
Use `equals()`, e.g., `s1.equals(s2)`.
230. How do you compare strings case-insensitively?
Use `equalsIgnoreCase()`, e.g., `s1.equalsIgnoreCase(s2)`.
231. How do you convert a string to uppercase?
Use `toUpperCase()`, e.g., `s.toUpperCase()`.
232. How do you convert a string to lowercase?
Use `toLowerCase()`, e.g., `s.toLowerCase()`.
233. How do you trim a string?
Use `trim()`, e.g., `s.trim()` removes leading/trailing spaces.
234. How do you replace characters in a string?
Use `replace()`, e.g., `s.replace(\'a\', \'b\')`.
235. How do you split a string?
Use `split()`, e.g., `String[] arr
236. How do you get a substring?
Use `substring()`, e.g., `s.substring(0, 3)`.
237. How do you check if a string contains a substring?
Use `contains()`, e.g., `s.contains(\"abc\")`.
238. How do you check if a string starts with a prefix?
Use `startsWith()`, e.g., `s.startsWith(\"He\")`.
239. How do you check if a string ends with a suffix?
Use `endsWith()`, e.g., `s.endsWith(\"lo\")`.
240. How do you find the index of a substring?
Use `indexOf()`, e.g., `s.indexOf(\"abc\")`.
241. How do you find the last index of a substring?
Use `lastIndexOf()`, e.g., `s.lastIndexOf(\"abc\")`.
242. What is the `StringBuilder` class?
243. How do you append to a `StringBuilder`?
Use `append()`, e.g., `sb.append(\"Hello\")`.
244. How do you insert into a `StringBuilder`?
Use `insert()`, e.g., `sb.insert(0, \"Hi\")`.
245. How do you delete from a `StringBuilder`?
Use `delete()`, e.g., `sb.delete(0, 2)`.
246. How do you reverse a `StringBuilder`?
Use `reverse()`, e.g., `sb.reverse()`.
247. How do you convert `StringBuilder` to `String`?
Use `toString()`, e.g., `String s
248. What is the `StringBuffer` class?
Thread-safe mutable string, e.g., `StringBuffer sb
249. What is the difference between `StringBuilder` and `StringBuffer`?
`StringBuilder` is not thread-safe; `StringBuffer` is.
250. How do you convert a string to a character array?
Use `toCharArray()`, e.g., `char[] arr
251. How do you create a string from a character array?
Use `String` constructor, e.g., `String s
252. How do you format a string?
Use `String.format()`, e.g., `String.format(\"Value: %d\", 5)`.
253. How do you check if a string is empty?
Use `isEmpty()`, e.g., `s.isEmpty()`.
254. How do you check if a string is blank (Java 11+)?
Use `isBlank()`, e.g., `s.isBlank()` checks for whitespace.
255. How do you strip whitespace (Java 11+)?
Use `strip()`, e.g., `s.strip()` removes all whitespace.
256. How do you repeat a string (Java 11+)?
Use `repeat()`, e.g., `s.repeat(3)` repeats 3 times.
257. How do you join strings (Java 8+)?
Use `String.join()`, e.g., `String.join(\",\", \"a\", \"b\")`.
258. How do you convert a number to a string?
Use `String.valueOf()`, e.g., `String s
259. How do you convert a string to a number?
260. What is a string pool?
Memory area for string literals, e.g., `\"Hello\"` reused.
261. How do you intern a string?
Use `intern()`, e.g., `s.intern()` adds to string pool.
262. How do you create a string with `new`?
Use `new String()`, e.g., `String s
263. What is the difference between `String` literal and `new String()`?
Literal uses string pool; `new` creates new object.
264. How do you check string equality with `
Compares references, e.g., `s1
265. How do you compare strings lexicographically?
Use `compareTo()`, e.g., `s1.compareTo(s2)`.
266. How do you create an array of strings?
Use `String[]`, e.g., `String[] arr
267. How do you sort an array of strings?
268. How do you copy part of an array?
Use `Arrays.copyOfRange()`, e.g., `int[] sub
269. How do you initialize an array with a default value?
Use `Arrays.fill()`, e.g., `Arrays.fill(arr, -1)`.
270. How do you convert an array to a `List`?
Use `Arrays.asList()`, e.g., `List list
271. How do you convert a `List` to an array?
Use `toArray()`, e.g., `String[] arr
272. How do you check if an array contains a value?
Use `Arrays.stream().anyMatch()`, e.g., `Arrays.stream(arr).anyMatch(x -> x
273. How do you resize an array?
Use `Arrays.copyOf()`, e.g., `arr
274. How do you create a dynamic array?
Use `ArrayList`, e.g., `ArrayList list
275. How do you reverse an array?
Use `Collections.reverse(Arrays.asList(arr))`, e.g., converts to list first.
276. How do you find the maximum in an array?
Use `Arrays.stream().max()`, e.g., `int max
277. How do you find the minimum in an array?
Use `Arrays.stream().min()`, e.g., `int min
278. How do you sum an array?
Use `Arrays.stream().sum()`, e.g., `int sum
279. How do you check if two arrays are equal?
280. How do you create a deep copy of a 2D array?
Manually copy, e.g., `int[][] copy
281. How do you flatten a 2D array?
Use `Arrays.stream().flatMapToInt()`, e.g., `int[] flat
282. How do you check if a string is a palindrome?
Compare with reverse, e.g., `s.equals(new StringBuilder(s).reverse().toString())`.
283. How do you count occurrences in a string?
Use `replace()`, e.g., `(s.length() - s.replace(\"a\", \"\").length())`.
284. How do you remove duplicates from a string?
Use `StringBuilder` and `Set`, e.g., `new LinkedHashSet<>(Arrays.asList(s.split(\"\"))).stream().collect(Collectors.joining())`.
285. How do you reverse a string?
Use `StringBuilder`, e.g., `new StringBuilder(s).reverse().toString()`.
286. How do you convert a string to a `StringBuilder`?
Use constructor, e.g., `StringBuilder sb
287. How do you convert a `StringBuilder` to a character array?
Use `toString().toCharArray()`, e.g., `char[] arr
288. How do you check if two strings are anagrams?
Sort and compare, e.g., `Arrays.equals(s1.toCharArray().sorted(), s2.toCharArray().sorted())`.
289. How do you find the first non-repeated character in a string?
Use `LinkedHashMap`, e.g., count characters, return first with count 1.
290. How do you replace all occurrences in a string?
Use `replaceAll()`, e.g., `s.replaceAll(\"a\", \"b\")`.
291. How do you use regex with `replaceAll()`?
Use pattern, e.g., `s.replaceAll(\"\\\\d\", \"#\")` replaces digits.
292. How do you match a string with a regex?
Use `matches()`, e.g., `s.matches(\"\\\\d+\")` checks for digits.
293. How do you tokenize a string?
Use `StringTokenizer`, e.g., `StringTokenizer st
294. How do you get tokens from `StringTokenizer`?
Use `nextToken()`, e.g., `String token
295. // Collections Framework: What is the Collections Framework?
A set of classes/interfaces for data structures, e.g., `List`, `Set`, `Map`.
296. What is the `Collection` interface?
Root of collection hierarchy, e.g., defines `add()`, `remove()`.
297. What is the `List` interface?
Ordered collection, e.g., `List list
298. What is the `ArrayList` class?
Resizable array, e.g., `ArrayList list
299. How do you add an element to an `ArrayList`?
Use `add()`, e.g., `list.add(\"Hello\")`.
300. How do you remove an element from an `ArrayList`?
Use `remove()`, e.g., `list.remove(0)`.
301. How do you get an element from an `ArrayList`?
Use `get()`, e.g., `String s
302. What is the `LinkedList` class?
Doubly-linked list, e.g., `LinkedList list
303. How do you add an element to a `LinkedList`?
304. What is the `Set` interface?
Unordered collection, no duplicates, e.g., `Set set
305. What is the `HashSet` class?
Unordered set with hashing, e.g., `HashSet set
306. How do you add an element to a `HashSet`?
Use `add()`, e.g., `set.add(\"Hello\")`.
307. What is the `LinkedHashSet` class?
Set with insertion order, e.g., `LinkedHashSet set
308. What is the `TreeSet` class?
Sorted set, e.g., `TreeSet set
309. How do you add an element to a `TreeSet`?
310. What is the `Map` interface?
Key-value pairs, e.g., `Map map
311. What is the `HashMap` class?
Unordered key-value map, e.g., `HashMap map
312. How do you add a key-value pair to a `HashMap`?
Use `put()`, e.g., `map.put(\"key\", 1)`.
313. How do you get a value from a `HashMap`?
Use `get()`, e.g., `int value
314. What is the `LinkedHashMap` class?
Map with insertion order, e.g., `LinkedHashMap map
315. What is the `TreeMap` class?
Sorted key-value map, e.g., `TreeMap map
316. What is the `Iterator` interface?
Traverses collections, e.g., `Iterator it
317. How do you use an `Iterator`?
Use `hasNext()` and `next()`, e.g., `while (it.hasNext()) { String s
318. What is the `ListIterator` interface?
Bidirectional iterator, e.g., `ListIterator it
319. How do you use `ListIterator` to traverse backward?
Use `hasPrevious()` and `previous()`, e.g., `while (it.hasPrevious()) { String s
320. What is the `Collections` class?
Provides utility methods, e.g., `Collections.sort(list)`.
321. How do you sort a `List`?
Use `Collections.sort()`, e.g., `Collections.sort(list)`.
322. How do you reverse a `List`?
Use `Collections.reverse()`, e.g., `Collections.reverse(list)`.
323. How do you shuffle a `List`?
Use `Collections.shuffle()`, e.g., `Collections.shuffle(list)`.
324. What is a synchronized collection?
Thread-safe, e.g., `Collections.synchronizedList(list)`.
325. What is an unmodifiable collection?
Read-only, e.g., `Collections.unmodifiableList(list)`.
326. What is the `Queue` interface?
Ordered collection for processing, e.g., `Queue queue
327. What is the `Deque` interface?
Double-ended queue, e.g., `Deque deque
328. What is the `PriorityQueue` class?
Queue with priority ordering, e.g., `PriorityQueue pq
329. How do you add an element to a `PriorityQueue`?
Use `offer()`, e.g., `pq.offer(5)`.
330. How do you remove an element from a `PriorityQueue`?
Use `poll()`, e.g., `int x
331. What is the `ConcurrentHashMap` class?
Thread-safe map, e.g., `ConcurrentHashMap map
332. What is the `CopyOnWriteArrayList` class?
Thread-safe list, e.g., `CopyOnWriteArrayList list
333. What is the `Vector` class?
Synchronized list, e.g., `Vector vector
334. What is the `Stack` class?
LIFO stack, e.g., `Stack stack
335. How do you push to a `Stack`?
Use `push()`, e.g., `stack.push(\"Hello\")`.
336. How do you pop from a `Stack`?
Use `pop()`, e.g., `String s
337. What is the `Hashtable` class?
Synchronized key-value map, e.g., `Hashtable table
338. What is the difference between `HashMap` and `Hashtable`?
`HashMap` is unsynchronized; `Hashtable` is synchronized.
339. What is a `WeakHashMap`?
Map with weak keys, e.g., `WeakHashMap map
340. What is an `IdentityHashMap`?
Map using reference equality, e.g., `IdentityHashMap map
341. What is the `EnumSet` class?
Set for enums, e.g., `EnumSet set
342. What is the `EnumMap` class?
Map for enum keys, e.g., `EnumMap map
343. What is the `BitSet` class?
Bit array, e.g., `BitSet bs
344. How do you set a bit in `BitSet`?
Use `set()`, e.g., `bs.set(5)`.
345. What is the `NavigableSet` interface?
Sorted set with navigation, e.g., `NavigableSet set
346. What is the `NavigableMap` interface?
Sorted map with navigation, e.g., `NavigableMap map
347. How do you get a subset of a `TreeSet`?
Use `subSet()`, e.g., `set.subSet(\"a\", \"c\")`.
348. How do you get a submap of a `TreeMap`?
Use `subMap()`, e.g., `map.subMap(\"a\", \"c\")`.
349. What is the `forEach()` method in collections?
Applies action to elements, e.g., `list.forEach(System.out::println)`.
350. What is the `stream()` method in collections?
Creates a stream, e.g., `list.stream().filter(x -> x > 0)`.
351. What is the `parallelStream()` method?
Creates parallel stream, e.g., `list.parallelStream()`.
352. How do you convert a collection to an array?
353. How do you convert an array to a `List`?
354. How do you check if a collection is empty?
Use `isEmpty()`, e.g., `list.isEmpty()`.
355. How do you clear a collection?
Use `clear()`, e.g., `list.clear()`.
356. How do you get the size of a collection?
Use `size()`, e.g., `int size
357. What is the `Comparable` interface in collections?
Defines natural order, e.g., `class Person implements Comparable`.
358. What is the `Comparator` interface in collections?
Custom ordering, e.g., `Comparator.comparing(Person::getAge)`.
359. How do you sort a `List` with a `Comparator`?
Use `sort()`, e.g., `list.sort(Comparator.comparing(String::length))`.
360. What is the `Spliterator` interface?
Divides collection for parallel processing, e.g., `Spliterator sp
361. What is a `ConcurrentLinkedQueue`?
Thread-safe queue, e.g., `ConcurrentLinkedQueue queue
362. What is a `BlockingQueue`?
Queue with blocking operations, e.g., `BlockingQueue queue
363. What is a `LinkedBlockingQueue`?
Thread-safe queue with capacity, e.g., `LinkedBlockingQueue queue
364. What is a `PriorityBlockingQueue`?
Thread-safe priority queue, e.g., `PriorityBlockingQueue pq
365. What is a `SynchronousQueue`?
Queue with no capacity, e.g., `SynchronousQueue queue
366. What is a `DelayQueue`?
Queue with delayed elements, e.g., `DelayQueue queue
367. What is the `Collections.emptyList()` method?
Returns immutable empty list, e.g., `List empty
368. What is the `Collections.singletonList()` method?
Returns immutable single-element list, e.g., `List single
369. What is the `Collections.nCopies()` method?
Returns immutable list with copies, e.g., `List copies
370. What is the `Map.Entry` interface?
Represents key-value pair, e.g., `for (Map.Entry e : map.entrySet())`.
371. How do you iterate over a `Map`?
Use `entrySet()`, e.g., `for (Map.Entry e : map.entrySet())`.
372. How do you iterate over `Map` keys?
Use `keySet()`, e.g., `for (String key : map.keySet())`.
373. How do you iterate over `Map` values?
Use `values()`, e.g., `for (Integer value : map.values())`.
374. What is the `compute()` method in `Map`?
Updates value, e.g., `map.compute(\"key\", (k, v) -> v
375. What is the `merge()` method in `Map`?
Merges values, e.g., `map.merge(\"key\", 1, Integer::sum)`.
376. What is the `putIfAbsent()` method in `Map`?
Adds if key absent, e.g., `map.putIfAbsent(\"key\", 0)`.
377. What is the `getOrDefault()` method in `Map`?
Returns default if key absent, e.g., `map.getOrDefault(\"key\", 0)`.
378. What is the `replace()` method in `Map`?
Replaces value, e.g., `map.replace(\"key\", 2)`.
379. What is the `remove()` method in `Map`?
Removes key-value pair, e.g., `map.remove(\"key\")`.
380. What is a `ConcurrentSkipListSet`?
Thread-safe sorted set, e.g., `ConcurrentSkipListSet set
381. What is a `ConcurrentSkipListMap`?
Thread-safe sorted map, e.g., `ConcurrentSkipListMap map
382. What is the `Arrays.asList()` method?
Converts array to list, e.g., `List list
383. What is the `Collections.checkedList()` method?
Type-safe list, e.g., `List checked
384. What is the `Collections.disjoint()` method?
Checks no common elements, e.g., `Collections.disjoint(list1, list2)`.
385. What is the `Collections.frequency()` method?
Counts occurrences, e.g., `Collections.frequency(list, \"a\")`.
386. What is the `Collections.max()` method?
Finds maximum, e.g., `String max
387. What is the `Collections.min()` method?
Finds minimum, e.g., `String min
388. What is the `Collections.swap()` method?
Swaps elements, e.g., `Collections.swap(list, 0, 1)`.
389. What is the `Collections.copy()` method?
Copies list, e.g., `Collections.copy(dest, src)`.
390. What is a `ConcurrentLinkedDeque`?
Thread-safe double-ended queue, e.g., `ConcurrentLinkedDeque deque
391. What is a `LinkedBlockingDeque`?
Thread-safe double-ended queue, e.g., `LinkedBlockingDeque deque
392. What is the `Collections.rotate()` method?
Rotates list, e.g., `Collections.rotate(list, 1)`.
393. What is the `Collections.replaceAll()` method?
Replaces elements, e.g., `Collections.replaceAll(list, \"a\", \"b\")`.
394. What is the `Collections.indexOfSubList()` method?
Finds sublist index, e.g., `Collections.indexOfSubList(list, subList)`.
395. What is the `Collections.lastIndexOfSubList()` method?
Finds last sublist index, e.g., `Collections.lastIndexOfSubList(list, subList)`.
396. // Exception Handling: What is an exception in Java?
Disrupts program flow, e.g., `ArithmeticException` for division by zero.
397. What is exception handling?
Managing exceptions, e.g., `try-catch` blocks.
398. What is the `try` block?
Contains risky code, e.g., `try { int x
399. What is the `catch` block?
Handles exception, e.g., `catch (ArithmeticException e) { }`.
400. What is the `finally` block?
Always executes, e.g., `finally { System.out.println(\"Cleanup\"); }`.
401. What is the `throw` keyword?
Throws exception, e.g., `throw new IOException(\"Error\")`.
402. What is the `throws` keyword?
Declares exceptions, e.g., `void method() throws IOException`.
403. What is a checked exception?
Compile-time exception, e.g., `IOException`.
404. What is an unchecked exception?
Runtime exception, e.g., `NullPointerException`.
405. What is the `Throwable` class?
Parent of `Exception` and `Error`, e.g., `Throwable t
406. What is the `Exception` class?
Parent of exceptions, e.g., `IOException`, `RuntimeException`.
407. What is the `Error` class?
Serious errors, e.g., `OutOfMemoryError`.
408. What is a `RuntimeException`?
Unchecked exception, e.g., `ArithmeticException`.
409. How do you handle multiple exceptions?
Use multiple `catch`, e.g., `catch (IOException e) { } catch (SQLException e) { }`.
410. What is multi-catch (Java 7+)?
Single `catch` for multiple, e.g., `catch (IOException | SQLException e)`.
411. What is try-with-resources (Java 7+)?
Auto-closes resources, e.g., `try (FileReader fr
412. What interface is required for try-with-resources?
`AutoCloseable`, e.g., `FileReader` implements `AutoCloseable`.
413. How do you create a custom exception?
Extend `Exception`, e.g., `class MyException extends Exception { }`.
414. How do you throw a custom exception?
Use `throw`, e.g., `throw new MyException(\"Error\")`.
415. How do you handle a custom exception?
Use `catch`, e.g., `catch (MyException e) { }`.
416. What is the `getMessage()` method?
Returns exception message, e.g., `e.getMessage()`.
417. What is the `printStackTrace()` method?
Prints stack trace, e.g., `e.printStackTrace()`.
418. What is exception propagation?
Exception moves up call stack, e.g., unhandled in method.
419. What is a stack trace?
Call stack report, e.g., shows method calls.
420. What is the `ArithmeticException`?
Thrown for arithmetic errors, e.g., `1 / 0`.
421. What is the `NullPointerException`?
Thrown for null access, e.g., `String s
422. What is the `ArrayIndexOutOfBoundsException`?
423. What is the `ClassCastException`?
Thrown for invalid cast, e.g., `Object o
424. What is the `IllegalArgumentException`?
Thrown for invalid argument, e.g., `throw new IllegalArgumentException()`.
425. What is the `NumberFormatException`?
Thrown for invalid number format, e.g., `Integer.parseInt(\"abc\")`.
426. What is the `IOException`?
Thrown for I/O errors, e.g., `new FileReader(\"missing.txt\")`.
427. What is the `FileNotFoundException`?
Thrown for missing file, e.g., `new FileReader(\"missing.txt\")`.
428. What is the `NoSuchElementException`?
Thrown for missing element, e.g., `Iterator` with no next.
429. What is the `ConcurrentModificationException`?
Thrown for concurrent modification, e.g., modifying list during iteration.
430. What is the `UnsupportedOperationException`?
Thrown for unsupported operation, e.g., modifying unmodifiable list.
431. What is the `OutOfMemoryError`?
Thrown for insufficient memory, e.g., large array allocation.
432. What is the `StackOverflowError`?
Thrown for excessive recursion, e.g., `void recurse() { recurse(); }`.
433. How do you catch all exceptions?
Use `catch (Exception e)`, e.g., `try { } catch (Exception e) { }`.
434. How do you rethrow an exception?
Use `throw`, e.g., `catch (IOException e) { throw e; }`.
435. What is exception chaining?
Wrapping exceptions, e.g., `throw new IOException(\"Error\", e)`.
436. How do you get the cause of an exception?
Use `getCause()`, e.g., `e.getCause()`.
437. How do you initialize an exception with a cause?
Use constructor, e.g., `new IOException(\"Error\", cause)`.
438. What is the `addSuppressed()` method?
Adds suppressed exception, e.g., `e.addSuppressed(new IOException())`.
439. How do you access suppressed exceptions?
Use `getSuppressed()`, e.g., `e.getSuppressed()`.
440. Can a `try` block exist without `catch`?
Yes, with `finally`, e.g., `try { } finally { }`.
441. Can a `finally` block throw an exception?
Yes, e.g., `finally { throw new RuntimeException(); }`.
442. What happens if `catch` and `finally` both throw exceptions?
`finally`’s exception suppresses `catch`’s, e.g., use `addSuppressed()`.
443. How do you declare multiple exceptions in a method?
Use `throws`, e.g., `void method() throws IOException, SQLException`.
444. What is the `InterruptedException`?
Thrown for thread interruption, e.g., `Thread.sleep(1000)`.
445. How do you handle `InterruptedException`?
Catch or propagate, e.g., `catch (InterruptedException e) { Thread.currentThread().interrupt(); }`.
446. How do you avoid `NullPointerException`?
Check for null, e.g., `if (obj !
447. How do you avoid `ArrayIndexOutOfBoundsException`?
Check index, e.g., `if (i < arr.length)`.
448. How do you avoid `ClassCastException`?
Use `instanceof`, e.g., `if (obj instanceof String)`.
449. How do you avoid `NumberFormatException`?
Validate input, e.g., `try { Integer.parseInt(s); } catch (NumberFormatException e) { }`.
450. What is the `IllegalStateException`?
Thrown for invalid state, e.g., `throw new IllegalStateException(\"Invalid\")`.
451. What is the `SecurityException`?
Thrown for security violation, e.g., restricted operation.
452. What is the `CloneNotSupportedException`?
Thrown for cloning without `Cloneable`, e.g., `obj.clone()`.
453. What is the `NoClassDefFoundError`?
Thrown for missing class at runtime, e.g., missing dependency.
454. What is the `ClassNotFoundException`?
Thrown for missing class, e.g., `Class.forName(\"Missing\")`.
455. What is the `AssertionError`?
Thrown for failed assertion, e.g., `assert false`.
456. How do you enable assertions?
Use `-ea` flag, e.g., `java -ea MyClass`.
457. What is the `getStackTrace()` method?
Returns stack trace, e.g., `e.getStackTrace()`.
Share this protal to share friends and complete unlimited tests here. You can also make friends on our protal also start mutual competition tests with your firends easily.