Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Friday, March 13, 2020

One of the correct Singleton Class implementation

Here is a correct way of implementation:
class Singleton {
 private volatile static Singleton _instance;//do not initialize here

 private Singleton() { //mark it private to prevent Singleton object to be instantiated from outside

 }
 
 public static Singleton getInstance() {
  if (_instance == null) { 
   synchronized (Singleton.class) { 
    if (_instance == null) { 
     _instance = new Singleton();
    }
   }
  }
 return _instance;
}

Common mistakes to avoid while coding in Java

During my development experience I have gone through multiple stages of exceptions and errors. I will list down all the mistakes I have done in my development experience from the beginning of my career. I think it will be very helpful to all of those who faced same kind of issues.

1. Use of integer, long, floats: While calculating some result with integer array and trying to get the sum, often it might happen that the result sum exceeded the integer.max_val. So in this case I recommend to use long.

we know if we do float operation with integer variable we might loose the decimal point value. hence we need to be very careful while doing such kind of computation.

2. NULL pointer exception: Handling null pointer exception is mandatory in 99% cases BUT we might miss some critical bugs in future if we use if-else blocks instead of assert statement. So recommended is to use assert statement if you don't want the value to be null.

3. Trying to overuse !StringUtils.isEmpty() kind of syntax. Its always better to use StringUtils.isNotEmpty() since it gives better readability. We often spend our time figuring out issues in code where we missed "!" before StringUtils.isEmpty().


Monday, June 27, 2016

Benefits of immutable objects in Java

Benefits of immutable objects in Java are:
1. Reference caching: References to immutable objects can be cached since there state is not going to change.throughout the program.
2. Easier to parallize: Since there are no conflicts between 2 objects, we can easily run operations in parallel.
3. Thread safe: Immutable objects are thread-safe so you will not have any synchronisation issues.
4. Hash key: Immutable objects are best as key Hash data structures.(Map keys and Set elements) since these typically do not change once created.
5. Easier to write code.

Sunday, May 1, 2016

Producer-Consumer with java.util.concurrent.locks.Lock

In my earlier post I have given odd-even printing in sequence using 2 threads.(Similar to producer consumer). In this post I have given implementation of producer consumer problem with java.util.concurrent.locks.Lock

Code:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MyPCWithLock {
public static void main(String[] args) {
SharedResourceMgr srm=new SharedResourceMgr();
Thread t1=new Thread(new ProducerWithLock(srm));
Thread t2=new Thread(new ConsumerWithLock(srm));
t1.start();
t2.start();
}
}

class SharedResourceMgr{
Lock lock=new ReentrantLock();;
Condition condition=lock.newCondition();
boolean produced=false;
public void consume(){
lock.lock();
try{
while(!produced){
condition.await();
}
System.out.println("Consumed..");
produced=false;
condition.signalAll();
}catch (Exception e) {
// TODO: handle exception
}finally{
lock.unlock();
}
}

public void produce(){
lock.lock();
try{
while(produced){
condition.await();
}
System.out.println("Produced..");
produced=true;
condition.signalAll();//very important, it should not be notify
}catch (Exception e) {
// TODO: handle exception
}finally{
lock.unlock();
}
}

}

class ProducerWithLock implements Runnable{
SharedResourceMgr srm;
ProducerWithLock(SharedResourceMgr s){
this.srm=s;
}
@Override
public void run() {
for(int i=0;i<5;i++){
//System.out.println("P:"+i);
srm.produce();
try{
Thread.sleep(1000);
}catch(Exception ex){

}
}
}
}
class ConsumerWithLock implements Runnable{
SharedResourceMgr srm;
ConsumerWithLock(SharedResourceMgr s){
this.srm=s;
}
@Override
public void run() {
for(int i=0;i<5;i++){
//System.out.println("C:"+i);
srm.consume();
try{
Thread.sleep(1000);
}catch(Exception ex){

}
}
}
}

Output:
Produced..
Consumed..
Produced..
Consumed..
Produced..
Consumed..
Produced..
Consumed..
Produced..
Consumed..

Print Odd-Even numbers in sequence using 2 Threads

Here we have used producer-consumer implementation to achieve the results.

Producer will print the even numbers starting from 0.
Consumer will print the odd numbers starting from 1.


Code:
public class MyPC {

public static void main(String[] args) {
ResourceManager rm=new ResourceManager();
Thread c=new Thread(new Consumer(rm));
Thread p=new Thread(new Producer(rm));
p.start();
c.start();

}
}

class ResourceManager{

/* This method is for consume */
public synchronized void get(){
//while not produced, we should wait for producer to produce.
//wait will release the lock and will let producer thread to execute
while(!produced){
try{
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
System.out.println(odd);
odd+=2;
produced=false;
notify();
try{
Thread.sleep(1000);
}catch(Exception ex){

}
}
boolean produced=false;
int even=0;
int odd=1;
public synchronized void put(){
while(produced){
try{
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}

System.out.println(even);
even+=2;
produced=true;
notify();
try{
Thread.sleep(1000);
}catch(Exception ex){

}
}
}


class Producer implements Runnable{
ResourceManager rm;
Producer(ResourceManager r){
this.rm=r;
}
public void run(){
for(int i=0;i<10;i++){
rm.put();
}
}
}

class Consumer implements Runnable{
ResourceManager rm;
Consumer(ResourceManager r){
this.rm=r;
}
public void run(){
for(int i=0;i<10;i++){
rm.get();
}}
}

Output:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19


Thursday, April 14, 2016

Write async methods in Java

In the below example code you can find out how to write your own async methods and invoke it.


import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class MyAsyncUtil {

public static void main(String[] args) throws InterruptedException, ExecutionException {

System.out.println("Starting...");
ExecutorService pool = Executors.newFixedThreadPool(3);
Future<Result> future = pool.submit(new AsyncCallable("My async method"));

for(int i=0;i<10;i++){
System.out.println("cc");
}
//Compute the result
Result result = future.get();
System.out.println(result.isResult());
System.out.println(result.getResponse());
pool.shutdownNow();
System.out.println("cool");
System.out.println(pool.isShutdown());
}
}


class AsyncCallable implements Callable<Result>{

private String str;

public AsyncCallable(String str1){
this.str = str1;
}

@Override
public Result call() throws Exception {
try{

Thread.sleep(5*1000);
System.out.println(str);
System.out.println("*** End of Thread ***");
}catch(Exception ex){
//System.exit(0);
return new Result(Thread.currentThread().getName(),
false,ex);
}
return new Result(Thread.currentThread().getName(),
true, null, "PASS");
}

public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}

}


The result class is to get the result of the execution of async method.

class Result implements Cloneable{
private String threadName;
private boolean result;
private Exception thrownEx;
private Object response;

public String getThreadName() {
return threadName;
}

public void setThreadName(String threadName) {
this.threadName = threadName;
}

public boolean isResult() {
return result;
}

public void setResult(boolean result) {
this.result = result;
}

public Exception getThrownEx() {
return thrownEx;
}

public void setThrownEx(Exception thrownEx) {
this.thrownEx = thrownEx;
}

public Result(String threadName, boolean result, Exception thrownEx){
this.threadName=threadName;
this.result=result;
this.thrownEx=thrownEx;
}

public Result(String threadName, boolean result, Exception thrownEx,
Object o){
this(threadName,result,thrownEx);
this.response = o;
}

@Override
protected Result clone() throws CloneNotSupportedException {
return (Result) super.clone();
}

public Object getResponse() {
return response;
}

public void setResponse(Object response) {
this.response = response;
}
}

Tuesday, April 5, 2016

Heap Sort Utility for Generic classes

In below I have written one simple Heap Utility class for sorting any kind of comparable objects.

Comparable objects means object of class which inherit the java.lang.Comaparable class.
As for example Integer, Long, String etc.

Here is the code snippet of the utility class.

<SNIP>
/**
 * This utility class is for implementation
 * of HeapSort for any type of comparable objects
 * @author Iftikar
 *
 * @param <T>
 */
class HeapUtilTemplate<T extends Comparable<T>> {
T[] A;
int heapSize;

public HeapUtilTemplate(T[] arr1) {
this.A = arr1;
this.heapSize = arr1.length;
}
/**
* Method to sort the array using heapSort
*/
public void heapSort(){
//displayArr();
buildMaxHeap();
//displayArr();
for(int i=heapSize-1;i>0;i--){
T temp=A[i];
A[i]=A[0];
A[0]=temp;
heapSize=heapSize-1;
maxHeapify(A, 0);
}
}

public void displayArr(){

for(T i:A){
System.out.print(i+" ");
}
System.out.println();
}


/**
* Method to build the max heap
*/
public void buildMaxHeap(){

for(int i=A.length/2;i>=0;i--){
maxHeapify(A,i);
}
}


/**
* Method to Heapify(max) the array
* @param A
* @param i
*/
public void maxHeapify(T[] A, int i){
int l=left(i);
int r=right(i);
int largest=i;
if(l<heapSize && A[i].compareTo(A[l]) < 0){//A[i] < A[l]
largest=l;
}
if(r<heapSize && A[r].compareTo(A[largest])>0){//A[r]>A[largest]
largest=r;
}
if(largest!=i){
//exchange data
T temp=A[i];
A[i]=A[largest];
A[largest]=temp;
maxHeapify(A,largest);
}
}
public int parent(int i){
return i/2;
}

public int left(int i){
return 2*i+1;
}

public int right(int i){
return 2*i+2;
}
}
</SNIP>

Please comment below if the code can be made better. Your inputs are always welcome.





Monday, March 14, 2016

Why wait-notify should be called in a loop in a production environment?


From Java Documentation,

A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. While this will rarely occur in practice, applications must guard against it by testing for the condition that should have caused the thread to be awakened, and continuing to wait if the condition is not satisfied. In other words, waits should always occur in loops, like this one:
     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait(timeout);
         ... // Perform action appropriate to condition
     } 
 
Some more deatils on spurious wakeup ca be found here.
 

Tuesday, March 8, 2016

Build a Multi-Threaded framework using ThreadPool and Executor Framework

In the below example you can find out how to write multi-Threaded framework using ThreadPool and Executor Framework.

===
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ExecutorFramework {

/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {

List<MyThreadTask> opTaskList = new ArrayList<MyThreadTask>();
opTaskList.add(new MyThreadTask(new Configuration("h1")));
opTaskList.add(new MyThreadTask(new Configuration("h2")));

ExecutorService pool = Executors.newFixedThreadPool(opTaskList.size());

List<Future<TaskResult>> futures = new ArrayList<Future<TaskResult>>();
futures = pool.invokeAll(opTaskList);

try {
boolean doneAllThread = checkResults(futures);
if(doneAllThread){
System.out.println("Done all tasks..Shutting down");
pool.shutdownNow();
}
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}

public static boolean checkResults(List<Future<TaskResult>> futures)
throws InterruptedException, ExecutionException{
        boolean doneAllThread = true;
        TaskResult temp=null;
        for (Future<TaskResult> f : futures) {
            temp=f.get();
            System.out.println("Thread finished. Result - {}"+ temp);
            if(null != temp && !temp.isResult() && temp.getThrownEx() != null){
            System.out.println(temp.getThrownEx().getStackTrace());
            }
            doneAllThread &= (temp != null)?temp.isResult():false;
        }
        return doneAllThread;
    }
}


class TaskResult{

private String threadName;
private boolean result;
private Exception thrownEx;

public TaskResult(String threadName, boolean result, Exception thrownEx){
this.threadName=threadName;
this.result=result;
this.thrownEx=thrownEx;
}

public String getThreadName() {
return threadName;
}
public void setThreadName(String threadName) {
this.threadName = threadName;
}
public boolean isResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
public Exception getThrownEx() {
return thrownEx;
}
public void setThrownEx(Exception thrownEx) {
this.thrownEx = thrownEx;
}

@Override
public String toString() {
return "TaskResult [threadName=" + threadName + ", result="
+ result + ", thrownEx=" + thrownEx + "]";
}
}

class Configuration{
String hostName;

public Configuration(String hn) {
// TODO Auto-generated constructor stub
this.hostName=hn;
}

public String getHostName() {
return hostName;
}

public void setHostName(String hostName) {
this.hostName = hostName;
}

}

class MyThreadTask implements Callable<TaskResult>
{
Configuration config;
public MyThreadTask(Configuration temp)
{

this.config=temp;
}

/**
* Call method contains the actual execution flow of the thread.
*/
@Override
public TaskResult call()
throws Exception
{
try{
System.out.println("*****************************");
System.out.println("**Start of Thread of host:"+
Thread.currentThread().getName()+
this.config.getHostName());
System.out.println("*****************************");
System.out.println("Config Data:\n{}\n"+config);
System.out.println("*****************************");
System.out.println("**End of Thread of host:"+
Thread.currentThread().getName()+
config.getHostName());
System.out.println("*****************************");
}catch(Exception ex){

return new TaskResult(Thread.currentThread().getName(),
false,ex);
}
return new TaskResult(Thread.currentThread().getName(),true,null);
}
}
===

Difference between poll and remove of Queue

The difference between poll() and remove() methods is that:
remove() method will throw NoSuchElementException if the queue is empty. But poll() method will return null if Queue is empty. So we need to use these methods carefully.



Wednesday, February 24, 2016

Display a double/float data up to some decimal places?

This is a very common use case while displaying some data to users[UI]

To display a double value up to 8 decimal places, below example code can be used.

import java.text.DecimalFormat;
DecimalFormat df = new DecimalFormat("#.00000000");
df.setMaximumFractionDigits(8);
double res=(long)(2/3)
System.out.println(df.format(res));


*** "#.00000000" pattern is used to keep the numbers exactly up to 8 decimal places. If this pattern is not used then if the res=1.25, it would print 1.25


*** But the above pattern will not print the leading zero, to print that use "0.00000000"

Tuesday, February 23, 2016

Exception handling in Java

Exception handling is a most frequently used mechanism while developing applications in Java. There are 2 kinds of exceptions in an application:
1. at run time due to careless use of variable/return values some exception might come. This is called RuntimeException. Example of these kind of exceptions are: NullPointerException, DevideByZeroException, ArrayIndexOutOfBoundException etc.
2. During compile time, the application might throw some self defined exceptions for which we must to have either a try-catch block or throws in the method declaration. These time of exceptions are called Checked exceptions. Example of these kind of exceptions are: IOException, SQLException etc.


Exception Hierarchy

Here is the hierarchy for the Exception and Error conditions in Java.


                             Throwable
                              //           \\
                      Error              Exception
(Ex: OutOfMemory error)     //          \\
                            (Subclass: these    RuntimeException
                          are called Checked
                         Exception)


If you want to write a Exception for your own project extend the class Exception and handle the Exception in a separate Catch Block.

Example:

class BusinessException extends Exception{
...
}

void method1(){

try{

throw new BusinessException();

}catch(BusinessException be){

//enter Business exception handling logic here
}catch(IOException ioe){
//enter your exception handling logic here

}
}




Monday, February 22, 2016

Serialization

Say we want to save state of some object before modifying the object state. How we can save the state or in simple term value of its variables/fields?

One way is to use file and write the data into the file. For that we need our own logic. We need to follow strict ordering of reads and writes for correct manipulation of the object states[Employee in below example]. For an object which is having a huge number of variables, it becomes a tedious job to implement.

Java provides another easy way to achieve that which is called serialization. java.io.Serializable is a marker interface using which we can serialize/de-serialize one object. If the class of object implements Serializable interface then each and every values except transient will be serialized.

We might need some variables not to be serialized mainly because of security reasons. How we can prevent some variable in the Serializable Employee object to be serialized/de-serialized? Java provides transient keyword to mark one variable of an object non-serializable.

Lets take an example to understand the above concept better:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SerializationTest {

public static void main(String[] args) {
Employee e1=new Employee("James","Bond", "007");
try {
             ObjectOutputStream oout = new ObjectOutputStream(
                       new FileOutputStream("filename"));
           
             oout.writeObject(e1);
             oout.flush();
             oout.close();
           
             ObjectInputStream oin = new ObjectInputStream(
                       new FileInputStream("filename"));
           
             Object o1 = oin.readObject();
             System.out.println(o1);
           
        } catch (Exception e){
             e.printStackTrace();
        }

}

}


class Employee implements Serializable{
String firstName;
String lastName;
String empId;
transient String securityKey;

public Employee(String fname,String lname,String id) {
this.firstName=fname;
this.lastName=lname;
this.empId=id;
this.securityKey="xyz";
}

@Override
public String toString() {
return "Employee [empId=" + empId + ", firstName=" + firstName
+ ", lastName=" + lastName + ", securityKey=" + securityKey
+ "]";
}

}

Output:
Employee [empId=007, firstName=James, lastName=Bond, securityKey=null]

Note here, since securityKey is marked as transient it got initialized to its default value null after deserialization.



Saturday, February 13, 2016

Collections Basics Part 2

We will discuss some important methods in the Object class itself which is used for collections.
Below 2 methods will be discussed here.

1. boolean equals(Object o): This method is used for checking 2 objects are equal or not.

2. int hashCode(): This method is used to get the hash key [bucket in the hash table]

Say 2 objects of below A, a1 and a2 has to be added into some Set. How JVM will make sure 2 objects are not duplicate of each other? JVM will use the equals method to decide this.

Example:
======
class A{

int i;

A(int in){
this.i=in;
}

public boolean equals(Object o){
if(o != null && o instanceof A && ((A) o).getI()==this.i){

return true;
}
return false;
}

public int hashCode(){

return i%10001;
}

int getI(){
return i;
}

void setI(int in){
this.i=in;
}
}
======

But is equals method sufficient for 2 objects to be equal? The answer is no. Here both the object should have same hashCode returned by the int hashCode()
This hashCode() method is used for bucketing in Hash implementations of Java e.g. HashMap, Hashtable, HashSet.

So for the above a1 and a2 objects, below checks are followed to check equal or not.

1. if a1 and a2 return same hashCode
    then both are in the same bucket of hash table. Now check for equals(Object o) method.
2. else
    return false(objects are not equal)





Wednesday, February 10, 2016

Collections Basics

Collections Basics

Here we will first discuss about most basic collection data structures used in Java. Then will dive into details of Collections.

3 basic Collections interfaces.
1. List: This is used for representing set of elements with duplicate elements allowed. 
2. Set: This is used for representing set of elements with no duplicate element allowed.
3. Map: This interface is used for implementing hash table data structure with key-value pair.

Most frequently used implementation class of java.util.List is java.util.LinkedList and java.util.ArrayList

Example of ArrayList:
=====ListExamples.java====

import java.util.List;
import java.util.ArrayList;

public class ListExamples {
public static void main(String[] args) {
List<String> listOfStudents=new ArrayList<String>();
listOfStudents.add("James");
listOfStudents.add("Jack");
listOfStudents.add("Mike");

displayList(listOfStudents);
System.out.println(listOfStudents.size());
listOfStudents.get(1);
listOfStudents.remove(1);
displayList(listOfStudents);
System.out.println(listOfStudents.size());
listOfStudents.remove("James");
displayList(listOfStudents);
System.out.println(listOfStudents.size());
}

public static void displayList(List<String> listOfStudents){
for(String name:listOfStudents){
System.out.print(name+" ");
}
}
}
=====
Output:
James Jack Mike 3
James Mike 2
Mike 1

Most frequently used implementation class of java.util.Set is java.util.HashSet.

Example of HashSet:
====SetExamples.java======
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;

public class SetExamples {
public static void main(String[] args) {

Set<String> setOfStudents=new HashSet<String>();
setOfStudents.add("James");
setOfStudents.add("James"); //added twice
setOfStudents.add("Jack");
setOfStudents.add("Mike");

displayList(setOfStudents);
System.out.println(setOfStudents.size());

System.out.println(setOfStudents.contains("Jack"));

System.out.println(setOfStudents.remove(1));// notice the difference with list here,
//Don't think element at index 1 will not be deleted

displayList(setOfStudents);
System.out.println(setOfStudents.size());

System.out.println(setOfStudents.remove("James"));//notice it returns true since it is in the Set
displayList(setOfStudents);

System.out.println(setOfStudents.size());

}

public static void displayList(Set<String> listOfStudents){
for(String name:listOfStudents){
System.out.print(name+" ");
}
}
}
====
Output:
Jack James Mike 3
true
false
Jack James Mike 3
true
Jack Mike 2

Most frequently used implementation class of java.util.Map is java.util.HashMap.

Example of HashMap:
=====MapExamples.java======
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;

public class MapExamples {
public static void main(String[] args) {

Map<String,String> mapOfStudents=new HashMap<String,String>();
mapOfStudents.put("RollNo_1", "James");
mapOfStudents.put("RollNo_2","James"); //added twice
mapOfStudents.put("RollNo_1","Jack");
mapOfStudents.put(null,"Mike");

displayList(mapOfStudents);
System.out.println(mapOfStudents.size());

System.out.println(mapOfStudents.keySet().contains("RollNo_1"));

System.out.println(mapOfStudents.remove("RollNo_1"));// notice removed value will be shown here

displayList(mapOfStudents);
System.out.println(mapOfStudents.size());

System.out.println(mapOfStudents.remove("James"));//notice it returns null if not found, James is not a KEY here
displayList(mapOfStudents);

System.out.println(mapOfStudents.size());

}

public static void displayList(Map<String,String> students){
for(String name:students.values()){
System.out.print(name+" ");
}
}
}
=============
Output:
Mike James Jack 3
true
Jack
Mike James 2
null
Mike James 2

Sunday, February 7, 2016

Correct Singleton Class implemnetaion

This is a very basic design pattern question asked by the interviewer. There are multiple ways to implement Singleton class using Java.

Here is a correct way of implementation:

===
class Singleton {
 private volatile static Singleton _instance;//do not initialize here

private Singleton() { //mark it private to prevent Singleton object to be instantiated from outside

}

public static Singleton getInstance() {
 if (_instance == null) { 
  synchronized (Singleton.class) { 
   if (_instance == null) { 
    _instance = new Singleton();
    }
   }
  }
 return _instance;
}
===

Hibernate interview questions

1. Difference between load and get?
2. How load works? What is proxy?
3. What are first level and second level caches? Are these caches configurable? Specially first level cache.
4. QueryByExample?
5. What is better Criteria or HQL? Why?
Answer:
a. HQL is to perform both select and non-select queries  but Criteria is only for select query, we cannot perform non-select operations using criteria
b. HQL is suitable for executing Static Queries where as Criteria is suitable for executing Dynamic Queries(Dynamic SQL is simply a SQL statement that is composed on the fly before being executed)
c. HQL doesn’t support pagination concept, but we can achieve pagination with Criteria
d. With Criteria we are safe with SQL Injection because of its dynamic query generation but in HQL as your queries are either fixed or parametrized, there is no safe from SQL Injection.

Also criteria queries is Java developer friendly, so Criteria is better.

6. Lazy Load vs Eager Load?
7. Primary key generators.


Will update more questions.

Java interview questions


1. What is re-entrant lock? Difference between re-entrant lock and synchronized keyword?

2. Use of CountDownLatch, CyclicBarrier, Semaphore, Re-entrant Lock?

3. Difference between Iterator and for loop

Source: https://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

for-each loop really beautifies your code. Unfortunately, you cannot use it everywhere. Consider, below example,
--------------------
void exampleMethod(Collection<String> c) {

for (Iterator<String> i = c.iterator();

i.hasNext();

if (i.next().length() == 40)

i.remove();

}
--------------------
The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over multiple collections in parallel. These shortcomings were known by the designers, who made a conscious decision to go with a clean, simple construct that would cover the great majority of cases.

3. Order of execution of static class level blocks, class level block and constructor.
4. Which is better interface or 100% Abstract Class and why? 
5. Return statement in try, catch and finally. 
6. Abstract class constructor.
7. Cloneable Interface.
8. How to write immutable class? What about having data object? why the class is made final?
9. What constructs JVM?
10. What happens when Thread1 is running locking obj1 and Thread2 is wating for obj1. And Thread1 throws exception?
11. Serialization? How to de-serialize a singleton object? How to make subclass not serializable though its super is serializable?
12. What implements Decorator pattern? One example?
13. What changes between Java 1.5 vs Java 1.6?
14 What is Concurrent HashMap?  How it is improving performance than synchronizedMap?
What is the method to increment segment size?
15. What is the difference between wait and sleep method in Java?
Ans:
a. wait call should be made  from synchronized context but not mandatory for sleep.
b. If wait acquires any lock say obj1 then it will release the lock(monitor) temporarily so that notifying thread continue. It will acquire the lock again once the other threads notifies the thread(calling wait method). but sleep will hold the lock(until interrupted).



Will update more questions soon. Please feel free to make comments on the answer.

Saturday, February 6, 2016

What is overriding?

What is overriding?

We have discussed about overloading in the the previous post. Now we will discuss about overriding and its differences with overloading.

Overriding allows us to modify a method behavior at run time.

Here are the rules to make 2 overridden methods:
1. Methods must not take its arguments different. Here if a method is taking object of Class A then another method which is taking object of [Class B extends A] then it is allowed.
2. Overriding is done with its super class methods only.
3. Overriding does not allow overriding method to throw a new checked exception or a super class of the exception class that overridden method is throwing.

Example:
class A{
protected void display() throw SQLException{

}
}

class B extends A{

void display() Exception {

}

void display() IOException {

}

public void display(){

}

}

4. Overloading must not change its return return types. Here if a method is returning object of Class A then another method returning object of [Class B extends A] then it is allowed.
5. Overriding can change the access modifiers but overriding method should have less limiting access permission.
Example:

class A{

protected void display(){

}

}


class B extends A{

default void display(){

}

public void display(){

}

}

*** Red means not allowed and Green means allowed here.

What is overloading?

What is overloading?

Java supports polymorphism i.e with one name multiple functionalities. Java can acheive this by either overloading or overriding.

Overloading is when inside a class we might have multiple methods to which different arguments are passed. Here different argument means 2 variables which is not having any is-a relationship between them.

Lets take an example to understand it better.

Class A{
void display(String str){
 Syestem.out.println(str);
}
void display(int i){
 Syestem.out.println(i);
}
}

Here 2 methods display(...) are overloaded method because their arguments are different.

Here are the rules to make 2 methods overloaded:
1. Methods must take its arguments different. Here if a method is taking object of Class A then another method which is taking object of [Class B extends A] then it is not allowed.
2. Overloading can be done with its super class methods.
3. Overloading allows 2 methods to throw different Exceptions.
4. Overloading can change return types.
5. Overloading can change the access modifiers of the methods in any combination.