Showing posts with label J2SE. Show all posts

Exception Handling with Method Overriding in Java


In our day to day programming we use method overriding widely. Have you ever considered how exception handling rule works in method overriding? Lets see how it works in Java with example. 
 
RULE 1. Super class method does not declare any exception in its method signature.
If super class method does not declared any exception in its method signature then sub-class's over ridden method can not declare any checked exception however it can declare any unchecked/RuntimeException. Following example demonstrate the first rule of exception. 
 
Source code (SuperClassExceptionRule1.java)
/**
 * Example of SuperClassExceptionRule1 in java.
 * @author javaQuery
 * @date 2021-09-07
 * @Github: https://github.com/javaquery/Examples
 */
public class SuperClassExceptionRule1 {

    public void methodWithoutException(){
        System.out.println("methodWithoutException");
    }

    public static void main(String[] args) {
        System.out.printf("SuperClassExceptionRule1");
    }

    public class ChildClassExceptionRule1 extends SuperClassExceptionRule1{

//        Compile time error when tried to throw checked exception
//        @Override
//        public void methodWithoutException() throws Exception{
//            super.methodWithoutException();
//        }

        // Allowed to throw unchecked exception (i.e Any RuntimeException)
        @Override
        public void methodWithoutException() throws RuntimeException{
            super.methodWithoutException();
        }
    }
}
RULE 2. Super class method declared exception in its method signature.
If super class method declared any exception in its method signature then sub-class's over ridden method can declare same exception, any child/sub-class exception or no exception however you can not declare parent exception. Following example demonstrate the second rule of exception.
 
Source code (SuperClassExceptionRule2.java)
/**
 * Example of SuperClassExceptionRule2 in java.
 * @author javaQuery
 * @date 2021-09-07
 * @Github: https://github.com/javaquery/Examples
 */
public class SuperClassExceptionRule2 {

    public void methodWithException() throws IllegalArgumentException{
        System.out.println("methodWithException");
    }

    public static void main(String[] args) {
        System.out.printf("SuperClassExceptionRule2");
    }

    public class ChildClassExceptionRule2 extends SuperClassExceptionRule2 {

//        Compile time error when tried to throw parent exception
//        @Override
//        public void methodWithException() throws Exception{
//            super.methodWithException();
//        }

        // Allowed to throw original exception (IllegalArgumentException)
        // or child exception of IllegalArgumentException
        @Override
        public void methodWithException() throws NumberFormatException{
            super.methodWithException();
        }
    }

    public class ChildClassExceptionRule22 extends SuperClassExceptionRule2 {

        // Allowed not to throw any exception
        @Override
        public void methodWithException(){
            super.methodWithException();
        }
    }
}

How to create immutable class in Java?

immutable class

Immutable Object
Once created its state can not be altered.
String is good example of Immutable class in Java which you use in your day-to-day programming.

Read: Why String is immutable in Java?

Most important benefit of immutable class is, It provides thread safety so you don't have to worry about its value getting changed in multi-threaded environment. Also immutable class with valid hashCode() and equals() method is good choice for Map key.

Points to be taken care while creating immutable class.

  • Class must be declared as final so it can not be extended. i.e public final class ClassName.
  • All variables/critical methods should be private so it can not be accessed outside of class. i.e private int x;.
  • Make all mutable variables final so it can not be changed after initialization.
    i.e private final int x;.
  • Initialize all variables via constructor only by performing deep copy. (follow example)
  • Do not provide setter methods for variables. i.e public void setX(int x) {this.x = x;}
  • Return cloned object/variable in getter method rather returning actual object. (follow example)

Source code (ImmutableClassLatLon.java)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Example of Immutable class in java.
 * @author javaQuery
 * @date 2019-12-10
 * @Github: https://github.com/javaquery/Examples
 */
public final class ImmutableClassLatLon {
    private final double latitude;
    private final double longitude;
    private final List<String> labels;

