Showing posts with label java interview questions. Show all posts
Showing posts with label java interview questions. Show all posts

Sunday, May 5, 2013

JNDI

The Java Naming and Directory Interface (JNDI) is part of the Java platform, providing applications based on Java technology with a unified interface to multiple naming and directory services. You can build powerful and portable directory-enabled applications using this industry standard.

Example of creating JNDI Datasource.

Tuesday, April 30, 2013

Iterate a HashMap


HashMap is an object that stores both “key/value” as a pairs.
It is one of the most useful data structures in the Java programming language.

Step by Step Iterating a HashMap :- 

Method 1 :-
Map<Integer, Integer> map = new HashMap<Integer, Integer>();

//iterating over keys only
for (Integer key : map.keySet()) {
System.out.println("Key = " + key);
}

//iterating over values only
for (Integer value : map.values()) {
System.out.println("Value = " + value);
}

Method 2 :-
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

Sunday, January 6, 2013

Extract a list of filtered files in Java

Sometimes, we need to get a list of files exist within a directory as per our criteria like filename, file extension, last modified date or other attributes. It reduces the overhead to filter them after getting the list using our code. To achieve this, Java provides an interface - FileFilter which has a single method prototype as boolean accept(File file). To apply our filtering criteria, we have to override this method and if our logic returns true for a file then only the file will be included in the list otherwise not. 

Example :- 

import java.io.*;
import java.util.*;
 
public class FilteredFileList {
    public static File[] getFilteredFileList(File folder, final String filenameFilter, Date lastModifiedDateFilter) {
        File[] listOfFiles = folder.listFiles(new FileFilter(){
                                public boolean accept(File file) {
                                    //file is the object against which we are applying our logic.
                                    //You can put your logic using filenameFilter and check whether
                                    //the file's name comes under your criteria or not.
                                    //To check against the lastmodified date you can use lastModifiedDateFilter.
                                    return true;
                                }});
        return listOfFiles;
    }
}

JDBC Connection in Java

JDBC (Java DataBase Connectivity) is an API for the Java programming language through which the databse can be accessed using methods for querying and updating data.


Example :- 

import java.sql.*;
 
public class ConnectionInfo {
 
    public Connection getConnection() {
        Connection conn = null;
        // the below properties should be read from a properties file based on the Database used
        String url = "jdbc:mysql://localhost:3306/"; // url = jdbc:[subprotocol]://[hostname]:[portnumber]/
        String dbName = "jdbctutorial"; // database name
        String driver = "com.mysql.jdbc.Driver"; //Driver class name
        String username = "root"; // username
        String password = "root"; // password
        try {
          Class.forName(driver); // Dynamic loading based on database used.
          conn = DriverManager.getConnection(url + dbName, username, password);
          System.out.println("Connection Established");
        } catch (SQLException e) {
          e.printStackTrace();
        } finally {
            return conn;
        }
    }
 
    public void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

Java Multithreading


Process can be further divided into small tasks which refer as a Thread. If two or more tasks of a process executes concurrently, then this scenario refers as aMultithreading environment. Every thread has it's own independent path of execution. In java, there are two ways to implement multithreading -

Through implementation of Runnable interface - To create a thread, we can implement Runnable interface. This interface has a single run() method declaration, so we have to override that method. Actually, in this approach, we write a wrapper over Thread class. The objects of the class which implements Runnable interface, work as a thread of the program and run on their own execution paths.

Example :- 
public class RunnableExample implements Runnable {
    private Thread thread;
    public RunnableExample(String name) {
        //here we pass the reference whose run method should be called.
        thread = new Thread(this, name);
        //creating thread
        thread.start();
    }
     
    public void run() {
        //your logic will go here
        System.out.println(thread.getName());
    }
}
 
public class RunnableMain {
    public static void main(String[] args) {
        //Creating three objects
        Runnable run1 = new RunnableExample("Thread-1");
        Runnable run2 = new RunnableExample("Thread-2");
        Runnable run3 = new RunnableExample("Thread-3");
    }
}



2. Using Thread class extension - This is another approach of thread creation. But, it restricts the class to extend other classes (if required). In this approach, we extend our class to Thread class so that it's objects work as threads and run on their own separate execution paths.

Here is the sample code -
public class ThreadExample extends Thread {
 
