I will be making a list of intermediate to advanced interview questions, then listing their answers here.
- What are Java streams and how would you use them?
- What are lambda functions and when would you use them?
- What’s an example of how to use lambda functions with a stream method?
- What are the different types of exceptions?
- How would you handle an exception?
Here are my answers!
- Java provides a new additional package in Java 8 called java.util.stream which consists of classes, interfaces and enum to allows functional-style operations on the elements. You can use stream by importing java.util.stream package. The best feature about streams is how they focus on declarative programming, not focusing on the coding process as much as the objective. Watch the video at the bottom of this post for an in-depth explanation of how Java 8 streams work.
- Also introduced in Java 8, lambda expressions express instances of functional interfaces (An interface with a single abstract method is called functional interface. An example is java.lang.Runnable). Lambda expressions implement the only abstract function and therefore implement functional interfaces. Lambda expressions are added in Java 8 and provide the following functionalities: able to treat functionality as a method argument, or code as data, functions that can be created without belonging to any class, and a lambda expression can be passed around as if it was an object and executed on demand. Read the code segment at the bottom of this post for an explanation of how Java 8 lambda expressions work.
- [will continue]
- Checked exceptions are checked at compile-time in Java. It means if a method is throwing a checked exception then it should handle the exception using try-catch block or it should declare the exception using throws keyword, otherwise the program will give a compilation error. It is named as checked exception because these exceptions are checked at compile-time. All Unchecked exceptions are direct subclasses of RuntimeException class. Unchecked exceptions are not checked at compile-time. Most of the times these exception occurs due to the bad data provided by user during the user-program interaction. It is up to the programmer to judge the conditions in advance, that can cause such exceptions and handle them appropriately.
- An exception caused by a method can be propagated to the method caller by the “throws” keyword, or can be handled within the method with a try/catch block.