    /**
     * @param latitude
     * @param longitude
     * @param labels
     */
    public ImmutableClassLatLon(double latitude, double longitude, List<String> labels) {
        this.latitude = latitude;
        this.longitude = longitude;
        if(labels != null && !labels.isEmpty()){
            this.labels = new ArrayList<>(labels);
        }else{
            this.labels = null;
        }
    }

    /**
     * Will return new copy of List rather returning reference to current list.
     * @return
     */
    public List<String> getLabels() {
        return labels != null ? new ArrayList<>(labels) : null;
    }

    /**
     * Get new object of ImmutableClassLatLon with updated label.
     * @param label
     * @return ImmutableClassLatLon
     */
    public ImmutableClassLatLon addLabel(String label){
        List<String> temporary = new ArrayList<>();
        if(labels != null && !labels.isEmpty()){
            temporary.addAll(labels);
        }
        temporary.add(label);
        return new ImmutableClassLatLon(latitude, longitude, temporary);
    }

    public static void main(String[] args) {
        ImmutableClassLatLon classLatLon = new ImmutableClassLatLon(23.0225, 72.5714, Arrays.asList("India"));
        System.out.println("classLatLon address: " + classLatLon);

        System.out.println("\n- classLatLon getLabels and add label -");
        System.out.println("classLatLon labels before: " + classLatLon.getLabels());
        /* classLatLon.getLabels() will return new copy of List rather returning reference to current list */
        List<String> localLables = classLatLon.getLabels();
        localLables.add("Hindi");
        System.out.println("localLables: " + localLables);
        System.out.println("classLatLon labels after: " + classLatLon.getLabels());

        System.out.println("\n- add new label to classLatLon -");
        System.out.println("classLatLon add label before: " + classLatLon.getLabels());
        /* When new label is added it will return new object of ImmutableClassLatLon rather updating current object's list */
        ImmutableClassLatLon classLatLonNewLabel = classLatLon.addLabel("Asia");
        System.out.println("classLatLon add label after: " + classLatLon.getLabels());
        System.out.println("classLatLonNewLabel address: " + classLatLonNewLabel);
        System.out.println("classLatLonNewLabel labels: " + classLatLonNewLabel.getLabels());

    }
}
Output
As you can see after initialization of ImmutableClassLatLon@36baf30c, user can not change its state even if we provided operation on it.
classLatLon address: com.javaquery.core.immutable.ImmutableClassLatLon@36baf30c

- classLatLon getLabels and add label -
classLatLon labels before: [India]
localLables: [India, Hindi]
classLatLon labels after: [India]

- add new label to classLatLon -
classLatLon add label before: [India]
classLatLon add label after: [India]
classLatLonNewLabel address: com.javaquery.core.immutable.ImmutableClassLatLon@7a81197d
classLatLonNewLabel labels: [India, Asia]
Further Reading
What is the difference between final and effectively final?
How HashMap works internally in Java?
How LinkedHashMap works internally in Java?

How LinkedHashMap works internally in Java?

LinkedHashMap implemented using the HashMap. So before we begin to understand How LinkedHashMap works you should first read How HashMap works internally in Java?

We will understand part of code that defers from HashMap and supports LinkedHashMap implementation.

LinkedHasMap#Entry
Entry class in LinkedHashMap extends Node class of HashMap and contains two more variable before and after to hold the before and after references of Entry object.
static class Entry<K,V> extends HashMap.Node<K,V> {
    Entry<K,V> before, after;
    Entry(int hash, K key, V value, Node<K,V> next) {
        super(hash, key, value, next);
    }
}
Now when you put(key, value) pair in LinkedHashMap, it creates new node object by calling newNode(..) method. In newNode(..) method linkNodeLast(LinkedHashMap.Entry<K,V> p) method is called which is responsible for pointing head and tail element in LinkedHashMap and also set reference of before and after objects.
Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {
    LinkedHashMap.Entry<K,V> p = new LinkedHashMap.Entry<K,V>(hash, key, value, e);
    linkNodeLast(p);
    return p;
}

