Thursday, 10 March 2016

Predicate vs Function in Java 8

Both Predicate and Function are predefined functional interfaces introduced in JDK8. 

These are added in java.util.function package. 

Predicate Interface

This is represented as Predicate<T> where T is an object type input.
The purpose of Predicate<T> is to decide if the object of type T passes some test.
For this,
Predicate interface contains a method test() , which takes one argument and returns a Boolean value.
Here is an example of using Predicate to determine if a number is greater than zero or not.
 import java.util.function.Predicate;
public class PredicateInterfaceDemo {
public static void main(String[] args) {
int num = -10;
Predicate gt_lt = i -&gt; i&gt;0 ;
boolean result = gt_lt.test(num);
System.out.println(num + " greater than zero : "+ result);
 }
}
Running this program will produce :
-10 greater than zero : false
In the above program, a predicate gt_lt was created to test whether a number is greater than zero. Then it was tested with -10 and the test() method of Predicate returned false.

Function Interface

Function interface is represented as Function<T,R> where T is the type of object passed to Function and R is the type of object returned.
Functions are similar to Predicates, but Functions return an object as result while Predicates return Boolean.
For this,
Function interface contains a method called apply() , which takes a one argument and returns an object as result.
Here is an example of Function that takes a string and returns its length.
 import java.util.function.Function;
public class FunctionInterfaceDemo {
public static void main(String[] args) {
Function&lt;String, Integer&gt; length = str -&gt; str.length();
System.out.println("Length of string 'Hello World' is " + length.apply("Hello World"));
}
} 
Running this program will produce following output :
Length of string ‘Hello World’ is 11
In the above example, Function length takes a String as parameter and returns an Integer.
The Function interface has inbuilt apply() function that uses the logic provided to evaluate the length of string “Hello World”.

Difference between Predicate and Function

A Predicate takes one object argument and returns a Boolean value where as a Function takes an object argument and returns an object.
Predicate contains a method test() for testing if the object matches its condition. Function contains apply() method that applies some logic on object parameter and returns an object.

Singleton Design Pattern in Java

In this article, we will discuss :

– What is Singleton design pattern ?
– How to implement Singleton design pattern in java ?
– Effects of multithreading on singleton pattern
– Implementing Double checked locking for singleton
– Eager instantiation of singleton
– Ways of breaking singleton
– Uses of Singleton pattern
– Singleton pattern in Java EE
– Singleton as Anti-pattern
-Singleton is an EJB

Singleton Design Pattern


The Singleton pattern ensures that a class has only one instance and provides a global point of access to it.

Standard Singleton implementation


To ensure the class has only one instance, we mark the constructor has private. So, we can only instantiate this class from within the class.



We create a static variable that will hold the instance of the class.

Then, we create a static method that provides the instance of the singleton class. This method checks if an instance of the singleton class is available. It creates an instance, if its not available; Otherwise, it returns the available instance.



@Command public class Singleton { private static Singleton instance; private Singleton() { } public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }

Problem with the standard implementation code above


The standard singleton implementation code works fine in Single threaded environment.

But in multithreaded environment, the getInstance() code breaks :

public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; }
If two threads enter the if condition at the same time, then two instances of Singleton will be created.

Handling Multithreading issue with standard singleton implementation


We can add synchronized keyword to the getInstance method signature and it would make the method synchronized. So, only one thread can access it at a time.

public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
  
This solves the multithreading issue. But it is slow since only one thread can access getInstance() method at a time.

We can use following approaches for this :

1 : Double checked locking


In this approach, we first check if the instance is created. If not, we synchronize.

