Showing posts with label interview questions. Show all posts
Showing posts with label interview questions. Show all posts

Saturday, June 14, 2014

Java 8 : Frequently Asked Questions for Interviews - 5


What are Functional Interfaces

A functional interface is an interface with a single abstract method. That abstract method is used as the type of a lambda expression.
public interface ActionListner extends EventListener {
      public void actionPerformed( ActionEvent event);
}
In the above example ActionListener has only one method actionPerformed and we use it to represent the action that takes one argument and returns no result. => It is a functional Interfaces.
  • It doesn't matter what the single method ( e.g. actionPerformed ) is called. 
  • The method will match up to lambda expression as long as it has compatible method signature
  • One can see the type of the parameter in the functional interface => improves readability and understanding in code.
  • Functional interfaces can use generics also.
  • Some important functional interfaces in Java :
Interface NameArgumentsReturnsExample
Predicate<T>sasdadasTdfasdfasdfafsadfsbooleanasfsdfsdadfsdHas this book been published yet?aasdfsdfasdfasdfasdfasdfasdfasfsdfsfsdfsdadfsd
Consumer<T>TvoidPrinting out a value. Getting an action/task done.
Function<T,R>TRGet a property/instance var from an object. Eg: get the author from book object
Supplier<T>NoneTAny Factory Method. Get Constant Values defined in certain context.
UnaryOperator<T>TTLogical not (!)
BinaryOperator<T> (T,T)(T,T)TMultiplying two numbers (*)

  • There are many interfaces in Java that encapsulates blocks of code such as "Runnable" or "Comparator"
  • Lambdas are backwards compatible with these interfaces.

When to supply Lambda Expression?

  • When an object of an interfaces with a single method is expected. Eg. ActionListerner is the functional interfaces in  the following example: The Left Hand Side Code changes to written in Lambda expression in the right hand side.
  • button.addActionListener( new ActionListener() {

        public void actionPerformed(ActionEvent event){
            System.out.println("Click on Button");
            }
    })
    button.addActionListerner( event ->
                 System.out.println("Click on Button"); )
  • The boiler plate code is minimized, readability enhanced and meaningfulness accomplished.

Why a functional interface must have a single abstract method. Aren’t all methods in an interface abstract?

  • In Java 8, interfaces can declare nonabstract methods.
  • Some interfaces in the Java API redeclare Objectmethods (such as toString or clone) to attach javadoc comments. But these declarations do not make the methods abstract.
    • Check out the Comparator API for an example.

Java 8 : Frequently Asked Questions for Interviews - 4



  1. What  is the Syntax of Lamdba Expression ? Give examples of each.
  2. Can we use annotations and final modifiers for parameters in Lambda expressions?
  3. Since Java is statically typed language, it is necessary to specify the type for parameters in lambda expressions?
  4. In what cases and when can we avoid specifying type for parameters in Lambdas?
  5. How do you specify type of returned variables in Lambdas?


Syntax of Lambda expressions in Java8 is very similar to writing methods without any return types :

  • parameter -> expression
  • (parameters) -> {expressions}
  • () -> expression
  • () -> {expressions}
  • (type parameter, type parameter ....) -> expression
  • (type parameter, type parameter ....) -> { expressions }
  • Never specify the result type of a lambda expression. It is always inferred from the context.
SyntaxMeaningExample
parameter -> expression sasdasdadsadadadadadasSimplest Lambda expression, the code fits into one expression.
A single parameter with inferred type of passed to the lambda expression. The type of parameter is implied in the context.
asdasfasdfassdsdfsfsdfsdfsdfsddfsdfasdfasdfafsadfsd
ActionListener acl = event ->
       System.out.println("Single expression Lamdba");asdasfasdfassdsdfsfsdfsdfsdfsdadfsd
(parameters) -> {expressions}Multiple parameters with multiple expressions are often coded inside "( )" and " { } " respectively.The type of parameters is implied in the context.BinaryOperator<Long> add = (x , y) ->
        { z = x + y;
              return z; }
Comparator<String> comp = (first, second) ->
         Integer.compare( first.length(),
                                      second.length() )