private void linkNodeLast(LinkedHashMap.Entry<K,V> p) {
    LinkedHashMap.Entry<K,V> last = tail;
    tail = p;
    if (last == null)
        head = p;
    else {
        p.before = last;
        last.after = p;
    }
}
Following image shows graphical representation of How LinkedHashMap works internally.


Lets understand LinkedHashMap implementation using real Java Program to make everything clear.

Source code (LinkedHashMapExample.java)
Note: Check value of before, after and next to understand example.
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * LinkedHashMap Example.
 * @author javaQuery
 * @date 2019-11-29
 * @Github: https://github.com/javaquery/Examples
 */
public class LinkedHashMapExample {
    public static void main(String[] args) {
        Map<String, String> map = new LinkedHashMap<>();

        /* Check value of before, after and next to understand example */
        map.put("AaAaAa", "JJJ");
        /**
         * Current bucket data visualization
         *
         * bucket-index: 2
         * EntryObject1 [before = null, hash = 123, key = AaAaAa, value = JJJ, next = null, after = null]
         */

        map.put("xyz", "KKK");
        /**
         * Current bucket data visualization
         *
         * bucket-index: 2
         * EntryObject1 [before = null, hash = 123, key = AaAaAa, value = JJJ, next = null, after = EntryObject2]
         *
         * bucket-index: 11
         * EntryObject2 [before = EntryObject1, hash = 456, key = xyz, value = KKK, next = null, after = null]
         */

        /* since hashcode of 'AaAaBB' is same as 'AaAaAa' so it be added at 2nd index in bucket */
        map.put("AaAaBB", "LLL");
        /**
         * Current bucket data visualization
         *
         * bucket-index: 2
         * [
         *  EntryObject1 [before = null, hash = 123, key = AaAaAa, value = JJJ, next = EntryObject3, after = EntryObject2]
         *  EntryObject3 [before = EntryObject2, hash = 123, key = AaAaBB, value = LLL, next = null, after = null]
         * ]
         *
         * bucket-index: 11
         * EntryObject2 [before = EntryObject1, hash = 456, key = xyz, value = KKK, next = null, after = EntryObject3]
         */
    }
}
Above program can be graphically represented as follows.


References
How HashMap works internally in Java?
Popular Map interview questions in Java

Popular Map interview questions in Java

Question: Why Map interface does not extends Collection interface?
Answer: Map is (key, value) pair not a collection of one type of values so it does not extends Collection interface. Collection interface accept single object via add(E e) but Map interface requires key, value pair in method put(K key, V value)

Question: Does Map accept `null` as key?
Answer: HashMap and LinkedHashMap accepts null key but TreeMap will throws NullPointerException. HashMap stores null key at 0th index in bucket.

Question: Does Map accept `null` values?
Answer: You can have n null values.

Question: What is the initial capacity of HashMap?
Answer: 16. DEFAULT_INITIAL_CAPACITY = (1 << 4)

Question: What is the maximum capacity of HashMap?
Answer: 1073741824. MAXIMUM_CAPACITY = ( 1 << 30)

Question: Does HashMap maintain insertion order?
Answer: No

Question: Is HashMap synchronized?
Question: Is HashMap thread-safe?
Answer: No

Question: How to synchronize Map?
Answer: Using Collections.synchronizedMap(map), best practice Map m = Collections.synchronizedMap(new HashMap(...));

Question: How to avoid concurrent modification exception?
Answer: Synchronize Map using Map m = Collections.synchronizedMap(new HashMap(...)); or Map n = new ConcurrentHashMap();

Question: How HashMap works internally in Java?
Answer: To understand How HashMap works internally read the article https://www.javaquery.com/2019/11/how-hashmap-works-internally-in-java.html

