Tuesday, February 10, 2015

Top 25 Most Frequently Asked Interview Questions And Answers on Core Java

Top 25 Most Frequently Asked Interview Core Java Interview Questions And Answers 

1. Which two method you need to implement for key Object in HashMap ? 

In order to use any object as Key in HashMap, it must implements equals and hashcode method in Java.

2. What is immutable object? Can you write immutable object?  

Immutable classes are Java classes whose objects can not be modified once created. Any modification in Immutable object result in new object. For example, String is immutable in Java. Mostly Immutable are also final in Java, in order to prevent sub class from overriding methods in Java which can compromise Immutability. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.

3. What is the difference between creating String as new() and literal?
When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.

String s = new String("Test");

does not  put the object in String pool , we need to call String.intern() method which is used to put  them into String pool explicitly. its only when you create String object as String literal e.g. String s = "Test" Java automatically put that into String pool.

4. What is difference between StringBuffer and StringBuilder in Java ?

Classic Java questions which some people thing tricky and some consider very easy. StringBuilder in Java is introduced in Java 5 and only difference between both of them is that Stringbuffer methods are synchronized while StringBuilder is non synchronized.

5.  Write code to find the First non repeated character in the String  ?
Another good Java interview question, This question is mainly asked by Amazon and equivalent companies.


import java.util.HashMap;
import java.util.Scanner;