    public ThreadExample(String name) {
        super(name);
    }
     
    public void run() {
        //your logic will go here
        System.out.println(thread.getName());
    }
}
 
public class ThreadMain {
    public static void main(String[] args) {
        //Creating three objects
        Thread t1 = new ThreadExample("Thread-1");
        Thread t2 = new ThreadExample("Thread-2");
        Thread t3 = new ThreadExample("Thread-3");
        creating threads
        t1.start();
        t2.start();
        t3.start();
    }
}

Recursion

Recursion is one of the interesting topic. The problems, which can be implemented using loops, can be implemented with Recursion as well. But, most of us go with the looping solution. Today, I am going to set some light on how the same logic can be implemented using recursion. If we could derive a mathematical function for these type of problems, the implementation will be more easier. Lets understand it through some examples.

Example 1 : Factorial 
The factorial of a non-negative number is the multiplication of all the positive integers which are less than or equal to the number.

Suppose fact(n) is a function of n, where x is non-negative integer value. Hence 

fact(0) = fact(1) = 1
fact(2) = 2 * fact(1) = 2
fact(3) = 3 * fact(2) = 6
...
...
... 
fact(n) = n * fact(n-1)

So, the logic would be - If the value of n is 0 or 1 return 1, else return multiplication of n and value of function for (n-1).


int fact(int num) {
    if(num == 0 || num == 1)
        return 1;
    else
        return num * fact (num - 1);
}
Example 2 : Fibonacci Series 
The Fibonacci series is a sequence of integers whose first and second terms are 0 and 1 respectively and  each subsequent term is the sum of the previous two terms. Like - 0, 1, 1, 2, 3, 5, 8, 13, 21, .....

Suppose fibo(n) is a function of n which returns the term n of the fibonacci series and where n > 0 -

fibo(1) = 0
fibo(2) = 1
fibo(3) = fibo(1) + fibo(2) = 1
fibo(4) = fibo(2) + fibo(3) = 2
fibo(5) = fibo(3) + fibo(4) = 3
...
...
...
fibo(n) = fibo(n-2) + fibo(n-1)

So, the logic would be - If the value of n is 1 or 2 return (n-1), else return the addition of value of function for (n-2) and function for (n-1) .

int fibo(int num) {
    if(num == 1 || num == 2)
        return (num - 1);
    else
        return fibo(num - 2) + fibo(num - 1);
}

Singleton design pattern

The Singleton class means whose only one instance can be created. To make the class Singleton, we should restrict the ways through which the objects can be created. The object can be created in the following ways -
  1. Using new operator
  2. Using newInstance() method  (by Dynamic loading of class).
  3. Through Serialization/Deserialization
  4. Through Cloning
To restrict the ways of object  creation, we should take care of the following points -
  1. The Constructer must be private so that static (using new operator) and dynamic (using newInstance() method) creation of object does not get supported.
  2. Static field as object of the Singleton class should be declared within that class. In getInstance() method, it should be checked whether the static object has been instantiated or not. If not, then instantiate and return it.
  3. The method getInstance() must be Static and Synchronized. Static, so it can be accessed through the class name. Synchronized, because it should be thread-safe.
  4. The class must implement the Externalizable interface and override thewriteExternal() and readExternal() methods such that serialization/deserialization should not be supported.
  5. The class must override clone() method so that another object could not get created.

import java.io.*;
 
//Implement Externalizable interface to avoid object creation through Deserialization.
public class SingletonExample implements Externalizable {
    //make a static object
    private static SingletonExample g_instance;
 
    //make the construct as provate to hide it from outer world.
    private SingletonExample() {
        //do nothing
    }
 
    //make this static method as synchronized for thread-safe model.
    public synchronized static SingletonExample getInstance() {
        if (g_instance == null)             
            g_instance = new SingletonExample();
        return g_instance;
    }
     
    //override method and throw exception to avoid serialization     
    public void writeExternal(ObjectOutput out) throws SerializationNotAllowedException {
        throw new SerializationNotAllowedException("Serialization is not supported.");
    }     
 
    //override method and throw exception to avoid deserialization
    public void readExternal(ObjectInput in) throws SerializationNotAllowedException {
        throw new SerializationNotAllowedException("Deserialization is not supported.");
    }         
 
    //override method to avoid object cloning
    protected Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException("Cloning not allowed");
    } 
}
 