Question: What happens when you put same key again in HashMap?
Answer: When you put(existing-key, value) in HashMap, it will replace old value with new value. And returns old value.
Map<String, String&gt; map = new HashMap<&gt;();
map.put("a", "x");
String oldValue = map.put("a", "y");
System.out.println(oldValue);
//output: x

Question: Can we store duplicate key in HashMap?
Answer: No

Question: Can we store duplicate value in HashMap?
Answer: Yes.

Question: What is Hash code/key collision?
Answer: When two same or different hash code of key generates same index of bucket location by performing bitwise AND is called hash code/key collision. In this situation HashMap forms linked list at given bucket location (index).

For example "AaAaAa".hashCode() and "AaAaBB".hashCode() generates same hash code.

Question: How HashMap handles Hash code/key collision?
Question: What will happens if two objects have same hash code?
Answer: It forms linked list at bucket location.

Question: Why String, Integer and other wrapper classes are good choice for HashMap key?
Answer: String, Integer and other wrapper classes are immutable so its best choice to use it as key. Why String is immutable in Java?

Question: Can we use mutable key in HashMap?
Answer: Yes, You can use mutable key but its not good choice because it'll fail to retrieve correct value in get(key).

Question: Can we use our own custom object/class as key in HashMap?
Answer: Yes, You can use your custom object as key in HashMap but its necessary to consider immutability of that object and also implementing hashCode() and equals() method in your class.

Question: How HashMap is improved in Java 8?
Answer: Prior to Java 8, HashMap forms linked list in case of hash collision. Now from Java 8 when hash collision occurs and it hits following threshold TREEIFY_THRESHOLD = 8 and MIN_TREEIFY_CAPACITY = 64 then it uses TreeNode to store Entry object to improve HashMap get performance.
Why HashMap resize when it hits TREEIFY_THRESHOLD value which is not required?

Question: Which tree stucture is used in Java 8 to improve performance of HashMap?
Answer: red-black tree structure is used to improce performance of HashMap.

Question: How LinkedHashMap works internally in Java?
Answer: To understand How LinkedHashMap works internally read the article https://www.javaquery.com/2019/12/how-linkedhashmap-works-internally-in.html

How HashMap works internally in Java?

HashMap is one of the implementation of java.util.Map interface. We will understand how it internally stores (put) and retrieve (get) values. HashMap uses array known as bucket/table to store (key, value) pair.

This is one of the popular question in Java Interviews, lets understand how it works.

Instantiation: How to create HashMap object?
There are 3 different ways you instantiate HashMap

  1. new HashMap() - It will create HashMap with default capacity of 16 and default load factor 0.75f.
  2. new HashMap(int initialCapacity) - You can provide the initial capacity of HashMap and default load factor 0.75f is used.
  3. new HashMap(int initialCapacity, float loadFactor) - You can provide both initial capacity and load factor.
Note: We will consider HashMap with default capacity and load factor for explanation of this article.

Understanding implementation of HashMap
I extracted Node class (inner class) from HashMap which implements sub-interface Entry of Map interface. Node class plays important role in implementation of HashMap. Every (key, value) pair in HashMap will be stored as Entry object using Node class implementation.

Node class holds - hash code of key, key, value and `next` is used to store next element (node) reference in case of hash code/key collision. We'll understand hash code/key collision later in this article.
static class Node<K,V> implements Map.Entry<K,V> {
    final int hash; // hash code of key
    final K key; // the key
    V value; // the value to put
    Node<K,V> next; // next element(node) in case of hash code/key collision 

    Node(int hash, K key, V value, Node<K,V> next) {...}
    ...
    ...
}

