Friday, June 17, 2016

Things to remember about Null Pointer Exception

Our day to day coding life, we are facing Null pointer exception in most cases. We can see some good points about this. 

1. The instanceof operator

Code: 
String str = null;
if(str instanceof String)
   System.out.println("String is an instance here");
else
   System.out.println("String is not an instance here");

Output:
String is not an instance here

You can use instanceof operator , even if the object reference equals to null. It will not throw null pointer exception.


2. Null with contains , containsKey and containsValue methods

Code: 
 
String value = map.get(key);
System.out.println(value.toString());  

We know map, which is working based on key and value concept. From the above code, suppose if value is null, then it will throw null pointer exception here.

To avoid Null pointer for above code : 
if(map.containsKey(key)) {
    String value = map.get(key);
    System.out.println(value.toString()); // Now No exception
}


3. Apache StringUtils class
 
if (StringUtils.isNotEmpty(str)) {
     System.out.println(str.toString());
}

We can use StringUtils.IsEmpty and StringUtils.equals also.


4. String comparison with equals 

This is very useful, in most of our programs.

String str = null;
 if(str.equals("Test")) { // Exception will throw here
    }

  To avoid above Code Error

String str = null;
    if("Test".equals(str)) { //No Exception now
    }


5. Ternary operator

String message = (str == null) ? "" : str.length();

From the above, if str is null, then assign empty for that, else calculate length.


6. valueOf() is better than toString()

    String str = null;
    System.out.println(String.valueOf(str));  // it will prints null        
    System.out.println(str.toString()); // it will throw NullPointer Exception


7. Working with Static method or Static members

Below code will not throw any error.

class Test {     
         public static void testMessage() {
              System.out.println("Test Message");
         }
    }

    public class TestStatic {
         public static void main(String[] args) {
              Test t = null;
              t.testMessage();
         }
    }

However, as per rule, static method should be called through class name only. Calling static method by object reference is not advisable.

Friday, June 10, 2016

extends Thread vs Implements Runnable

There are two ways to create a thread in Java.

1. By extending Thread class

2. By implementing Runnable Interface

Lets see the difference now.
  • If you are extending Thread class , you can not extends another class again, since Java does not support multiple inheritance.
  • If you are using implements Runnable interface , then there is a chance to extending another class.
  • Very important difference is, your thread will create unique object and make an associates with it while extends Thread.
  • But if you are using an implements Runnable Interface, It will share same object to multiple threads. 

Now we can understand this with one example, which will clarify more.

class ImplementsRunnable implements Runnable {
 
 private int count = 0;
 
 public void run() {
 count++;
 System.out.println("ImplementsRunnable checking Test : " + count);
 }
 }
 
 class ExtendsThread extends Thread {
 
 private int count = 0;
 
 public void run() {
 count++;
 System.out.println("ExtendsThread checking Test : " + count);
 }
 }
 
 public class ThreadVsRunnable {
 
 public static void main(String args[]) throws Exception {


 ImplementsRunnable rc = new ImplementsRunnable();
 Thread t1 = new Thread(rc);
 t1.start();

 Thread.sleep(1000); 
 Thread t2 = new Thread(rc);
 t2.start();

 Thread.sleep(1000); 
 Thread t3 = new Thread(rc);
 t3.start();
 

 ExtendsThread tc1 = new ExtendsThread();
 tc1.start();
 Thread.sleep(1000);
 
 ExtendsThread tc2 = new ExtendsThread();
 tc2.start();
 Thread.sleep(1000); 

 ExtendsThread tc3 = new ExtendsThread();
 tc3.start();
 }
 }

Output :

ImplementsRunnable checking Test : 1
ImplementsRunnable checking Test : 2
ImplementsRunnable checking Test : 3
ExtendsThread checking Test : 1
ExtendsThread checking Test : 1
ExtendsThread checking Test : 1

If you will analyze the output, it says well like Runnable interface sharing one instance and increment values. But it is opposite in Thread class, since it creates separate instance every time.

Monday, June 6, 2016

Difference between sleep and wait in java ?

Sleep and wait () method

sleep () is a method , which is used to hold the process for a particular time or How much time you wanted to hold. 

wait () method goes to waiting stage and it wont come back to normal until notify() or notifyAll() method should be called. 

