Tuesday, July 19, 2016

How to create Immutable class in java?

Most of the interview, we can expect this question. In Nutshell, java have lot of immutable classes like String, Integer, Float etc.,

Please remember below points to make your class as immutable.
  • Make your class as Final, So that other can not extends it, means cannot create sub class. 
  • Declare instance variable as Final with private modifier, so that it can not change once initiated.
  • Don't implement setter methods.
  • Finally, don't provide any method which will change the behavior of state of the object.

Example :

public final class JavaHit{ 
    final String name;  
  
public JavaHit(String name){  
    this.name=name;  
  }  
  
public String getName(){  
    return name;  
  }    


Benefits of Immutable class:
  • It will be helpful in synchronization environments, since its thread-safe.
  • Internal state of immutable class will be fine, even you get any exception.
  • It will be good to work with Map Keys and set elements, since typically it will not change once its created.

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

Monday, May 30, 2016

JSP Interview Questions and Answers

1. Can you tell me JSP life cycle methods and JSP life cycle phases ?

JSP Life Cycle methods
 
Jspinit()      - It will be invoked when the JSP page is initialized.

_jspService()  - It corresponds to the body of the jsp page and it will be handle for requests  
                 and response for all seven HTTP methods ie. GET, POST, DELETE etc.

jspDestroy()   - CleanUp activity will be handled by this method.

Refer for flow diagram

JSP Life Cycle Phases

1. Translation phase
2. Compilation phase
3  Instantiation phase
4  Initialization phase
5  Servicing phase
6  Destruction phase

2. What are the Directives in Jsp?

jsp engine will use this as a translation time instruction.

1. Page directive
2. Include directive
3. Taglib directive

3. What are the Jsp Implicit Objects?

Implicit objects will be created by container and developer no need to create it explicitly. Totally 9 implicit objects are available in jsp.

    1. out
    2. request
    3. response
    4. config
    5. application
    6. session
    7. pagecontext
    8. page
    9. exception

4. Difference between include directive and include action?

include directive -
<%@ include>

1. It will be processed at translation time.

2. It wil be static
<%@ include file="header.html" %>

3. You can not pass parameters.


include action (jsp:include )

1. It will be processed at run time.

2. It will be dynamic.

             <jsp:include page="header.jsp" />

              header.jsp will be addded at request time.

3. We can pass parameters by using below.

             <jsp:include page="header.jsp">
                   <jsp param name="menu" value="obj1"/>
             </jsp:include>

5.  Is there anyway to disable session in JSP ? 

Yes,  by using page directive

<%@ page session="false" %>

6.  How to handle exception in JSP and explain?

Two ways we can handle exception in JSP

1. By using isErrorPage and errorPage of page directive attributes.
2. By using <error-page> tag in Deployment Descriptor. (web.xml)


1.1 isErrorPage

<%@ page isErrorPage="true" %>
<html>
<body>
<b> Sorry! This requested page not availbale </b>
<img src="ErrorImage.jpg"/>
</body>
</html>

The above file (Error.jsp) will be executed if any error occurred. Error will be identified by using page directive attribute of isErrorPage. Remember it will be developed only to display error.

1.2 errorPage

It will tells to the Web Container that if any exception occurred at particular page, then forward the request to an error page. So both are totally different logic, but for error purpose only. 

<%@ page errorPage="error.jsp">

<html>
<body>

<!-- Your logical code and any exception occurred while executing this -->

</body>
</html>

 2. <error-page> tag in Deployment Descriptor

It will give some good option to handle error. You should define this web.xml

For all type of Exception

<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error.jsp</location>
</error-page>

For particular exception
<error-page>
<exception-type>java.lang.ArithmeticException</exception-type>
<location>/error.jsp</location>
</error-page>

For HTTP Status code
<error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>

<error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>

7. What are the action tags in JSP ?

Action Tag Tag Description
jsp:forwardforward the request to a new page
jsp:getProperty    retrieve a property from a JavaBean instance.

jsp:include
include the runtime response of a JSP page.
jsp:plugin
Generates client browser-specific construct that makes an OBJECT or EMBED tag for the Java Applets
jsp:useBean
instantiates a JavaBean
jsp:param
Adds parameters to the request
jsp:elementDefines XML elements dynamically
jsp:textUse to write template text in JSP pages and documents.
jsp:setProperty
store data in JavaBeans instance.
jsp:fallbackSupplies alternate text if java applet is unavailable on the client
jsp:bodyUsed within standard or custom tags to supply the tag body.
jsp:attributedefines dynamically defined XML element's attribute

8.Differentiate between response.sendRedirect(url) and <jsp:forward page > ?

jsp:forward - It will forward one request object to another , which is to be HTML, servlet or JSP.  But important point here is, it should be within application context. (Application).

sendRedirect (url) - It will transer one request to another resource , which is to be different domain or different server.

9.  How you can implement thread safe in jsp ?

To make JSP as thread-safe, you can implement the SingleThreadModel interface , which prevents two threads from accessing the service method at the same time.

The JSP page by default is not thread safe, if you want to make it thread safe then you should add following directive in your JSP page declaration:

<%@ page isThreadSafe="false" %>

10. Is JSP technology extensible?

Yes, JSP is easily extensible witht the help of modification of tags, custom actions etc.,

11.  How will you pass information from one JSP to another JSP?

<Jsp:param> allows us to pass information between multiple Jsp’s.

12. Why does _jspService() start with an ‘_’ but other lifecycle methods does not start ?

The reason is, we should not override _jspservice method, since it will be executed by container. But remaining two methods we can override. 


So '_'  representing here, we should should not override. If you override compiler will give an error.

13.  How to avoid session created automatically in JSP?

 <%@ page session=”false”  %>

14.  What are the various scope values for <jsp:useBean> ?

1)application

2)request

3)page

4)session


15. How to disable java code or scripting in JSP page?

We should add below code in deployment descriptor(web.xml)
   

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern
        <scripting-invalid>true</scripting-invalid>
    </jsp-property-group>
</jsp-config>
 
Here, it will disable all jsp page , but you want to allow to any special jsp then you should add that JSP file name manually.