What happens when you put(K key, V value) in HashMap?
When you put (key, value) pair in HashMap, it generates hash of key by calling hashCode() method of key and follows these steps...

  • put#1.1: Create the bucket (array) of Node<K, V>[] with default capacity or given capacity if not initialized. 
    • In case of bucket (array) is full then it increases capacity by twice the current capacity and transfer all data to new bucket (array). (i.e default capacity [16] > [32] > [64] ...)
  • put#1.2: Now it generates bucket location (array-index) by performing bitwise AND on current capacity of bucket and hash code of key
    /**
     * i = index to store (key, pair) in bucket (array)
     * n = size of bucket (array)
     * hash = hash code of key
     */
    int i = (n - 1) & hash;
    
  • put#1.3: Fetch node (element) from bucket using generated location (index).
    • put#1.3.1: no element found - insert given key, pair in form of Node object (Entry object).
    • put#1.3.2: element found at that location (index) - its the case of Hash code/key collision.
      • put#1.3.2.1: Now it'll compare key of existing node (element) with newly given key. If both the keys are same then it'll replace current Node's value with new value.
      • put#1.3.2.2: If both the keys are different then it forms linked list at the bucket location (index). Current node's next variable will be assigned to reference of newly given Node (key, value). 


What happens when you get(Object key) in HashMap?
When you try to get value using key, it generates hash of key by calling hashCode() method of key and follows these steps...

  • get#1.1: Generates bucket location (array-index) by performing bitwise AND on current capacity of bucket and hash code of key.
  • get#1.2: Find the Entry(Node) object from that bucket index.
    • get#1.2.1: No Entry object found - returns null.
    • get#1.2.2: Entry object found from bucket - It will compare provided hash of key, key and calls equals() method of key with Entry object found from bucket. 
      • get#1.2.2.1: If everything matched then it returns the Entry object. 
      • get#1.2.2.2: If not matched then it check linked list formed at that bucket location (has `next` element) then do the same check as in get#1.2.2 until it find the correct Entry object from linked list.
Now lets discuss question can be asked in interview related to implementation.

What is the initial capcity and load factor of HashMap?
Initial capacity of HashMap is 16 and load factor is 0.75f.

How HashMap stores data in bucket (array/table)?
Its important to remember that HashMap stores not just hash code of key in Array. It stores hash code, key, value and `next` as Entry object in Array.

What is Hash code/key collision?
When two same or different hash code of key generates same index of bucket location by performing bitwise AND is called hash code/key collision. In this situation HashMap forms linked list at given bucket location (index).

For example "AaAaAa".hashCode() and "AaAaBB".hashCode() generates same hash code.

How HashMap handles Hash code/key collision?
What will happend if two objects have same hash code?
It forms linked list at bucket location.

How HashMap will retrieve value when two keys have same hash code?
Linked list formed at bucket location when two keys have same hash code so it'll travese through all linked list node until it find the correct key and equals method of key retruns true. Read get1.2.2 for complete understanding.

Where does HashMap stores null key?
null key will be stored at 0th index of bucket.

Why String, Integer and other wrapper classesare good choice for HashMap key?
String, Integer and other wrapper classes are immutable so its best choice to use it as key. Why String is immutable in Java?

Can we use mutable key in HashMap?
Yes, You can use mutable key but its not good choice because it'll fail to retrive correct value in get(key).

Can we use our own custom object as key in HashMap?
Yes, You can use your custom object as key in HashMap but its necessary to consider immutablity of that object and also implementing hashCode() and equals() method in your class.

How HashMap is improved in Java 8?
Prior to Java 8, HashMap forms linked list in case of hash collision. Now from Java 8 when hash collision occurs and it hits following threshold TREEIFY_THRESHOLD = 8 and MIN_TREEIFY_CAPACITY = 64 then it uses TreeNode to store Entry object to improve HashMap get performance.
Why HashMap resize when it hits TREEIFY_THRESHOLD value which is not required?

Which tree stucture is used in Java 8 to improve performance of HashMap?
red-black tree structure is used to improce performance of HashMap.

References
Popular Map interview questions in Java
How LinkedHashMap works internally in Java?

What is Abstract class in Java and popular interview questions?

