Monday, August 29, 2016

Enumerations or Enums

Enumerations was added to Java language in JDK5. Enumeration means a list of named constant. In Java, enumeration defines a class type. An Enumeration can have constructors, methods and instance variables. It is created using enum keyword. Each enumeration constant is publicstatic and final by default. Even though enumeration defines a class type and have constructors, you do not instantiate an enum using new. Enumeration variables are used and declared in much a same way as you do a primitive variable.
How to Define and Use an Enumeration
  1. An enumeration can be defined simply by creating a list of enum variable. Let us take an example for list of Subject variable, with different subjects in the list.
enum Subject           //Enumeration defined
{
 Java, Cpp, C, Dbms
}

2.      Identifiers Java, Cpp, C and Dbms are called enumeration constants. These are public, static final by default.
  1. Variables of Enumeration can be defined directly without any new keyword.
Subject sub

Example of Enumeration
enum WeekDays
{ sun, mon, tues, wed, thurs, fri, sat }

class Test
{
 public static void main(String args[])
 {
  WeekDays wk;
  wk = WeekDays.sun;
  System.out.println("Today is "+wk);
 }
}

Values( ) and ValueOf( ) method
All the enumerations have values() and valueOf() methods in them. values() method returns an array of enum-type containing all the enumeration constants in it. Its general form is,
public static enum-type[ ] values()
valueOf() method is used to return the enumeration constant whose value is equal to the string passed in as argument while calling this method. It's general form is,
public static enum-type valueOf (String str)

Points to remember about Enumerations

  1. Enumerations are of class type, and have all the capabilities that a Java class has.
  2. Enumerations can have Constructors, instance Variables, methods and can even implement Interfaces.
  3. Enumerations are not instantiated using new keyword.
  4. All Enumerations by default inherit java.lang.Enum class.

Static Blocks in Java

Static blocks are also called Static initialization blocks. A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example: 
static {
    // whatever code is needed for initialization goes here
}

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code. And don’t forget, this code will be executed when JVM loads the class. JVM combines all these blocks into one single static block and then executes. Here are a couple of points I like to mention: 

  • If you have executable statements in the static block, JVM will automatically execute these statements when the class is loaded into JVM.
  • If you’re referring some static variables/methods from the static blocks, these statements will be executed after the class is loaded into JVM same as above i.e., now the static variables/methods referred and the static block both will be executed.
So what are the advantages of static blocks?
  • If you’re loading drivers and other items into the namespace. For ex, Class has a static block where it registers the natives.
  • If you need to do computation in order to initialize your static variables, you can declare a static block which gets executed exactly once, when the class is first loaded.
  • Security related issues or logging related tasks

Of course there are limitations for static blocks 

  • There is a limitation of JVM that a static initializer block should not exceed 64K.
  • You cannot throw Checked Exceptions.
  • You should not return anything from this block.
  • Static blocks make testing a nightmare.

Serialization and Deserialization in Java


Serialization is a process of converting an object into a sequence of bytes which can be persisted to a disk or database or can be sent through streams. The reverse process of creating object from sequence of bytes is called deserialization.

Serialization is usually used when there is need to send your data over network or to store in files. By data I mean objects and not text.
Now the problem is your Network infrastructure and your Hard disk are hardware components that understand bits and bytes but not Java objects.
Serialization is the translation of Java object’s values/states to bytes to send it over network or to save it. On other hand, Deserialization is conversion of byte code to corresponding java objects.

A class must implement Serializable interface present in java.io package in order to serialize its object successfully. Serializable is a marker interface that adds serializable behaviour to the class implementing it.

Java provides Serializable API encapsulated under java.io package for serializing and deserializing objects which include,
  • java.io.serializable
  • java.io.Externalizable
  • ObjectInputStream
  • and ObjectOutputStream etc.

Marker interface
Marker Interface is a special interface in Java without any field and method. Marker interface is used to inform compiler that the class implementing it has some special behaviour or meaning. Some example of Marker interface are,
  • java.io.Serializable
  • java.lang.Cloneable
  • java.rmi.Remote
  • java.util.RandomAccess
All these interfaces do not have any method and field. They only add special behavior to the classes implementing them. However, marker interfaces have been deprecated since Java 5, they were replaced by Annotations. Annotations are used in place of Marker Interface that play the exact same role as marker interfaces did before.