public class Singleton { private static Singleton instance; private Singleton() { } public static Singleton getInstance() { // first check if instance is available if (instance == null) { // if instance not available, enter synchronized block to create synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }
This is an approach to handle multithreading issues with the standard implementation. However, this approach has issues as well. Read more about this in the comments section before using this.

2 : Eager instance creation


We can choose to create the instance of Singleton class when the class is loaded.

public class EagerSingleton {
// create instance eagerly
private static EagerSingleton instance = new EagerSingleton();

private EagerSingleton() {
}

public static EagerSingleton getInstance() {
return instance;// just return the instance
}
}

3 : Bill Pugh Singleton


This solution is considered better as it performs singleton instantiation when getInstance() is called.

public class BillPughSingleton { private BillPughSingleton() { } private static class SingletonHelper { private static final BillPughSingleton INSTANCE = new BillPughSingleton(); } public static BillPughSingleton getInstance() { return SingletonHelper.INSTANCE; } }

4 : Creating Singleton using Enum


Enum is thread safe. We can implement Singleton through Enum so that the singleton will have only one instance even in a multithreaded environment.

public enum EnumSingleTon {
INSTANCE;
// add sinlgeton methods
public void method() {
System.out.println("SingleTon Method");
}
}
public class TestEnumSingleton {
public static void main(String[] args) {
EnumSingleTon.INSTANCE.method();
}
} 
Using enums protects against deserialization and reflection. Also, Enum singletons are lazily initialized.
Enum based singleton is considered the best way to implement singletons. (Refer : Effective Java by Joshua Bloch)

Breaking Singleton questions you may get in interviews


Even though we avoided multiple instance creation of singleton class by using Double checked locking or Eager instance creation, instances can still be created by :
– cloning
– reflection
– Deserialization
– Sub-classing singleton class

How to avoid Singleton instance creation by cloning ?


We can create a copy of an object using clone() method.

To avoid creating a clone of our singleton class, we can do the following :

– Implement Cloneable interface
– Override the clone() method and throw CloneNotSupportedException from it.

How to avoid Singleton class instance creation through Reflection ?


To avoid instance creation through reflection, throw an exception from constructor if it already has an instance.

private Singleton() {
    if( Singleton.instance != null ) {
       throw new InstantiationError("Cannot create instance Singleton through reflection");
     }
}

How to avoid singleton instance creation during deserialization ?


Avoid multiple singletons during deserialization using readResolve().

protected Object readResolve() {return instance;}

How to avoid a subclass creating singleton instance ?


If you just provide a private constructor, a subclass cannot instantiate it to create another instance. This is because the super constructor won’t be visible to the child class.

Uses of Singleton Design Pattern


Logger


Singleton pattern is a good option for the Logger class when we want to create one log file with the logged messages. If we have more than one instances of Logger in the application, a new log will be created with every instance.

Cache


We can use Singleton pattern to implement caches as that provides a single global access to it.

Implementing Singleton Pattern in Java EE


In Java EE, just by adding @Singleton annotation to a class, you can turn it into a singleton bean.

import javax.ejb.Singleton;
@Singleton
public class SingletonBean {
} 
The @Singleton annotation marks the class as a singleton EJB, and the container handles creation and usage of the single instance.

Why singleton pattern is considered an Anti-pattern ?


– Singletons aren’t easy to handle with unit tests. You can’t control their instantiation and they may retain state across invocations.

Frameworks such as Spring control the lifecycle of their objects and often create singletons, but these objects are injected into their dependent objects by the framework. Thus the codebase itself doesn’t treat the objects as singletons.

– In multithreaded environment, access to the singleton object may have to be guarded (e.g. via synchronisation).

Singleton is an EJB

http://www.mastertheboss.com/javaee/ejb-3/singleton-ejb-tutorial

Monday, 21 December 2015

Exceptions Java - MCQ set 1 (25 questions, 50 marks)

Exceptions Java - MCQ set 1 (25 questions, 50 marks)



    Q1 - Q5, 5 EASY level difficulty questions 1 mark each. 1 * 5 = 5 marks 

  1. Exception is a class/interface/abstract class/other?

  2. a.Class
    b.Interface
    c.Abstract class
    d.Other

  3. Exception is found in which package in java

  4. a.java.lang
    b.java.util
    c.java.io
    d.java

  5. Exception was introduced in which java version

  6. a.Java 1
    b.Java 2
    c.Java 3
    d.Java 4

  7. Which of these class is highest in hierarchy in java

  8. a.java.lang.Exception
    b.java.lang.Error
    c.java.lang.Throwable
    d.java.lang.Object

  9. What keyword is used to explicitly raise a exception?

  10. a.catch
    b.throw
    c.throws
    d.raise



    Q6 - Q20, 15 MEDIUM level difficulty questions 2 mark each. 2 * 15 = 30 marks

  11. What block is always executed, independently of a exception being raised?

  12. a.throws
    b.finally
    c.catch
    d.throw