What is Abstract Class?
An abstract class is a class that is incomplete, or to be considered incomplete.

You can declare abstract methods for which non abstract subclass has to provide implementation or it'll give compile-time error. "Methods that are declared but not yet implemented."

Also you can provide method implementation in abstract class itself. It can be used from subclass. You can override these method in its subclass.

Source code (Mobile.java)
import java.util.Date;
public abstract class Mobile {

    /**
     * Sub class has to provide implementation for method `call()`
     */ 
    public abstract void call();

    /**
     * Sub class has to provide implementation for method `sms()`
     */ 
    public abstract void sms();

    /**
     * We've provided implementation for current time.
     */
    public Date currentTime(){
     return new Date();
    }
}
Source code (SmartMobile.java)
public class SmartMobile extends Mobile{
 
    public void call(){
     // provide implementation
    }

    public void sms(){
     // provide implementation
    }
}
Source code (Main.java)
public class Main(){
    public static void main(String[] args){
     /** You can not instantiate abstract class. 
      * Following line will cause Compile-Time error 
      */
     // Mobile mobile = new Mobile();

     Mobile smartMobile = new SmartMobile();
    }
}

Now lets discuss behavior of abstract class via question-answer. These are the popular abstract class interview questions .

Question: Can we instantiate abstract class?
Answer: No. We can not instantiate abstract class. Its restricted by Java.

Question: Why does abstract class have constructor if we can not instantiate? 
Answer: Constructor in abstract class used to initialize properties/fields of abstract class via not abstract sub-class.

Question: When constructor of abstract class called?
Answer: When sub-class instantiated, constructor of abstract class is called.

Question: Can we mark constructor as abstract?
Answer: No

Question: Is it compulsory for abstract class to have at least one abstract method?
Answer: No its not compulsory. You can create abstract class with or without abstract methods.

Question: Can we declare abstract method as private? 
Answer: No. If abstract method is private then its not visible/accessible in its sub-class so it can not provide its implementation. However you can make abstract method protected.

Question: Why final and abstract can not be used at a time? 
Answer: When class or method marked with final means value or implementation provided and you don't want it to be changed while abstract means implementation asked to provide.

Simply it contradicts with each other.

Question: Can we declare abstract class or method as static?
Answer: No. static can be called without creating object and it contains implementation or value. abstract means implementation asked to provide. Its same as final.

Simply it contradicts with each other.

Question: Can we declare inner class as abstract?
Answer: Yes

Question: Can abstract method include throws in its declaration?
Answer: Yes

Question: Can we mark abstract method as synchronized?
Answer: No. However sub-class which override the method can be synchronized.
public abstract class Demo{
    public abstract void test();
}

public class DemoImpl extends Demo{
    @Override
    public synchronized void test(){
        //implementation
    }
}

Question: Can we use abstract class as member of another abstract class?
Answer: Yes. Its same as declaring other class as member(variable).

Reference
Difference between Abstract class and Interface in Java

Access modifiers in Java

Access modifiers in Java define the scope of class, constructor, methods and variable.

Why access modifiers?
The whole concept of access modifier is "What you want to expose from class".

There are total four access modifier public, protected, default and private in Java.

public - As name suggest any class, constructor, method and variable marked as public can be accessed within class, from sub/child-class, within same package or out of package. In other word "Can be accessed globally".

protected - Any Inner class, constructor, method and variable marked as protected can be accessed within class, from sub/child-class created in same package or different package, via object creation in same package.

You can not access protected Inner class, constructor, method and variable via object created in different package.

default - No access specifier defined for any Inner class, constructor, method and variable considered as default access level. It can be accessed within class, from sub/child-class created in same package only.

Default class, inner class, constructor, method and variables are not visible out side of package.

private - As name suggest any Inner class, constructor, method and variable marked as private can be accessed within same class only.


All access modifier's scope is given in following table.