Concept of serialVersionUID :
serialVersionUID is used to ensure that same class(That was used during Serialization) is loaded during Deserialization.serialVersionUID is used for version control of object.

Signature of writeObject() and readObject()
writeObject() method of ObjectOutputStream class serializes an object and send it to the output stream.
public final void writeObject(object x) throws IOException
readObject() method of ObjectInputStream class references object out of stream and deserialize it.
public final Object readObject() throws IOException,ClassNotFoundException
while serializing if you do not want any field to be part of object state then declare it either static or transient based on your need and it will not be included during java serialization process.

Serializing an Object
import java.io.*;
class studentinfo implements Serializable
{
 String name;
 int rid;
 static String contact;
 studentinfo(string n, int r, string c)
 {
  this.name = n;
  this.rid = r;
  this.contact = c;
 }
}

class Test
{
 public static void main(String[] args)
 {
 try
 {
  Studentinfo si = new studentinfo("Abhi", 104, "110044");
  FileOutputStream fos = new FileOutputStream("student.ser");
  Objectoutputstream oos = new ObjectOutputStream(fos);
  oos.writeObject(si);
  oos.close();
  fos.close();
  }
  catch (Exception e)
  { e. printStackTrace(); }
 }
}
Object of Studentinfo class is serialized using writeObject() method and written to student.ser file.

Deserialization of Object
import java.io * ;
class DeserializationTest
{
 public static void main(String[] args)
 {
  studentinfo si=null ;
  try 
  {
   FileInputStream fis = new FileInputStream("student.ser");
   ObjectOutputStream ois = new ObjectOutputStream(fis);
   si = (studentinfo)ois.readObject();
  }
  catch (Exception e)
   { e.printStackTrace(); }
  System.out.println(si.name);
  System.out. println(si.rid);
  System.out.println(si.contact);
 }
}
Output :
Abhi
104
null
Contact field is null because, it was marked as static and as we have discussed earlier static fields does not get serialized.

NOTE: Static members are never serialized because they are connected to class not object of class.

transient Keyword
While serializing an object, if we don't want certain data member of the object to be serialized we can mention it transient. transient keyword will prevent that data member from being serialized.
class studentinfo implements Serializable
{
 String name;
 transient int rid;
 static String contact;
}
  • Making a data member transient will prevent its serialization.
  • In this example rid will not be serialized because it is transient, and contact will also remain unserialized because it is static.

What if superclass is Serializable?
If superclass is serialzable then all its subclasses are automatically serializable.

What if superclass is not Serializable?
If super class is not serializable then we have to handle it quite differently.
If superclass is not serializable then it must have no argument constructor.

If superclass is not Serializable then all values of the instance variables inherited from super class will be initialized by calling constructor of Non-Serializable Super class during deserialization process. so here name is inherited from person so during deserialization,name is initialized to default.

What if superclass is Serializable but you don’t want subclass to be Serializable
If you don’t want subclass to serializable then you need to implement writeObject() and readObject() method and need to throw NotSerializableException from this methods.



HashMap Interview Questions in java

Can we synchronize a HashMap?
Yes, a HashMap can be synchronized using its synchronizedMap() method.
Map s = Collections.synchronizedMap(new HashMap(…));
  
Can we add duplicate keys in a HashMap?
What happens to the value if we add a duplicate key with new value? Is is discarded or is it overwritten?

If a key already exists in a HashMap and we try to add another value for the same key, then the old value of the key will be replaced with the new value.

What is the difference between a HashMap and a Hashtable?
– HashMap is not synchronized whereas Hashtable is synchronized.
– HashMap allows a null key and null values. Hashtable does not allow null keys or values.
– Since HashMap isn’t synchronized, it is faster compared to a HashTable.

- Iterator in hashmap is fail-fast. But enum in Hashtable is not fail-fast. Fail-fast means if one thread is iterating over a map and another is trying to modify it by adding/deleting elements, it will throw ConcurrentModificationException

What is an IdentityHashMap? How is it different from a normal HashMap?
IdentityHashMap is similar to HashMap except that it uses reference equality when comparing elements.
Instead of using the equals() method to compare entries as in HashMap, IdentityHashMap compares them using the == operator
So, two object references are considered equal if they refer to the same object instance.