//As the methods writeExternal and readExternal throws IOException, hence we have to extend to create our own Exception.
class SerializationNotAllowedException extends IOException {
    public SerializationNotAllowedException(String message) {
        super(message);
    }
}

Static and Non Static Synchronized Methods



Static Method Call - When we make a call to a static method (either directly from class or any object of that class), the Class object of that Class involves in that call. Every Class has only one Class object.

Non-static Call -  When we call a non-static method (always from an object of that class), it works for that object only (which is of that class only). A class can have as many objects (if not restricted though some design patterns or lack of memory).

Now, lets come to Static and Non-static Synchronized method calls -

Static Synchronized Method Call - Whenever a thread accesses any synchronized static method, it acquires the lock on Class object of that class and hence no other static method can be accessed of that class.

Non-static Synchronized Method Call - As the non-static methods can be accessed through only objects of that class. So whenever, a thread enters any non-static synchronized method, it acquires the lock on the object through which the call has been made. Hence the other threads can still access the same or other non-static methods using other unlocked objects (free resources) of that class.

Sunday, December 16, 2012

Synchronous and Asynchronous Exceptions


     The interpreter executes the java program sequentially. An exception E can occur relative to a line (L) of program. That is that exception E will always occur at the execution of that line L. This is called Synchronous exception.

An asynchronous exception in java can occur at any point in the execution of a program.

Checked Vs Unchecked Exception

Checked Exception  in Java is all those Exception which requires being catches and handled during compile time. If Compiler doesn't see try or catch block handling a Checked Exception, it throws Compilation error. All the Exception which are direct sub Class of Exception but not inherit RuntimeException are Checked Exception.
IOException
SQLException
DataAccessException
ClassNotFoundException
InvocationTargetException

Unchecked Exception  in Java is those Exceptions whose handling is not verified during Compile time. Unchecked Exceptions mostly arise due to programming errors like accessing method of a null object, accessing element outside an array bonding or invoking method with illegal arguments. In Java, Unchecked Exception is direct sub Class of RuntimeException. What is major benefit of Unchecked Exception is that it doesn't reduce code readability and keeps the client code clean.
NullPointerException
ArrayIndexOutOfBound
IllegalArgumentException
IllegalStateException

Difference :- Checked Exception is required to be handled by compile time while Unchecked Exception doesn't.
Checked Exception is direct sub-Class of Exception while Unchecked Exception are of RuntimeException.
CheckedException represent scenario with higher failure rate while UnCheckedException are mostly programming mistakes.






Saturday, December 1, 2012

System.out.println


System – is a final class and cannot be instantiated. Therefore all its members (fields and methods) will be static and we understand that it is an utility class. System class are standard input, standard output, and error output streams.

out – is a static member field of System class and is of type PrintStream. Its access specifiers are public final. This gets instantiated during startup and gets mapped with standard output console of the host.

println – Method of PrintStream class. println prints the argument passed to the standard console and a newline. 

Can a top level class be private or protected


No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.

main() method in java


The main function is important function in Java programming language. 
The main method is the first method, which the Java Virtual Machine executes. When you execute a class with the Java interpreter, the run time system starts by calling the class's main() method. The main() method then calls all the other methods required to run your application. It can be said that the main method is the entry point in the Java program and java program can't run without this method.

Public static void main (String args[])
Public is an Access Specifier.

static is a keyword which illustrates that method shared along all the classes.
void illustrates that this method will not have any return type.
main is the method which string has an argument. 
Public specifier makes the method visible outside the Class and because of the static nature of the method, JVM can call this main method without instantiating the class.

Friday, November 30, 2012

Path and Classpath


PATH is nothing but setting up an environment for operating system. Operating System will look in this PATH for executable.


Classpath is nothing but setting up the environment for Java. Java will use to find compiled classes (i.e. .class files).



Path refers to the system while classpath refers to the Developing Envornment.

We keep all "executable files"(like .exe files) and "batch files"(like .bat) in path variable. And we keep all jar files and class files in classpath variables.



For example,assume that Java is installed in C:\jdk1.5.0\ and your code is in C:\Sample\example.java, then your PATH and CLASSPATH should be set to:

PATH = C:\jdk1.5.0\bin;%PATH%

CLASSPATH = C:\Sample










ShareThis