Access Modifier same class same package
via sub-class/object
sub class in
different package
outside
the package
public Yes Yes Yes Yes
protected Yes Yes Yes No
default Yes Yes No No
private Yes No No No

What is runtime polymorphism in Java?

One way you can achieve Runtime polymorphism in java is by Method Overiding. Lets check the code followed by explanation.

Source code (Animal.java)
/**
 * @author javaQuery
 * @date 7th November, 2017
 * @Github: https://github.com/javaquery/Examples
 */
public class Animal {
    public void run(){
        System.out.println("Animal is running...");
    }
}
Source code (Dog.java)
/**
 * @author javaQuery
 * @date 7th November, 2017
 * @Github: https://github.com/javaquery/Examples
 */
public class Dog extends Animal{

    @Override
    public void run() {
        System.out.println("Dog is running...");
    }
}
Source code (Cat.java)
/**
 * @author javaQuery
 * @date 7th November, 2017
 * @Github: https://github.com/javaquery/Examples
 */
public class Cat extends Animal{

    @Override
    public void run() {
        System.out.println("Cat is running...");
    }
}
Source code (Horse.java)
/**
 * @author javaQuery
 * @date 7th November, 2017
 * @Github: https://github.com/javaquery/Examples
 */
public class Horse extends Animal{
}
Source code (RuntimePolymorphismExample.java)
/**
 * Example demonstrate Runtime Polymorphism.
 * 
 * @author javaQuery
 * @date 7th November, 2017
 * @Github: https://github.com/javaquery/Examples
 */
public class RuntimePolymorphismExample {
    public static void main(String[] args) {
        // super-class
        Animal animal = new Animal();
        animal.run();
        
        /***********************************************/
        /* sub-class `Dog` */
        /***********************************************/
        Dog dog = new Dog();
        dog.run();
        
        animal = dog;
        /**
         * animal.run()
         * It will call referenced object's `run()` method.
         * In this case, object of `Dog` class is referred.
         */
        animal.run(); // runtime polymorphism
        
        
        /***********************************************/
        /* sub-class `Cat` */
        /***********************************************/
        animal = new Cat();
        
         /**
         * animal.run()
         * It will call referenced object's `run()` method.
         * In this case, object of `Cat` class is referred.
         */
        animal.run(); // runtime polymorphism
        
        
        /***********************************************/
        /* sub-class `Horse` */
        /***********************************************/
        animal = new Horse();
        
         /**
         * animal.run()
         * It will call referenced object's `run()` method.
         * However in this case, object of `Horse` doesn't contain implementation of `run()` so method
         * from the super-class `Animal#run` will be called.
         */
        animal.run(); // runtime polymorphism
    }
}
Output
Animal is running...
Dog is running...
Dog is running...
Cat is running...
Animal is running...

Run Time Polymorphism in Java

Constraints validation for user inputs (javax.validation.constraints)

User input validation is common part of any application. JBoss developers made it easy to validate inputs using Java Bean Validation framework.