  13. Exception and Error are direct subclasses of?

  14. a.BaseException
    b.Throwable
    c.Object
    d.RuntimeException

  15. FileNotFoundException

  16. a.Is a subclass/extends IOException
    b.Is a Compile time exception
    c.Found in java.io package
    d.All

  17. IOException

  18. a.Found in java.io package
    b.Is a Compile time exception
    c.Is a subclass/extends Exception
    d.All

  19. Which of these are java.lang.Error in exception handling in java

  20. a.VirtualMachineError
    b.IOError
    c.AssertionError
    d.ThreadDeath
    e.All

  21. In which condition will the finally block will not be executed?

  22. a.When some Error occurs
    b.When Exception is raised
    c.When System.Exit(1) is called
    d.In all the cases

  23. What type of Exceptions can be ignored at compile time?

  24. a.Runtime
    b.Checked
    c.Both
    d.None

  25. What will be output of following exception handling code in java -


  26. a.ade
    b.adb
    c.bcde
    d.adbe

  27. What will be output of following program -


  28. a.runtime exception
    b.program will compile
    c.program won't compile
    d.

  29. What will happen in this program -


  30. a.StackFlowoverError
    b.compile timeError
    c.StackOverflowException
    d.StackOverflowError

  31. What is invalid statements for automatic resource management in java?

  32. a.Allows us to catch more than one exception in one catch block
    b.We could separate different exceptions using pipe ( | )
    c.Increases developer efforts of writing multiple catch blocks.
    d.None

  33. multiple catch syntax was introduced in ?

  34. a.java 5
    b.java 6
    c.java 7
    d.java 8

  35. Which of these points will be valid If superclass method does not throw any exception

  36. a.overridden method of subclass can throw any RuntimeException
    b.overridden method of subclass cannot throw any checked exception
    c.overridden method of subclass may not throw any exception.
    d.All

  37. What will happen when catch and finally block both return value?

  38. a.method will return value returned by finally block
    b.method will return value returned by catch block
    c.finally block won't execute
    d.None

  39. can a method be overloaded on basis of exceptions ?

  40. a.Will produce runtime error
    b.Will produce compilation error - ambiguity error
    c.Yes a method be overloaded on basis of exceptions.
    d.None



    Q21 - Q25, 5 HARD level difficulty questions 3 mark each.       3 * 5 = 15 marks

  41. What will be output of following program -


  42. a.runtime exception
    b.method return -> finally
    c.method return -> catch
    d.compile timeError

  43. What will be output of following program -


  44. a.abc
    b.abcd
    c.runtime exception
    d.compile timeError

  45. Which is valid about java.lang.Exceptions?

  46. a.The class Exception and all its subclasses that are not also subclasses of RuntimeException are checkedexceptions
    b.The class Error and all its subclasses are unchecked exceptions
    c.The class RuntimeException and all its subclasses are unchecked exceptions
    d.All

  47. What is disadvantage/invalid about try-with-resource

  48. a.introduced in java 7
    b.we need not to write explicit code for closing file
    c.Using multiple resources inside Try-with-resources is also allowed
    d.None

  49. FileInputStream implements which interface for closing file automatically in java7?

  50. a.java.lang.AutoClose
    b.java.lang.CloseAutomatically
    c.java.lang.AutoCloseable
    d.java.lang.Closeable




Quiz 1 - Correct answers



EASY
1) a
2) a
3) a
4) d
5) b

MEDIUM
6) b
7) b
8) d
9) d
10) e

11) c
12) a
13) b
14) c
15) d
16) c
17) c
18) d
19) a
20) c

HARD
21) b
22) c
23) d
24) d
25) c

Go to TOP of the page