public class FirstNonRepeated {
    public static void main(String[] args)
        // TODO Auto-generated method stub
        System.out.println(" Please enter the input string :" );
        Scanner in = new Scanner (System.in);
        String s=in.nextLine();
        char c=firstNonRepeatedCharacter(s);
        System.out.println("The first non repeated character is :  " + c);
    public static Character firstNonRepeatedCharacter(String str)
        HashMap<Character,Integer>  characterhashtable= 
                     new HashMap<Character ,Integer>();
        int i,length ;
        Character c ;
        length= str.length();  // Scan string and build hash table
        for (i=0;i < length;i++)
                // increment count corresponding to c
                characterhashtable.put(  c ,  characterhashtable.get(c) +1 );
                characterhashtable.put( c , 1 ) ;
        // Search characterhashtable in in order of string str
        for (i =0 ; i < length ; i++ )
            c= str.charAt(i);
            if( characterhashtable.get(c)  == 1 )
            return c;
        return null ;

6. What is the difference between ArrayList and Vector ?
This question is mostly used as a start up question in Technical interviews  on the topic of Collection framework .
1.  Synchronization and Thread-Safe

Vector is  synchronized while ArrayList is not synchronized  . Synchronization and thread safe means at a time only one thread can access the code .In Vector class all the methods are synchronized .Thats why the Vector object is already synchronized when it is created .

2.  Performance

Vector is slow as it is thread safe . In comparison ArrayList is fast as it is non synchronized . Thus     in ArrayList two or more threads  can access the code at the same time  , while Vector is limited to one thread at a time.

3. Automatic Increase in Capacity

A Vector defaults to doubling size of its array . While when you insert an element into the ArrayList ,      it increases its Array size by 50%  . By default ArrayList size is 10 . It checks whether it reaches the       last  element then it will create the new array ,copy the new data of last array to new array ,then old array     is garbage collected by the Java Virtual Machine (JVM) .

4. Set Increment Size
ArrayList does not define the increment size . Vector defines the increment size .
You can find the following method in Vector Class

public synchronized void setSize(int i) { //some code  }

There is no setSize() method or any other method in ArrayList which can manually set the increment size.

5. Enumerator
Other than Hashtable ,Vector is the only other class which uses both Enumeration and Iterator .While ArrayList can only use Iterator for traversing an ArrayList .

6.  Introduction in Java

java.util.Vector  class was there in java since the very first version of the java development kit (jdk).
java.util.ArrayList  was introduced in java version 1.2 , as part of Java Collections framework . In java version 1.2 , Vector class has been refactored to implement the List Inteface .

7. How do you handle error condition  while writing stored procedure or accessing stored procedure from java?
stored procedure should return error code if some operation fails but if stored procedure itself fail than catching SQLException is only choice.

8. What is difference between Executor.submit() and Executer.execute() method ?
There is a difference when looking at exception handling. If your tasks throws an exception and if it was submitted with execute this exception will go to the uncaught exception handler (when you don't have provided one explicitly, the default one will just print the stack trace to System.err). If you submitted the task with submit any thrown exception, checked exception or not, is then part of the task's return status. For a task that was submitted with submit and that terminates with an exception, the Future.get will re-throw this exception, wrapped in an ExecutionException.

9. What is the difference between factory and abstract factory pattern?
Abstract Factory provides one more level of abstraction. Consider different factories each extended from an Abstract Factory and responsible for creation of different hierarchies of objects based on the type of factory. E.g. AbstractFactory extended by AutomobileFactory, UserFactory, RoleFactory etc. Each individual factory would be responsible for creation of objects in that genre.
You can also refer What is Factory method design pattern in Java to know more details.

10. What is Singleton? is it better to make whole method synchronized or only critical section synchronized ?
Singleton in Java is a class with just one instance in whole Java application, for example java.lang.Runtime is a Singleton class. Creating Singleton was tricky prior Java 4 but once Java 5 introduced Enum its very easy.

11. Can you write critical section code for singleton?
This core Java question is followup of previous question and expecting candidate to write Java singleton using double checked locking. Remember to use volatile variable to make Singleton thread-safe.

12. Can you write code for iterating over hashmap in Java 4 and Java 5 ?
Tricky one but he managed to write using while and for loop.13. When do you override hashcode and equals() ?
Whenever necessary especially if you want to do equality check or want to use your object as key in HashMap.
14. What will be the problem if you don't override hashcode() method ?
You will not be able to recover your object from hash Map if that is used as key in HashMap.
15. Is it better to synchronize critical section of getInstance() method or whole getInstance() method ?
Answer is critical section because if we lock whole method th
en every time some one call this method will have to wait even though we are not creating any object.17. Does not overriding hashcode() method has any performance implication ?
This is a good question and open to all , as per my knowledge a poor hashcode function will result in frequent collision in HashMap which eventually increase time for adding an object into Hash Map.
18. What’s wrong using HashMap in multithreaded environment? When get() method go to infinite loop ?
During concurrent access and re-sizing.19.  What do you understand by thread-safety ? Why is it required ? And finally, how to achieve thread-safety in Java Applications ?

Java Memory Model defines the legal interaction of threads with the memory in a real computer system. In a way, it describes what behaviors are legal in multi-threaded code. It determines when a Thread can reliably see writes to variables made by other threads. It defines semantics for volatile, final & synchronized, that makes guarantee of visibility of memory operations across the Threads.
Let's first discuss about Memory Barrier which are the base for our further discussions. There are two type of memory barrier instructions in JMM - read barriers and write barrier.
A read barrier invalidates the local memory (cache, registers, etc) and then reads the contents from the main memory, so that changes made by other threads becomes visible to the current Thread.
A write barrier flushes out the contents of the processor's local memory to the main memory, so that changes made by the current Thread becomes visible to the other threads.
JMM semantics for synchronized
When a thread acquires monitor of an object, by entering into a synchronized block of code, it performs a read barrier (invalidates the local memory and reads from the heap instead). Similarly exiting from a synchronized block as part of releasing the associated monitor, it performs a write barrier (flushes changes to the main memory)
Thus modifications to a shared state using synchronized block by one Thread, is guaranteed to be visible to subsequent synchronized reads by other threads. This guarantee is provided by JMM in presence of synchronized code block.
JMM semantics for Volatile  fields
Read & write to volatile variables have same memory semantics as that of acquiring and releasing a monitor using synchronized code block. So the visibility of volatile field is guaranteed by the JMM. Moreover afterwards Java 1.5, volatile reads and writes are not reorderable with any other memory operations (volatile and non-volatile both). Thus when Thread A writes to a volatile variable V, and afterwards Thread B reads from variable V, any variable values that were visible to A at the time V was written are guaranteed now to be visible to B.

Let's try to understand the same using the following code

Data data = null;
volatile boolean flag = false;

Thread A
data = new Data();
flag = true; <-- writing to volatile will flush data as well as flag to main memory

Thread B
if(flag==true){ <-- as="" barrier="" data.="" flag="" font="" for="" from="" perform="" read="" reading="" volatile="" well="" will="">
use data; <!--- data is guaranteed to visible even though it is not declared volatile because of the JMM semantics of volatile flag.

20.  What will happen if you call return statement or System.exit on try or catch block ? will finally block execute?
This is a very popular tricky Java question and its tricky because many programmer think that finally block always executed. This question challenge that concept by putting return statement in try or catch block or calling System.exit from try or catch block. Answer of this tricky question in Java is that finally block will execute even if you put return statement in try block or catch block but finally block won't run if you call System.exit form try or catch.

19. Can you override private or static method in Java ?
Another popular Java tricky question, As I said method overriding is a good topic to ask trick questions in Java.  Anyway, you can not override private or static method in Java, if you create similar method with same return type and same method arguments that's called method hiding. 

20. What will happen if we put a key object in a HashMap which is already there ?
This tricky Java questions is part of How HashMap works in Java, which is also a popular topic to create confusing and tricky question in Java. well if you put the same key again than it will replace the old mapping because HashMap doesn't allow duplicate keys. 

21. If a method throws NullPointerException in super class, can we override it with a method which throws RuntimeException?
One more tricky Java questions from overloading and overriding concept. Answer is you can very well throw super class of RuntimeException in overridden method but you can not do same if its checked Exception. 

22. What is the issue with following implementation of compareTo() method in Java

public int compareTo(Object o){
   Employee emp = (Employee) emp;
   return this.id - o.id;

23. How do you ensure that N thread can access N resources without deadlock
If you are not well versed in writing multi-threading code then this is real tricky question for you. This Java question can be tricky even for experienced and senior programmer, who are not really exposed to deadlock and race conditions. Key point here is order, if you acquire resources in a particular order and release resources in reverse order you can prevent deadlock. 

24. What is difference between CyclicBarrier and CountDownLatch in Java
Relatively newer Java tricky question, only been introduced form Java 5. Main difference between both of them is that you can reuse CyclicBarrier even if Barrier is broken but you can not reuse CountDownLatch in Java. See CyclicBarrier vs CountDownLatch in Java for more differences.

25. Can you access non static variable in static context?
Another tricky Java question from Java fundamentals. No you can not access static variable in non static context in Java.

Sunday, June 22, 2014


Unix Architecture:

·         Kernel:
The kernel is the heart of the operating system. It interacts with hardware and most of the tasks like memory management, and file management.
·         Shell:
When you type in a command at your terminal, the shell interprets the command and calls the program that you want.
C Shell, Bourne Shell and Korn Shell are most famous shells which are available with most of the Unix variants.
·         Files and Directories: All data in UNIX is organized into files. All files are organized into directories. These directories are organized into a tree-like structure called the file system.

$ ls
$ ls -ltr
$ ls-a
Lists files (not content) in current directory.
-ltr List current directory in detailed format.
-a List current directory including hidden files.

$ cd tempdir
$ cd ..
$ cd ~ jbk/web
Change current directory.
Change directory to tempdir
Move back one directory
Move into jbk’s web directory
$ mkdir trialdir
Make a directory
Make a directory called graphics
$ rmdir  trialdir
Remove directory (must be empty)

$ pwd
Get full path of your current directory
$ cat  filename
Look at the content of file

$ vi filename
Creates a new file if it already does not exist, otherwise opens existing file.

Command mode- default mode of vi editor.
       -Saving file
       -Moving courser
              h     l
save the contents of the editor is :w!
out of vi is :q! or :q.
save and exit together :wq! or :wq.

Insert mode- to insert text into file
$ cat > demo.txt
This text print in above file.
Creating file using cat
$ echo 'The only winning move is not to play.' > demo.txt
Creating file using echo
$ cp file1 web-docs
$ cp file1 file1.bak

Copy whole directory
$ cp -r  sourcedir targetdir
Copy file.
Copy file into directory
Make backup of file1
$ rm file1.bak
$ rm *.tmp
$ rm –i file1.txt
Remove or delete file
Remove all file
Confirmation before file delete
$ mv old.html new.html
Move or rename files.
$ more index.html
Look at file, one page at a time
$ lpr index.html
Send file to printer
$ man ls
$ man mv
Manual pages (help) about command
$ cc HelloWorld.c
C compiler. Will compile c program
cat /etc/issue
$  cat /etc/issue
To find which version of linux using
$ useradd kiran

$  useradd -g groupname                   username

$useradd -g kiran umesh

$ groups username
To add user

To add user in specific group

Will show user belongs to which group
$ userdel kiran
To delete account from the system
$ groupadd developers
To add group
$ passwd kiran
Set password to account
$ ps
Snapshot of current processes

tail -f
$ tail filename
$ tail –n filename

$ tail -f  filename
Shows last few lines.
-n to show last n lines

Shows last 10 lines of file and monitor file for updates. i.e if line added to file tail then continue to output and keep refreshing.

$ find . *.txt

To find files in current directory or its sub directories.
Here . (period) represent  current directory
$ top
Display all system processes
$ grep "this" demo_file

$ grep "this" demo_*
$ grep -i "is" demo_file

To search for specific string containing line in specific file.
To search for specific string in multiple file
Case insensitive search in file.

Please find below screenshot for details
About grep command

chmod (To change file or directory permissions):
While using ls -l command it displays various information related to file permission as follows: $ ls –l demo.txt
-rw-r--r--    1 cliff    user 767392  Mar  6 14:28 demo.txt
^ ^  ^  ^     ^   ^       ^      ^     ^      ^     ^     
| |  |  |     |   |       |      |     |      |     |       
| |  |  |     | owner   group       size      date       time     name
| |  |  |     number of links to file or directory contents
| |  |  permissions for world
| |  permissions for members of group
| permissions for owner of file: permission r = read, w = write, x = execute - =no
Type of file: - = normal file, d=directory, l = symbolic link, and others...
Each permission is assigned a value, as the following table shows, and the total of each set of permissions provides a number for that set.

Octal Permission Representation
No permission
Execute permission
Write permission
Execute and write permission: 1 (execute) + 2 (write) = 3
Read permission
Read and execute permission: 4 (read) + 1 (execute) = 5
Read and write permission: 4 (read) + 2 (write) = 6
All permissions: 4 (read) + 2 (write) + 1 (execute) = 7

$ chmod 755 demo.txt
$ chmod o+wx demo.txt
$ chmod u-x demo.txt
$ chmod g=rx demo.txt
$ chmod o+wx,u-x,g=rx demo.txt

$ chown kiran  filename

The chown command changes the ownership of a file
$ chgrp developers  filename

Changes the group of the given file to developers group.
 | (pipe symbol)
To sort students name we write:
$ who > students.txt
$ sort <  students .txt

Instead of it use pipe:
$ who | sort

$ ls –al | more
The symbol | is the Unix pipe symbol.
Give output of one command is input to other.

< (input redirection)
> (output redirection)
This is simple and fast.
$ ls | tee file

$ ls | tee file1 file2

$ ls | tee –a file

It display the output and also saves it in the file at same time.

This is useful when you wanted to know which data going to store in your file.

-a instruct tee command to append data in file.
$  history
Record (or history) of commands is kept for your login session.
$ programmers

Allow permitted user to execute a command as a superuser.

ALL: Allow sudo access from any terminal (any machine).
(ALL): Allow sudo command to be executed as any user.
ALL: Allow all commands to be executed.

$ gzip readme
$ gzip –c readme
Compress files and save them in .gz format, to occupy less space than original
Compress the file named readme. Creates readme .gz and deletes readme.
-c keeps readme.
$ gunzip readme.gz
Decompress the .gz file
$ tar –cvf   /archives/data-history.tar    data/notes
Tape archive.
It create single file with the content of directory structure.
–cvf to view tar progress
–tvf to view content in tar file
$ rpm -ivh mozilla-mail-1.7.5-17.i586.rpm
$ rpm -Uvh mozilla-mail-1.7.6-12.i586.rpm
$ rpm -ev mozilla-mail
$  rpm -qa
Red Hat Package Manager.
RPM command is used for installing, uninstalling, upgrading RPM packages on Linux system.
Package can be archive file
-ivh  Install the package
-Uvh upgrade the package
-ev erase the package
-qa display installed packages
$ su kiran
$ su root
To change the ownership of a login session to root or to any other user.

$ halt
$ reboot
$ poweroff
Reboot or stop the system
$ kill processname
To kill running process
$ shutdown -h now
$ shutdown -h 20:00
$ shutdown -r now
$ shutdown -c

Shutdown the system in a safe way. shutdown the machine immediately, or schedule a shutdown using 24 hour format.
-h halt the system
-r reboot the system
-c cancel a running shutdown


$ awk '{print;}' employee.txt

$ awk '{print $2,$5;}' employee.txt

Awk command is used to generate
Formatted output.
It uses  search pattern is a regular expression.
If the line has 4 words, it will be stored in $1, $2, $3 and $4 variabe.

NF represents total number of fields in a record.

$2,$5 will print 2nd and 5th colum
$ alias ls="ls -al"
$ alias p="pwd"

p and pwd now work same
Allow user to give simple name for
Complex commands combination
Go to 143rd line of file
$ vim +143 filename.txt
Open file in read only format
$ vim -R filename

To provide extra file handling features
Replaces the word "unix" with "linux" in the file.
$ sed 's/unix/linux/' file.txt
Replaces the second occurrence of the word "unix" with "linux" in a line.
$ sed 's/unix/linux/2' file.txt

Sed command is mostly used to replace the text in a file
$ sort
$ sort names.txt
$ sort -r names.txt

Used to sort
-r for descending order
$ whereis ls
To find out where a specific Unix command exists
$ whatis ls
Single line description about a command.
$ mysql -u root –p root
To connect mysql database

Some basic Unix commands:
cal, date , time , who , whoami , sort , echo, df, du, ping, logout
How to create and run perl script:
1. Create a new text file and type the following exactly as shown:

print "Enter your name: ";
$ name=<STDIN>;
print "Hello, ${name} ... you will soon be a Perl
Save it as hello.pl to a location of your choice.
2. Back at the command prompt, change to the directory where you saved your Perl script.
$ cd c:\perl\scripts
$ perl hello.pl
you'll be prompted to enter your name.
Enter your name: Kiran
Hello, Kiran
... you will soon be a Perl creater!
-e with perl allows you to run code from the command line, instead of having to write your program to a file and then execute it.
$ perl -e 'print "Hello World\n";'
Hello World

To protect your directory:
We need to create two files .htaccess and .htpasswd in our directory

.htaccess file contains security directives for the specific directory

.htpasswd file contains the userids and associated encrypted passwords.
.htaccess file must contain:
AuthUserFile /users/www/userid/welcome_html/class1/.htpasswd
AuthGroupFile /dev/null
AuthName Private
AuthType Basic
<Limit GET>
require user USERID1 USERID2


.To create this file use command

htpasswd -c .htpasswd USERID1