What is a WeakHashMap?
A WeakHashMap implements a map that uses “weak keys”.
This allows an element in the map to be garbage-collected when the key is unused.
  
What is the difference between remove() and clear() methods in HashMap ?
We can remove entries from HashMap using remove(key) or clear() methods.
remove(key) removes the mapping for the key specified in parameter.
clear() method removes all the entries from the HashMap and returns void.
  
Explain how HashMap works?
HashMap works on the principle of hashing.

put() and get() methods are used to store and retrieve data from hashmap.
It has a number of buckets which stores key-value pairs.

when put() is called, hashmap implementation calls hashcode() on the key to identify the bucket location… then stores both key+value in the bucket
when get() is called, the hashcode() on key is used to identify the bucket location and the value if returned.

If two key objects have same hashcode, bucket location will be the same and collision occurs in hashmap.
Inside the bucket, data is stored in linked list, so in collision scenario, it will get added to next node.
So, when get() is called, the hashcode() would point to the bucket location, then the use key.equals() to find the correct node in the linked list.
  
What is the difference between ConcurrentHashMap and Hashtable?
 Both can be used in multithreaded environment but once the size of Hashtable becomes considerable large performance degrade because for iteration it has to be locked for longer duration.

Since ConcurrentHashMap introduced concept of segmentation , no matter how large it becomes only certain part of it get locked to provide thread safety so many other readers can still access map without waiting for iteration to complete.

In Summary ConcurrentHashMap only locked certain portion of Map while Hashtable lock full map while doing iteration.

What is the difference between ConcurrentHashMap and Collections.synchronizedMap ?
ConcurrentHashMap is designed for concurrency and improve performance while HashMap which is non synchronized by nature can be synchronized by applying a wrapper using Collections.synchronizedMap.




Java Design Pattern Interview questions

If two different class loaders load a singleton class, would they load it twice ?
Two objects loaded by different class loaders are never equal even if they carry the same values.
So, each class loader will have its own singleton.

What is Decorator design pattern?
The decorator design pattern attaches responsibilities to objects at runtime.
BufferedInputStream in java.io is an example of Decorator. It wraps around a InputStream and provide additional buffering functionality.

What is Strategy design pattern?
Strategy design pattern lets you swap new algorithms and processes into your program without
affecting the objects that use them.
AWT containers delegate the layout to layout managers. Layout managers use strategy pattern to for appropriate layout.

What is Iterator Design pattern?
 Iterator pattern is used to iterate over a collection sequentially and provide a way the access the individual elements.

What is Factory pattern?
 Factory pattern abstracts the object creation process from the code that uses the objects.

What is Front Controller design pattern?
Front controller suggest using a single servlet for centralizing request handling and delegating functions like validation and business process handling to helpers.

What is Composite view pattern?
A composite view is made of several sub-views.
A JSP page can use a header jsp, footer jsp etc.

What is View Helper pattern?
In this pattern, the view delegates processing responsibilities to helper classes.
Implemented using Javabeans.

Difference between Service to Worker pattern and Dispatcher View pattern.
Both pattern use Front controller combined with Helpers with Dispatcher component.
In Service to worker, front controller delegates content retrieval to View Helpers. Controller also takes care of tasks like authentication, authorization etc.
In Dispatcher View, Controller does not delegate content retrieval to helpers. Most of the work is done by views.


Java 8 new features

This article provides a summary of some of the important Java 8 new features.
Java 8 is the newest release of Java and the developer kit is JDK 8.
This is a significant upgrade to Java language.

1.      Introduction of Lambda Expression
Lambda expression is a major change in java as it changes how code is written in java and how solutions are conceptualized.
A lambda expression is a method without a name, access-specifier or return value declaration.

Lambda expression add functional programming features to java. This simplifies and greatly reduces the amount of code written to achieve tasks.

A functional interface is an interface that contains only one abstract method. Then main advantage of it is that it can be used to refer to a lambda expression.

2.      New Stream API
Stream represents a flow of objects on which operations can be performed. Primary aim of streams is to make the operations easy on collections.

The newly added Stream api is available in java.util.Stream package for creating and working with Streams.
It supports pipeline operations on data and is optimized for Lambda expressions.

3.      New java.util.function package
This new package defines number of functional interfaces that provide additional support for lambda expressions.