Important points about sleep() method

1. Sleep is a static method on Thread class. 

2. It will makes your current thread into Not Runnable state for the specified amount of time.      
    Thread keeps the lock, during this time. 

3. It will be waked by interrupt or time expires.

4. It throws interrupted exception if another thread interrupts a sleeping thread.


Important points about wait() method

1. wait is an object class method.

2. It will makes your current thread into Not Runnable state. 

3. Remember, wait is called on an object not on thread. 

4. wait() should be used inside synchronized block or synchronized method. 

5. It will release the lock and gives the chance to others. 

6. It will be awake by calling on notify() or notifyAll() methods.

Friday, June 3, 2016

How LEFT JOIN and RIGHT JOIN works

As usual, we are keeping the same two table Employee and location to explain left and right joins.

Employee Table

empIdEmpName
101Rajesh
102Vinodh
103Kumar
104Mukesh

Location Table

empIdLocation
101Chennai
102Mumbai
103Kolkatta
105Hyderabad

What is LEFT Join ?

The LEFT JOIN keyword returns all rows from the left table (What is left table ? ), with whatever matching rows in the right table (What is right table ?).

Suppose if there is no match in the right side, result is NULL.

We can write query first for this left join, after that I will explain. Left join query will be,

select * from employee left join location 
on employee.empID = location.empID;

Output : 

Employee.empIDEmployee.empNameLocation.empIDLocation.empLocation
101Rajesh101Chennai
102Vinodh102Mumbai
103Kumar103Kolkatta
104MukeshNullNull

From the result, we able to understand , left join query taking the rows from left table completely. If there is no match in the right tale it will return null like above.

Ven Diagram 
Left
Left Join Ven diagram














What is Right Join ?

The RIGHT JOIN returns all rows from the right table with the matching rows in the left table. If there is no match in the left table it will return NULL. 

Ven diagram of Right Join
right join
Right Join Ven diagram
 












Right Join Query

select * from employee right join location
on employee.empID = location.empID
 
Below figure represents some clear idea about left and right join.  

pointing
Table pointing identification of right and left join












Wednesday, June 1, 2016

Understanding Self Join Briefly with Example

Self join is easiest to understand. We can see how its working with one good example clearly. Consider the below table we have called Employee which have two columns name and location.

Employee Table

NameLocation
MillarChennai
RajeshDelhi
StalinChennai
KumarMumbai

Now you have to write the query for the below question.

1. How you find out which employees are coming from same location as name have Millar.

After seeing the question you will write the query immediately like below.
select name
from Employee
Where location in (select location from employee where name = "Millar"
 
Fine. It will work perfectly. But using sub query is not a good practice. So in this place SELF JOIN can play its role perfectly. 

What is SELF JOIN ? 

             Self join is nothing but, when a table is joined itself called self join. So it will take two copies to join the table itself. To work with self join we must use aliases which will allow you to write a query with good efficient way. The reason here, why we are using aliases means, we should differentiate two copies of that table. Right ?  Yes. 

Any join(left, right, outer etc.,) will work with condition only. So self join also having condition to perform self join operation. Now throw the sub query from your mind and bring your mind into Self Join. Already we have discussed , two copies of table it have. Just call those copies as e1, e2.


 Table  -    e1
NameLocation
MillarChennai
RajeshDelhi
StalinChennai
KumarMumbai


 Table  -    e2
NameLocation
MillarChennai
RajeshDelhi
StalinChennai
KumarMumbai

As we discussed earlier, two tables was created like e1 and e2. After writing query Self join query is like below. 

SELECT e1.Name
FROM employee e1, employee e2
WHERE e1.location = e2.location
AND e2.Name="Millar";

Lets analyze the query , the condition WHERE e1.location = e2.location will give results (Rows) of location. Again we must add another condition which should be e2.Name="Millar". Based on the name we should filter , so that we added this condition. But you may get one doubt here, why we want to add only e2.Name ?.   Since, we need to return only the rows name as Millar. If you will add condition for both side of e1 and e2, it will return both side of table rows.

So you will find below finally,

e1.Namee1.Locatione2.Namee2.Location
MillarChennaiMillarChennai
StalinChennaiStalinChennai