() -> expressionLambda that requires no parameters , one still provides an empty parenthesisRunnable myRun = () ->
          System.out.println("Running a
                runnable's RUN !!")
() -> {expressions}Lambda has no parameters but performs a bunch of tasks/multiple expressions() -> { for ( int i = 0; i <10 ; i++ ) {
          new Thread(myRun).start();
}}
(type parameter, type parameter ....) -> expressionWhen the type of parameters are not implied in the context, we need to supply the type with the parameter. 
(type parameter, type parameter ....) -> 
{ expressions }
Same meaning as above, but with more number of expressions.
No return type for lambdaThe result type of lambda expression is always inferred from the context (first, second) ->
            Integer.compare(first.length(),
                      second.length())
The above example is used in context where the result type is int.
(annotations type parameter) -> expressionJust like method parameters, you can add annotations to lambda parameters(@NonNull String name) -> ....
(final type parameter) -> expressionSimilarly, one can add final modifier to typed parameter in Lambda expressions(final String name) -> ....



Friday, June 13, 2014

Java 8 : Frequently Asked Questions for Interview - 3

What is Lambda Expression?
Lamdba expressions are just a block of code that can be passed around, which can be executed later, once or multiple times. A detailed answer here

Follow-up Question - Where have you seen similar code blocks in Java all along, before Java 8?

There are several examples where you write code in Java at some point, and it is executed at a later time. However, since Java is Object Oriented language, its not easy to pass or give somebody a block of code without having to construct an object belonging to a class that has the method with the desired behavior ( the method is the only behavior we want to execute ).
  1. run Method of a Runnable : while working with separate threads, we put the work in run method of a Runnable. Which we either execute by constructing an instance of the class that implements Runnable or simply submit the instance to a thread pool to start it in queue.
  2. class Task implements Runnable {
        public void run() {
            for(int i = 0; i < 10 ; i++) doTask(); 
        }
    }
    
    Task task = new Task();
    new Thread(w).start();
    
  3. sorting with custom comparator :while primitive sorts can work without any custom comparator code, sometimes the need arises to sort values based on different criteria. For instance  sorting an array of car objects, based on first their color, or their ratings or based on their prices. One can construct separate comparators and pass it to Array.sort method to defer the sorting at runtime. Note: the current code works with Java7 which has static method Integer.compare implemented in core java library.
  4. class ColorComparator implements Comparator<Car> {
        public int compare(Car firstCar, Car secondCar) {
            return firstCar.getColor().compareTo(secondCar.getColor()); 
        }
    }
    class RatingComparator implements Comparator<Car> {
        public int compare(Car firstCar, Car secondCar) {
            return Float.compare(firstCar.getRatings(),secondCar.getRatings());
        }
    }
    
    class PriceComparator implements Comparator<Car> {
        public int compare(Car firstCar, Car secondCar) {
            return Integer.compare(firstCar.getPrice(),secondCar.getPrice());
        }
    }
    
    
    Car cars = new Car[] { new Car("blue", 5.2f, 12000), new Car("green", 5.1f, 200000), new Car("grey", 6.2f, 1000), new Car("blue", 5.25f, 12090)}
    Arrays.sort(cars, newColorComparator());
    Color Cars
    Car [ blue, 5.2 12000 ]
    Car [ blue, 5.25 12090 ]
    Car [ green, 5.1 200000 ]
    Car [ grey, 6.2 1000 ]
    
    Arrays.sort(cars, new RatingComparator());
    Ratings Cars
    Car [ green, 5.1 200000 ]
    Car [ blue, 5.2 12000 ]
    Car [ blue, 5.25 12090 ]
    Car [ grey, 6.2 1000 ]
    
    Arrays.sort(cars, new PriceComparator());
    Price Cars
    Car [ grey, 6.2 1000 ]
    Car [ blue, 5.2 12000 ]
    Car [ blue, 5.25 12090 ]
    Car [ green, 5.1 200000 ]
    
    
  5. button callback : Button callback is another example of deferred execution. A callback action added to a class implementing the listener interface is a good example of that sort. For button, we can construct an instance of the class implementing the listener interface and then register it to the button class. In fact, the strategy is used often for creating GUI component callback actions the most listeners use "anonymous instance of the anonymous class".
  6. button.setOnAction(new EventHandler<actionEvent>() {
        public void handle(ActionEvent event) {
            System.out.Println("Event registered with User's click!!!")
        }
    }
    
    
    The callback is executed only on the click of the button, which eventually calls the code inside the handle method.
NOTE : It is possible to work with blocks of code in directly in other languages, However, in those languages it is vary easy to spawn a thread or to register a button click handler. In java, one could accomplish similar goals by writing similar API, but such API would be very unpleasant to use.

Wednesday, June 11, 2014

Java 8 : Frequently Asked Questions for Interview - 2

What is Lamdba Expression

Lambda Expressions are at the heart of Java SE 8. A “Lambda Expression” is a block of code that you can pass around so it can be executed later, once or multiple times.

Lambda Expressions are Closures or anonymous methods that provide developers with a simple and compact means for representing behavior as data.
  • The use or lambda expression improves readability, performance and reusability
  • The use of lambda expressions is all about abstracting complexity away into libraries
  • The use of lambda expressions improves developer productivity  
For example:  If one wants to model a workflow such as ` do A before you start, do B for each file in the file group, do C upon error and do D after you finish`, than one needs to break the phases of the workflow & the client code has to be directly involved in each phase.
=> Java (before java8) lacks in tools which can express the behavior from A to D. It also affects the APIs design.

Things to Remember in Lambda Expressions :

  • A lambda expression is a block of code with parameters.
BinaryOperator add = (long x, long y) -> {
    x+y
}
  • Use a lambda expression whenever you want a block of code executed at a later point in time.
Runnable myRunnable = () -> { 
    System.out.Println("Executing the Run method inside the Runnable!!!");
    DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = new Date();
    System.out.println("Running at a deferred time > "+df.format(date));
}
  • Lambda expressions can be converted to functional interfaces.
  • Lambda expressions can access effectively final or final variables from the enclosing scope.
public void enclosingMethod() {

    final String IamFinalVariable = "This is an immutable final variable";
    Button button = new Button("click me");
    button.addActionListener( event -> System.out.println(IamFinalVariable);

    String IamEffectivelyFinalVariable = "This is effectively final variable. Its value should not change in this scope.";
    IamEffectivelyFinalVariable = "Do not try to change me. Otherwise compiler will error out";

    JRadioButton finalRadioButton = new JRadioButton("Final Var Selected");
    finalRadioButton.setActionCommand(IamFinalVariable);
    JRadioButton effectiveFinalRadioButton = new JRadioButton("Effective Final Var Selected");
    effectiveFinalRadioButton.setActionCommand(IamEffectivelyFinalVariable);

    ButtonGroup group = new ButtonGroup();
    group.add(finalRadioButton);
    group.add(effectiveFinalRadioButton);

    ActionListener selectOrDeselect = event -> {
        System.out.println("You are talking to >"+ event.getActionCommand(    ));
   }
}
  • Method and constructor references refer to methods or constructors without invoking them.
  • You can now add default and static methods to interfaces that provide concrete implementations.
  • You must resolve any conflicts between default methods from multiple interfaces






Tuesday, June 10, 2014

Java 8 : Frequently Asked Questions for Interview - 1

What was lacking in Java before JAVA 8? Why are Lambda expressions introduced?

Now-a-days there is rising demand and requirement for 
1. Highly COMPLICATED applications
2. Programs that are executed on machines with MULTI-CORE CPU

Java (before Java8) has various cavets that makes it hard to write programs that could satisfy modern computing requirements because :

1. Programs using locks are error-prone and time-consuming
2. There is limits on level-of-abstraction that library writers can use
  • eg. lack of efficient parallel operations over large collections of data
3. There is lack of tools for expressing behavior easily without having to be involved in client code
4. Anonymous inner classes are hard-to-read & too verbose.
  • Callbacks and event handlers makes the process of reading code difficult.

What is Functional Programming?

  • Abstracting over behavior.
  • It is different from Object Oriented Programming in the sense that OOPs is mostly abstraction over data. 
  • Long before OOPs was introduced, there were several functional programming languages such as Lisp and Scheme. However, their benefits were not much appreciated outside academic circles. 
  • Functional programming is important because it is well suited for concurrent and event-driven (or “reactive”) programming

Whats new/Different for a Java programmer in Java 8 ?

  1. Learn to write and read lambda-enabled code
  2. Learn new syntax and a new idioms ( better than writing hugely complex thread-safe code )
  3. Write performance critical code
  4. Write easier-to-read code (code expressing business logic clearly rather than how its achieving it)
  5. Be able to blend both OOPS and functional programming together
  6. Even if you are not interested in concurrency, Java 8 provides a powerful upgrade. For example: Collection libraries can be given powerful APIs if the language has a convenient syntax for function expressions.
  7. ENJOY!
    • Code is easier to maintain, more reliable and less error-prone