Saturday, May 20, 2017

What are wrapper classes and why do we need them?

Wrapper classes are classes for the primitive data types.

We need them because:

  1. Null can be a possible value
  2. Would get to write lot of utility methods which can make conversions easier
  3. Helps in OOP
  4. Can be used in collection as it is a class
Converting a primitive type to a wrapper class is called Autoboxing.

Converting a wrapper class object instance to a primitive type is called unboxing.

     Integer i = 12; // autoboxing

     int k = i;  //unboxing

Friday, May 19, 2017

Casting in Java

Casting in Java is the process to convert one data type to another.

An example of casting can be like:

long c = 8L;
int a = c;

Casting can be broadly classified into two types:

1. Implicit Casting: It is done by the compiler
2. Explicit Casting: It is done by code

Eg:

    long c = 8L;
    int a = c; //implicit casting
    int b = (int) c; //explicit cast




Thursday, May 18, 2017

Iterate a Map

In the following program we can see a few different ways to iterate a map:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class MapExample {


public static void main(String args[]){

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("One", 1);
map.put("Three",3);
map.put("Two", 2);

ArrayList<String> arr = new ArrayList<String>();
arr.add("a");
arr.add("b");
arr.add("c");

iterateUsingEntrySet(map);
iterateUsingLambda(map);
iterateUsingIteratorAndEntry(map);
iterateUsingKeySetAndForeach(map);
iterateUsingStreamAPI(map);

}

public static void iterateUsingEntrySet(Map<String, Integer> map){
System.out.println("Using Entry Set");
for (Map.Entry<String, Integer> entry : map.entrySet()){
System.out.println(entry.getKey() + ":" + entry.getValue());
}

}

public static void iterateUsingLambda(Map<String, Integer> map){
System.out.println("Using Lambda Expression");
map.forEach((k,v) -> System.out.println(k + ":" + v));
}

public static void iterateUsingIteratorAndEntry(Map<String, Integer> map){

Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
System.out.println("Using Iterator and Map Entry");
while(iterator.hasNext()){
Map.Entry<String, Integer> pair = iterator.next();
System.out.println(pair.getKey() + ":" + pair.getValue());
}

}

public static void iterateUsingKeySetAndForeach(Map<String, Integer> map){
System.out.println("Using KeySet and for each");
for (String key : map.keySet()) {
System.out.println(key + ":" + map.get(key));
}

}

public static void iterateUsingStreamAPI(Map<String, Integer> map){
System.out.println("Using Stream API");
map.entrySet().stream().forEach(e-> System.out.println(e.getKey()+ ":" + e.getValue()));
}

public static void iterateKeys(Map<String, Integer> map){
System.out.println("Iterating Keys");
for (String key : map.keySet()){
System.out.println(key);
}
}


}