Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

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