Predicates and Functions

A predicate is a function with a single argument that returns a boolean value.
Functions are similar to Predicates, but functions return an object as a result.

Both predicates and functions are useful to evaluate lambda expressions.

4.      Interface default methods
Traditionally, interfaces contain only constants and method signatures. They cannot contain method implementations.
Beginning JDK 8, it is possible to define default implementation for a method in an interface. These methods are called default methods.
A default method is declared using a keyword “default” and it contains a method body.

A default method is available to all implementing classes of the interface. If the implementation class wants to use it, it can use it or it can ignore the default implementation and create its own implementation.

5.      New Date Time api
A new Joda Time api was introduced in JDK 8 with the package java.time.

MetaSpace:

With JDK8, the permGen Space has been removed. So where will the metadata information be stored now? This metadata is now stored in a native memory are called as "MetaSpace". This memory is not a contiguous Java Heap memory. It allows for improvements over PermGen space in Garbage collection, auto tuning, concurrent de-allocation of metadata.

Difference between PermGen space and MetaSpace.

PermGen SpaceMetaSpace
PermGen always has a fixed maximum size.Metaspace by default auto increases its size depending on the underlying OS.
Contiguous Java Heap MemoryNative Memory(provided by underlying OS)
Max size can be set using XX:MaxPermSizeMax size can be set using XX:MetaspaceSize
Comparatively ineffiecient Garbage collection. Frequent GC pauses and no concurrent deallocation.Comparatively effiecient Garbage collection. Deallocate class data concurrently and not during GC pause.






Java 8 Lambda Expressions

This article provides an introduction to lambda expression introduced in JDK 8 and explains executing them using functional interfaces.

What is Lambda expression in Java?
A Lambda expression represents an Anonymous method.
Anonymous method concept is similar to that of an Anonymous class… the difference being it implements a functional interface.
Functional interface is a new interface concept in Java 8. A functional interface can only declare one abstract method.
Lambda expressions allow the programmer to pass code in a concise manner making the code clearer and flexible.

Lambda expression syntax
A lambda expression contains:
  • A parameter list
  • An arrow symbol (->)
  • Body of the lambda containing statements

The syntax for Lambda expressions is:
(parameters) -> {statements;}

How to write simple methods as lambda expression
Here is a simple method that displays a message “Hello World”.
public void hello(){
        System.out.println("Hello World");
    }
To convert this method to a lambda expression, remove the access specifier “public”, return type “void” and method name “hello” and write it as:
() -> {System.out.println("Hello World");}

Here is another method example that adds two numbers and returns their sum:
int add(int x, int y){
        return x+y;
    }

This method can be converted to lambda expression as:
(int x, int y) -> {return x+y;}

Important points about lambda expressions
Here are some notable points regarding lambda expressions:

1) A lambda expression can have zero or more parameters.
 Here is an example of lambda expression with zero parameters:

() -> {System.out.println("Hello World");}

Here is an example of lambda expression with two parameters:
(int x, int y) -> {return x+y;}

2) If the type of the parameters can be decided by the compiler, then we can ignore adding them in the lambda expression.
(int x, int y) -> {return x+y;} // type mentioned
 (x,y) -> {return x+y;}; // type ignored

3) If there is only one parameter. the parenthesis of parameter can be omitted,
x -> {return x+10;}
String s -> s.toUpperCase()
String s -> System.out.println(s)

4) If the body has just one expression, the return keyword and curly braces can be omitted as show below:
(int x, int y) -> x + y

Calling a lambda expression
Once a lambda expression is written, it can be called and executed like a method.
For calling a lambda expression, we should create a functional interface.
Here is an example that uses functional interface to execute lambda expression:

public class FuntionalInterfaceDemo {
     interface MyInter{
        void hello();
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MyInter infVar = () -> {System.out.println("Hello World");};
        infVar.hello();
    }

}


Java 8 added lambda expressions and Stream api.
The Stream api java.util.Stream provides a forEach that can be used to loop over collection as shown below :

public class ForLoopExample {
    public static void main(String[] args) {
        List categories = Arrays.asList("Java","Dot Net","Oracle","Excel");
                // For Each loop
                for(String category: categories){ System.out.println(category); }

                // Java 8 Lambda For loop
                categories.stream().forEach(category-> System.out.println(category));
}

}