Exceptions Java - MCQ set 2 (25 questions, 50 marks)



    Q1 - Q5, 5 EASY level difficulty questions 1 mark each. 1 * 5 = 5 marks 

  1. What type of Exceptions can NOT be ignored at compile time?

  2. a.Checked Exceptions
    b.Unchecked Exceptions
    c.Uncompiled Exceptions
    d.Error

  3. java.lang.NullPointerException is a

  4. a.Error
    b.runtime exception
    c.Compile time exception
    d.None

  5. What will be output of following program -


  6. a.compile timeError
    b.UserDefinedException will be thrown
    c.UserDefinedException will be thrown and end will be present in output
    d.None

  7. Which of these is valid code snippet in exception handling in java?

  8. a. catch{ }
    b. finally{ }
    c. try{ }finally{ }
    d. try{ }

  9. Which of these will be invalid declaration

  10. a.try-catch block.
    b.
    c.try-catch-finally block.
    d.catch-finally block.



    Q6 - Q20, 15 MEDIUM level difficulty questions 2 mark each. 2 * 15 = 30 marks

  11. What will be output of following program -


  12. a.runtime exception
    b.compilation error
    c.superClass method
    d.SubClass method

  13. What will be output of following exception handling code in java -


  14. a.SubClass method
    b.compilation error
    c.runtime exception
    d.superClass method

  15. What will be output of following exception handling program -


  16. a.after calling m()
    b.runtime exception
    c.program won't compile
    d.None

  17. What will be output of following exception handling code in java -


  18. a.superClass method
    b.runtime exception
    c.compilation error
    d.SubClass method

  19. What will be output of following exception handling program -


  20. a.superClass method
    b.runtime exception
    c.SubClass method
    d.compilation error

  21. What will be output of following exception handling code in java -


  22. a.superClass method
    b.SubClass method
    c.runtime exception
    d.None of these

  23. If superclass method throws unchecked exception then overridden method of subclass can throw

  24. a.Only subclasses of exception thrown by superclass method
    b.Can't throw any exception
    c.Any checked exception
    d.Any runtime exception

  25. What will be output of following program -


  26. a.runtime exception
    b.superClass method
    c.compilation error
    d.SubClass method

  27. If superclass method throws checked exception than

  28. a.overridden method of subclass can declare any RuntimeException
    b.overridden method of subclass can declare narrower checked exception
    c.overridden method of subclass cannot throw broader checked exception
    d.All

  29. Which of these is not a one of the exception handling keyword?

  30. a.finally
    b.exception
    c.try
    d.catch

    e.throw

  31. What is invalid about java.lang.Error in java?

  32. a.Errors are abnormal conditions in application
    b.Error indicates some serious problems that our application should not try to catch
    c.Error is unchecked Exception
    d.Error is a subclass of Throwable

  33. Which of these not a Error?

  34. a.VirtualMachineError
    b.ClassNotFoundError
    c.OutOfMemoryError
    d.IOError

  35. Which is invalid about throws in Exception handling in java?

  36. a.throws can propagate exception to calling method
    b.throws can be used to throw multiple exception at time.
    c.throws is used inside method to throw exception
    d.None of these

  37. What is true about exception handling keyword throw in java

  38. a.throw is a keyword
    b.throw can be used to throw only one exception at time.
    c.throw is used inside method
    d.All

  39. Automatic resource management was introduced in which java version?

  40. a.java 5
    b.java 6
    c.java 7
    d.java 8



    Q21 - Q25, 5 HARD level difficulty questions 3 mark each.       3 * 5 = 15 marks

  41. Which of these is not a good exception handling practice?

  42. a.Throw exceptions when the method cannot handle the exception, and more importantly, must be handled by the caller
    b.log the exception and bubble it
    c.Bubble the exception if the method cannot handle it.
    d.Throw the exception right away

  43. Which are valid statements in Exception handling in java?

  44. a.Java exception handling allows us to use multiple catch block.
    b.Exception class handled in starting catch block must be subclass of Exception class handled in following catch blocks
    c.Either one of the multiple catch block will handle exception at time
    d.All

  45. Which is invalid statement in Exception handling in java?

  46. a.finally block can't throw exception
    b.try block can throw exception
    c.catch block can throw exception
    d.finally block can throw exception

  47. Which of these exceptions are propagated automatically in java?

  48. a.IOException
    b.NullPointerException
    c.ClassNotFoundException
    d.SQLException

  49. Which of these exceptions are always needed to be manually propagated?

  50. a.Error
    b.unchecked exceptions
    c.checked exceptions
    d.None




Quiz 2 - Correct answers



EASY
1) a
2) b
3) b
4) c
5) d

MEDIUM
6) d
7) b
8) b
9) d
10) d

11) b
12) d
13) c
14) d
15) b
16) c
17) b
18) c
19) d
20) c

HARD
21) b
22) d
23) a
24) b
25) c