└── README.md /README.md: -------------------------------------------------------------------------------- 1 | # Java Interview Questions 2 | 3 | This is a Collection of Computer Science, Java and SQL questions I use for the interviews. 4 | Feel free to propose new questions, contributions are open to everyone. 5 | 6 | * [General Questions](#general-questions) 7 | * [OOP Questions](#oop-questions) 8 | * [Algorithms and Data Structures / Collections / Generics](#algorithms-and-data-structures--collections--generics) 9 | * [Streams And Lambdas](#streams-and-lambdas) 10 | * [Threads](#threads--async) 11 | * [Creational, Structural and Behavioral Design Patterns](#creational-structural-and-behavioral-design-patterns) 12 | * [Java EE](#java-ee) 13 | * [Spring](#spring) 14 | * [Microservices](#microservices) 15 | * [Generic WEB](#generic-web) 16 | * [SQL](#sql) 17 | * [Exercises](#exercises) 18 | 19 | ## General Questions 20 | 21 | * What are the key memory segments inside JVM ? Explain **HEAP**, **STACK**. 22 | * What is a **Memory Leak** ? How can a memory leak appear in **garbage collected** language ? Is it even possible ? 23 | * Is Java *pass-by-value* or *pass-by-reference* ? 24 | * Write a Java method to swap the values of two integer values (*Is it possible ?*): 25 | ```Java 26 | public void swap(int x, int y) { /** code here **/ } 27 | ``` 28 | * What is the output of the following code: 29 | ```java 30 | public class PasserBy { 31 | public static void swap(int x, int y) { 32 | int tmp = x; 33 | x = y; 34 | y = tmp; 35 | } 36 | public static void main(String[] args) { 37 | int i = 1, j = 2; 38 | swap(i, j); 39 | System.out.println(i + " " + j); 40 | } 41 | } 42 | ``` 43 | * What is a *primitive type* in Java ? What are the main *primitive types* ? 44 | * What is *auto-boxing/unboxing* ? 45 | * What is *implicit casting* ? 46 | * What is *explicit casting* ? 47 | * When developing an e-commerce site, what is the recommended type to use for the *price* if performance is not an issue. What if performance is an issue ? 48 | * Explain the usage of the following keyword: `final`. 49 | * Can you give example of a `final` class from the Java Standard library ? 50 | * What is the difference between `==` and `equals()` ? 51 | * What is the output if we execute the following code: 52 | ```Java 53 | public class Ternary { 54 | public static void main(String[] args) { 55 | 56 | Integer x = 1987; 57 | Integer y = 1987; 58 | System.out.println(x == y ? "A" : "B"); 59 | 60 | x = 10; 61 | y = 10; 62 | System.out.println(x == y ? "A" : "B"); 63 | } 64 | } 65 | ``` 66 | * Explain the usage of the following keywords: `strictfp`, `native`. 67 | 68 | ## OOP Questions 69 | 70 | * What is a **constructor** ? 71 | * What is the **default constructor** ? 72 | * Explain the concept of *Inheritance*. Why doesn't Java supports the concept of *Multiple Inheritance* ? 73 | * What is **Polymorphism** ? 74 | * What is **Overloading** ? What is **Overriding** ? 75 | * What is the output if we execute the following code: 76 | ```Java 77 | public abstract class Engineer { 78 | public static String name() { 79 | return "Engineer"; 80 | } 81 | public String favorite() { 82 | return "Math and Physics"; 83 | } 84 | public static void main(String[] args) { 85 | Engineer e2 = new ElectricalEngineer(); 86 | Engineer e3 = new SoftwareEngineer(); 87 | System.out.format("%s %s \n", e2.name(), e2.favorite()); 88 | System.out.format("%s %s", e3.name(), e3.favorite()); 89 | } 90 | } 91 | class ElectricalEngineer extends Engineer { 92 | public static String name() { return "Electrical Engineer" } 93 | public String favorite() { return "Electricity"; } 94 | } 95 | class SoftwareEngineer extends Engineer { 96 | public static String name() { return "Software Engineer"; } 97 | public String favorite() { return "Java"; } 98 | } 99 | ``` 100 | * Can a `static` method be overwritten ? 101 | * Explain the concept of *Encapsulation*. 102 | * How would you encapsulate the following class: 103 | ```Java 104 | public class Circle { 105 | double radius; 106 | double area; 107 | } 108 | ``` 109 | * What is *immutability* ? 110 | * How can we write an **Immutable** class ? 111 | * Explain of the concept of **Marker Interface**. 112 | * Explain the concept of **Serialization**. 113 | * Explain how the keyword **transient** works. What fields would you mark as transient in a class ? 114 | * Explain the concept behind the **Cloneable** interface and how does it work. 115 | * What is the output if we execute the following code: 116 | ```Java 117 | public class Constructors { 118 | public static void main(String[] args) { 119 | new Dog(); 120 | } 121 | } 122 | class Animal { 123 | public Animal() { System.out.println("1"); } 124 | public Animal(String s) { 125 | this(); 126 | System.out.println("2"); 127 | } 128 | } 129 | class Dog extends Animal { 130 | public Dog() { 131 | super("3"); 132 | System.out.println("4"); 133 | } 134 | } 135 | ``` 136 | * What is a *Java Interface* ? 137 | * Does an interface `extends` or `implements` another interface ? 138 | * What is a *Java Abstract Class* ? 139 | * Does a *Java Abstract Class* `extends` or `implements` another *Java Abstract Class* ? 140 | * Explain the usage of the `default` keyword (Java 8 onwards). 141 | * With the introduction of the `default` keyword are there any reasons to use *Abstract Classes* instead of *Interfaces* ? 142 | * **Unchecked Exceptions** vs. **Checked Exceptions**. 143 | * What are the differences between **Exceptions** and an **Errors** ? Is there any similitude between the two ? 144 | * Name 3 **Unchecked Exceptions**. 145 | * Name 3 **Checked Exceptions**. 146 | * What are **Java Annotations** ? 147 | * What are the **SOLID** principles and how do they apply to Java ? Explain: 148 | * **S**ingle-Responsibility; 149 | * **O**pen-Closed 150 | * **L**iskov Substitution 151 | * **I**nterface Segregation 152 | * **D**ependency Inversion 153 | 154 | ## Algorithms and Data Structures / Collections / Generics 155 | 156 | * Explain the **O(n) Notation** (Big O). 157 | * How does a **Stack** data-structure works ? Are there any standard Java Stack implementations ? 158 | * How does a **Queue** data-structure works ? Are there any standard Java Queue implementations ? 159 | * How does a **Binary Tree** data-structure works ? 160 | * How can you recursively calculate the sum of numbers from a `List` (don't use for/do/while loops). 161 | * What is tail recursion ? 162 | * Why is not possible to use primitives as generic types ? 163 | * Explain the concept of **Type Erasure**. 164 | * Explain the following data structures: *List*, *Map*, *Queue*, *Set*. 165 | * Name a few implementations for each interface: 166 | 167 | | List | Set | Map | Queue | 168 | | ------ | ------ | ------ | ------ | 169 | | | | | | 170 | | | | | | 171 | | | | | | 172 | | | | | | 173 | 174 | * The following code highlights the difference between various **Map** implementations. What is the output if we run it (`impossible to say`: 175 | ```java 176 | public class Maps { 177 | public static void main(String[] args) { 178 | Map map1, map2, map3; 179 | 180 | map1 = Map.of( 181 | "A", 0, 182 | "D", 1, 183 | "B", 2, 184 | "C", 3 185 | ); 186 | 187 | map2 = new LinkedHashMap<>(map1); 188 | map3 = new TreeMap<>(map1); 189 | 190 | System.out.println(map2); 191 | System.out.println(map3); 192 | } 193 | } 194 | ``` 195 | * Explain how a **HashMap** is implemented. What is the relationship between *equals()* and *hashCode()*. 196 | * Given the following code what is the Output (`3`): 197 | ```java 198 | public class Sets { 199 | public static void main(String[] args) { 200 | Set set = new HashSet<>(); 201 | CustomData customData = new CustomData(); 202 | 203 | set.add(customData); 204 | set.add(customData); 205 | set.add(new CustomData()); 206 | set.add(new CustomData()); 207 | 208 | System.out.println(set.size()); 209 | } 210 | } 211 | class CustomData { 212 | @Override 213 | public int hashCode() { 214 | return 0; 215 | } 216 | } 217 | ``` 218 | * What are *hash collisions* ? 219 | * What are the operations for which a **LinkedList** is more efficient than an **ArrayList** ? 220 | * What is the difference between **CopyOnWriteArrayList**, **Vector** and **ArrayList** ? 221 | * What are the key differences between a **HashMap** and **ConcurrentHashMap** ? 222 | * How does a **WeakHashMap** works ? What are the main differences between a **WeakHashMap** and a **HashMap** ? 223 | * Does a **Set** accepts `null` as an element ? 224 | * What is the difference between an `Iterator` and `ListIterator` ? 225 | * Are there any **Immutable** Collection Classes ? 226 | * What is a **RingBuffer** ? 227 | * What is a **SkipList** ? 228 | * What happens if we run the following code: 229 | ```java 230 | class Test { 231 | public static void main(String[] args) { 232 | List list = new LinkedList<>(); 233 | 234 | list.add("A"); 235 | list.add("C"); 236 | list.add("D"); 237 | 238 | Iterator it = list.iterator(); 239 | 240 | System.out.println(it.next()); 241 | 242 | list.add(1, "B"); 243 | 244 | System.out.println(it.next()); 245 | System.out.println(it.next()); 246 | System.out.println(it.next()); 247 | } 248 | } 249 | ``` 250 | 251 | ### Streams and Lambdas 252 | 253 | * What is a **Functional Interface** ? 254 | * What happens if we try to run the following code: 255 | ```java 256 | public class Lambada { 257 | 258 | private String name = "Agent Smith"; 259 | 260 | public void doLambda() { 261 | Doer doer = () -> { 262 | System.out.println(this.name); 263 | }; 264 | doer.doAction(); 265 | } 266 | 267 | public void doAnonymous() { 268 | Doer doer = new Doer() { 269 | @Override 270 | public void doAction() { 271 | System.out.println(this.name); 272 | } 273 | }; 274 | doer.doAction(); 275 | } 276 | 277 | public static void main(String[] args) { 278 | Lambada lambada = new Lambada(); 279 | lambada.doLambda(); 280 | lambada.doAnonymous(); 281 | } 282 | } 283 | 284 | @FunctionalInterface 285 | interface Doer { 286 | void doAction(); 287 | } 288 | ``` 289 | * Can you please explain what is a **Predicate**, **Consumer**, **Function**, **Supplier** ? 290 | * What is the difference between a **Stream** and an **Iterator** ? 291 | * Using the `filter()` method write a method that returns only the positive numbers from a `List`. 292 | * What is a `parallelStream()` ? How is it different from a standard `stream()` ? 293 | * Find out the max element from a `List` using the `reduce()` method. 294 | * Find out the sum of elements from a `List` using the `reduce()` method. 295 | * What is the output if we run the following code: 296 | ```java 297 | class Test { 298 | public static void main(String[] args) { 299 | final List l = new LinkedList<>(); 300 | 301 | l.add("A"); 302 | l.add("B"); 303 | l.add("C"); 304 | 305 | l.stream().forEach(e -> { 306 | l.add("Z"); 307 | System.out.println(e); 308 | }); 309 | } 310 | } 311 | ``` 312 | 313 | ### Threads & Async 314 | 315 | * What is a Thread ? 316 | * Is the `++` operator thread-safe ? 317 | * How can we implement a Thread ? 318 | * How *synchronized* keyword works ? 319 | * How is the method `thread.join()` working ? 320 | * Explain the concept of **Thread Starvation** ? 321 | * Explain the concept of **Thread Pool** ? 322 | * What can you tell about the **Executor Interface** ? 323 | * What is a *Semaphore* in Java ? 324 | * Explain the concept of *Future* and *CompletableFuture*. What is the main difference between a *Future* and a *CompletableFuture* ? 325 | * What is the output if we execute the following code: 326 | ```java 327 | class Test { 328 | public static void main(String[] args) throws ExecutionException, InterruptedException { 329 | CompletableFuture cf1 = CompletableFuture.runAsync(() -> { 330 | System.out.println("B"); 331 | }); 332 | CompletableFuture cf2 = CompletableFuture.runAsync(() -> { 333 | System.out.println("A"); 334 | }); 335 | cf1.get(); 336 | cf2.get(); 337 | } 338 | } 339 | ``` 340 | 341 | ### Creational, Structural and Behavioral Design Patterns 342 | 343 | * What is a **Design Pattern** ? 344 | * What is a **Creational Design Pattern** ? 345 | * Pick two or three **Creational Design Patterns** from the following list and describe how you've used them in your code: *Abstract Factory*, *Builder*, *Factory Method*, *Prototype*, *Singleton* ? 346 | * What is a **Structural Design Pattern** ? 347 | * Pick two or three **Structural Design Patterns** from the following list and describe how you've used them in your code: *Adapter*, *Decorator*, *Facade*, *Flyweight*, *Proxy*? 348 | * What is a **Behavioral Design Pattern** ? 349 | * Pick two or three **Behavioral Design Patterns** from the following list and describe how you've used them in your code: *Chain Of Responsability*, *Command*, *Iterator*, *Mediator*, *Memento*, *Observer*, *Visitor* 350 | 351 | ### Spring 352 | 353 | * Explain the concept of *Inversion of Control*. What is the **Spring IoC Container** ? 354 | * Explain the concept of *Dependency Injection* (in Spring). 355 | * Do you know any other libraries that provide *Dependency Injection* features ? 356 | * What are the main advantages and disadvantages for *setter dependency injection* vs *constructor dependency injection* ? 357 | * What is a **Spring Bean** ? 358 | * What are the main **Spring Bean Scopes** ? Explain `singleton`, `prototype`, `request`, `session`, `global session`. 359 | * What are the **Spring Stereotyping Annotations** ? Explain the differences between: `@Component`, `@Controller`, `@Repository`, `@Service`. 360 | * Explain how the following Spring Annotations are working: `@Autowired`, `@Qualifier`, `@Required`. 361 | * Explain how the `@Async` annotations functions. 362 | * Explain the concept of **Spring Profiles**. 363 | * What is **Spring Boot** ? Give example of a Scenario where you would propose to use **Spring Boot** ? 364 | * What is **Spring Data** ? Give example of a Scenario where you would propose to use **Spring Data** ? 365 | * What is **Spring Integration** ? Give example of a Scenario where you would propose to use **Spring Integration** ? 366 | * What is **Spring Batch** ? Give example of a Scenario where you would propose to use **Spring Batch** ? 367 | * What is **Spring Security** ? Give example of a Scenario where you would propose to use **Spring Security** ? 368 | 369 | ### Microservices 370 | 371 | * What are the advantages and disadvantages of using a Microservice based architecture ? 372 | > **Advantages**: Improved Scalability, Fault Isolation, Localised Complexity, Increased Agility, Simplified Debugging and Maintenance, Smaller Development Teams, etc. 373 | > 374 | > **Disadvantages**: Complexity (e.g.: Dependencies), Requires accurate pre-planning, End-to-end testing is difficult, Complex deployment procedures, etc. 375 | * What is an API Gateway ? What "problem" does it solve ? 376 | * What is a Circuit Breaker ? What "problem" does it solve ? How is the `@HystrixCommand` annotations works in a Spring Cloud implementation? 377 | * Explain the concept of **Observability** ? 378 | * What is the **Log Aggregation** pattern ? What problem does it solve ? Can you give examples of **Log Aggregation** solutions (e.g.: AWS Cloud Watch) ? 379 | * What is the **Application Metrics** pattern ? What problem does it solve ? What are the two models of aggregating metrics (push. vs pull) ? Can you give examples of **Application Metrics** solutions ? 380 | * What is the **Distributed Tracing** pattern ? 381 | * You have applied the **Database per Service** pattern, so each microservice has its own database. Some business transactions are spanning over multiple services, so you need a mechanism to implement transaction that Span Services. How to implement transaction that span services ? (e.g.: **Saga Pattern**) 382 | * You have applied the **Database per Service** pattern, so each microservice has its own database. Additionally, you have implemented the **Event Sourcing** Pattern and data is no longer easily queryable. How to implement a query that retrieves data from multiple services in a micorservice architecture ? (e.g.: Command Query Responsibility Segregation - CQRS). 383 | 384 | ### Generic WEB 385 | 386 | * What is **JWT** ? How does **JWT** works ? 387 | * Where is recommended to store **JWT** tokens received from the Server on the client-side ? 388 | * What are the main HTTP verbs ? 389 | * What is the difference between **POST** and **PUT** ? 390 | * What is the difference between **POST** and **PATCH** ? 391 | * What is the difference between **POST** and **GET** ? 392 | * You have to develop a *REST API* for a book store. This API needs to implement CRUD-like operations. How would you design the API ? 393 | 394 | | Operation | HTTP VERB | ENDPOINT | 395 | | --------- | --------- | -------- | 396 | | Add a book | | | 397 | | Remove a book | | | 398 | | List books with pagination | | | 399 | | Edit a book | | | 400 | | Get info for a book | | | 401 | 402 | ### SQL 403 | * What is **ACID** standing for ? Explain: 404 | * **A**tomicity 405 | * **C**onsistency 406 | * **I**solation 407 | * **D**urability 408 | 409 | *Given the following SQL table `employees`:* 410 | 411 | | id | full_name | mng_id | 412 | | -- | --------- | ------ | 413 | | 100 | Patrick Read | 101 | 414 | | 101 | Bradley Hayes | `null` | 415 | | 102 | Kieran Bennett | 101 | 416 | | 103 | George Barnes | 101 | 417 | | 104 | Alex Griffiths | 102 | 418 | | 105 | Issac Jacobs | 102 | 419 | | 106 | Will Mack | 104 | 420 | 421 | *Write an SQL query that returns the following result:* 422 | 423 | | id | full_name | mng_full_name | 424 | | -- | --------- | ------------- | 425 | | 100 | Patrick Read | Bradley Hayes | 426 | | ... | ............ | ............. | 427 | 428 | *Write an SQL query that returns one row containing the manager with the most direct subalterns.* 429 | 430 | ### Generic Questions 431 | * From a protocol perspective what is the difference between **UDP** and **TCP** ? 432 | * What library would use to write a Scheduler in Java ? 433 | * What are the main **Maven** alternatives ? 434 | * What are the main **JUnit** alternatives ? 435 | * How is **Mockito** used ? Are there any other alternatives to **Mockito** 436 | * What is **Continuous Integration** (CI) ? 437 | * Name other **JVM**-based languages ? 438 | * What is **Functional Programming** ? Can you give a few examples of Functional Programming languages ? 439 | * What is a **DSL** ? Can you write a **DSL** in Java ? 440 | * What Quality Control tools do you know ? What is a Quality Gate ? 441 | 442 | ### Exercises 443 | 444 | #### Find the longest substring(s) that doesn't contains any letter duplicates from a string 445 | 446 | Input examples: `"abcsadjnii"` 447 | 448 | #### The solitary integer (Simple) 449 | 450 | Given a list of integers `LIST = [1,4,3,3,2,5,1,2,5,7,7, ...]` with size `N`. 451 | 452 | We know `LIST` contains only duplicated numbers (numbers that appear twice) except ONE integer which is called *The Solitary Integer*. 453 | 454 | Write an efficient algorithm that will determine this integer ? 455 | 456 | Can you solve the exercise in O(N) ? 457 | 458 | #### Pangrams (Simple) 459 | 460 | Roy wanted to increase his typing speed for programming contests. So, his friend advised him to type the sentence "The quick brown fox jumps over the lazy dog" repeatedly, because it is a pangram. (Pangrams are sentences constructed by using every letter of the alphabet at least once.) 461 | After typing the sentence several times, Roy became bored with it. So he started to look for other pangrams. 462 | Given a sentence s, tell Roy if it is a pangram or not. 463 | 464 | **Input Format** 465 | Input consists o a string s. 466 | Example: 467 | ``` 468 | We promptly judged antique ivory buckles for the next prize 469 | ``` 470 | 471 | **Output Format** 472 | Output a line containing “pangram” if s is pangram, otherwise print “not pangram”. 473 | Example: 474 | ``` 475 | pangram 476 | ``` 477 | 478 | #### Balanced Parentheses (Medium) 479 | 480 | Given a sequence consisting of parentheses, determine whether the expression is balanced. 481 | A sequence of parentheses is balanced if every open parentheses can be paired uniquely with a closed parentheses that occurs after the former. Also, the interval between them must be balanced. You will be given three types of parentheses: (, {, and [. 482 | 483 | 484 | ``` 485 | {[()]} - This is a balanced parentheses. 486 | {[(])} - This is not a balanced parentheses. 487 | ``` 488 | 489 | Example: 490 | 491 | **Input** 492 | ``` 493 | 3 494 | {[()]} 495 | {[(])} 496 | {{[[(())]]}} 497 | ``` 498 | 499 | **Ouput** 500 | ``` 501 | YES 502 | NO 503 | YES 504 | ``` 505 | 506 | --------------------------------------------------------------------------------