Bean Validation 2.0 (http://beanvalidation.orgJSR 380)
We will be using Bean Validation framework 2.0 for the example. Its certified implementation is Hibernate Validator 6.0.1.Final or above. Framework 2.0 require Java 8 or higher version.

Source code (User.java)
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;

/**
 * @author javaQuery
 * @since 2018-02-24
 * @github: https://github.com/javaquery/Examples
 */
public class User {

    @NotEmpty(message = "firstName can not be empty")
    @Size(min = 2, max = 20, message = "firstName length must be between 2 and 20")
    private String firstName;

    @NotEmpty(message = "lastName can not be empty")
    @Size(min = 2, max = 20, message = "lastName length must be between 2 and 20")
    private String lastName;

    @NotEmpty(message = "nickNames can not be empty")
    private List<@Size(min = 2, message = "nickName length must be greater than 2") String> nickNames;

    @Email
    private String email;

    @NotEmpty(message = "password can not be empty")
    @Size(min = 6, message = "password length must be at least 6 character")
    private String password;

    // getter-setter
}
  • @NotEmpty - We are using it to check string can not be empty. Can be used with collection, map or array.
  • @Size - We are using it to check the length of string. Can be used with collection, map or array.
  • @Email - The string has to be a well-formed email address.
There are other annotations like @NotNull, @Min, @Max@Past, @Future, @PastOrPresent, @FutureOrPresent, etc... Complete list of annotations is available on Bean Validation specification.

Source code (ValidatorFactoryExample.java)
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

/**
 * @author javaQuery
 * @since 2018-02-24
 * @github: https://github.com/javaquery/Examples
 */
public class ValidatorFactoryExample {

    public static void main(String[] args) {
        User user = new User();
        user.setFirstName("Vicky");
        user.setEmail("not-an-email");
        user.setNickNames(Arrays.asList("vicks", "v"));
        user.setPassword("1234567");
        
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        /* validate object and get constraints failed */
        Set<ConstraintViolation<User>> violations = validator.validate(user);
        
        for (ConstraintViolation<User> violation : violations) {
            System.err.println(violation.getMessage());
        }
    }
}

Output
nick name lenght must be greater than 2
lastName can not be empty
must be a well-formed email address

Other frameworks like Spring triggers validation using annotation so you don't have to validate bean on your own like we did using ValidatorFactory.

Similar
Passing and validating RequestParam in spring-boot rest api

Autoboxing and unboxing conversions in Java

Autoboxing and unboxing in java

Autoboxing and Unboxing
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called Unboxing.

Autoboxing
Converting primitive values (int, long, float, double...) into an object of the corresponding wrapper class (Integer, Long, Float, Double...) is called autoboxing. The compiler applies autoboxing when a primitive value is:

  • Passed as a parameter to a method that expects an object of the corresponding wrapper class.
  • Assigned to a variable of the corresponding wrapper class.

Autoboxing Example
The given code
/* Passed as a parameter to a method that expects an object of the corresponding wrapper class. */
List<Integer> listIntegers = new ArrayList<>();
for (int i = 1; i < 10; i++){
 listIntegers.add(i); 
}
=====
/* Assigned to a variable of the corresponding wrapper class. */
int x = 10;
Integer y = x;
will be converted by compiler as follow, Here i is autoboxed by Integer.valueOf(i).
List<Integer> listIntegers = new ArrayList<>();
for (int i = 1; i < 10; i++){
 listIntegers.add(Integer.valueOf(i));
}
=====
int x = 10;
Integer y = Interger.valueOf(x);

Unboxing
Converting an object of a wrapper type (Integer, Long, Float, Double...) to its corresponding primitive (int, long, float, double...) value is called unboxing. The compilere applied unboxing when an object of a wrapper class is:

  • Passed as a parameter to a method that expects a value of the corresponding primitive type.
  • Assigned to a variable of the corresponding primitive type.

Unboxing Example
The given code
/* Assigned to a variable of the corresponding primitive type. */
int sum = 0;
for (Integer i : listIntegers){
 if (i % 2 == 0){
  sum += i;
 }    
}
=====
/* Passed as a parameter to a method that expects a value of the corresponding primitive type. */
Integer a = new Integer(10);
Integer b = new Integer(10);

int summation = sum(a, b);

public int sum(int x, int y){
  return x + y;
}
will be converted by compiler as follow because remainder (%) and unary plus (+=) don't apply on wrapper class Integer. Here i % 2 unboxed by i.intValue() % 2 and sum += i unboxed by sum += i.intValue().
int sum = 0;
for (Integer i : listIntegers){
 if (i.intValue() % 2 == 0){
  sum += i.intValue();
 }    
}
=====
Integer a = new Integer(10);
Integer b = new Integer(10);

int summation = sum(a.intValue(), b.intValue());

public int sum(int x, int y){
  return x + y;
}