Interview Questions

Java

Web Application Auto Login

In general, every web application will have an authentication mechanism, to authenticate the users accessing the web application.

Suppose if there is a requirement to autologin to a web application from a given page, use the following code.

<html>
<head>
</head>
<script type="text/javascript">

function autoLogin()
{
var xmlhttp;
alert('loadXMLDoc');
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

Java Executor Service

The following code illustrates the usage of handling multiple threads using ExecutorService and Callable Interface.
The Callable Interface is similar to Runnable interface, except that it has following call() method instead of run().

 V call() throws Exception;

The major difference is call() method returns an object as a result of executing the thread and run() ( in Runnable Interface) method doesn't return.

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

Java Thread Synchronization

/**
 *  Print even/odd numbers sequentially using two different threads
 */

public class ThreadSequence {

        public static ThreadSequence tdSeq = new ThreadSequence();

        boolean avail = true;

        public ThreadSequence() {
       
        }

       
        public static void main(String[] args) {
               

                Thread one = new Thread(new MyThreadOdd());
                Thread two = new Thread(new MyThreadEven());
                two.start();
                one.start();

        }

}

class MyThreadOdd implements Runnable {

        public void run() {
                for (int i = 1; i <= 20; i += 2)

                {

jquery - highlight table cells

<html>
<head>
  <script type="text/javascript" src="jquery.js"></script>
</head>

<style type="text/css">
      .highlight{
        color:white;
        background-color:black;
        cursor: pointer;
      }
    </style>
   
    <table id="example" border='1'>
      <thead>
        <tr>
          <td>First Name</td>
          <td>Last Name</td>
          <td>Email</td>
        </tr>
      </thead>
      <tbody>
        <tr onclick="alert('John Smith')">
          <td>John</td>
          <td>Smith</td>
          <td>John.Smith@gmail.com</td>

How to insert BLOB/CLOB data in DB using JDBC ?

Use the following code to insert LOB data in DB using JDBC.

public static void insertLob() throws Exception
    {
            String dbUrl = "jdbc:oracle:thin:@<host_name>:<port_number>:<DB_Name>";
            Connection con = null;
            ResultSet rs = null;
            PreparedStatement psIns = null;
           
            try
            {
                    Class.forName("<Driver_Name>");

                    con = DriverManager.getConnection(dbUrl, "<userName>", "<passWord>");

                    psIns = con

Java - Read last line from a file

The following code is used to read last non-blank line from a file using java.

public String getLastNonBlankLine(File file) throws Exception
        {
                RandomAccessFile fileHandler = null;
                try
                {
                        fileHandler = new RandomAccessFile(file, "r");
                        long fileLength = file.length() - 1;
                        StringBuilder sb = new StringBuilder();

                        for (long filePointer = fileLength; filePointer != -1; filePointer--)
                        {
                                fileHandler.seek(filePointer);
                                int readByte = fileHandler.readByte();

                                if (readByte == 0xA)
                                {
                                        if (filePointer == fileLength)

Java Producer Consumer Model using Threads

Here is a simple example to illustrate Producer - Consumer Model using Java Threads.

public class Producer implements Runnable
{

        private static int      count   = 0;

        @Override
        public void run()
        {
                while (true)
                {
                        synchronized (Market.productList)
                        {

                                while (!(Market.productList.size() >= 0))
                                {
                                        System.out.println("entered while" + Market.productList.size());
                                        try
                                        {
                                                Market.productList.wait();
                                        }
                                        catch (InterruptedException e)
                                        {
                                                e.printStackTrace();
                                        }
                                }

jQuery Date Picker - Display Date range fields

The following is a JSP code to display date range fields using jQuery.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
<html>

<head>
<script type="text/javascript" src="<c:url value='/jquery/jquery-1.6.1.min.js'/>"></script>

<script type="text/javascript" src="<c:url value='/jquery/jquery-ui-1.8.15.custom.min.js'/>"></script>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />

<title>jQuery Date Picker Example</title>

<script type="text/javascript">
        $(function() {

Jsp Logout page template

Here is a simple JSP logout page template which can be used in Java based web applications.

It just invalidates the current user session and redirects to login page.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Logout</title>

</head>

Java - Send HTTP Post Request

Use the following code to send Http Post request to any URL from Java.

class HttpPost
{
        public HttpURLConnection getHTTPConnection(String sendUrl)
        {
                URL url = null;
                HttpURLConnection urlConn = null;

                try
                {
                        url = new URL(sendUrl);
                        urlConn = (HttpURLConnection) url.openConnection();
                        urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                        urlConn.addRequestProperty("User-Agent", "TDD");
                        urlConn.setUseCaches(false);
                        urlConn.setReadTimeout(5000);
                        urlConn.setConnectTimeout(5000);