You are on page 1of 43

# 1. Find out duplicate number between 1 to N numbers.

2. Find out middle index where sum of both ends are equal.
3. Write a singleton class.
5. Write a program to reverse a string using recursive algorithm.
6. Write a program to reverse a number.
7. Write a program to convert decimal number to binary format.
8. Write a program to find perfect number or not.
9. Write a program to implement ArrayList.
10. Write a program to find maximum repeated words from a file.
11. Wrie a program to find out duplicate characters in a string.
12. Write a program to find top two maximum numbers in a array.
13. Write a program to sort a map by value.
14. Write a program to find common elements between two arrays.
15. How to swap two numbers without using temporary variable?
16. Write a program to print fibonacci series.
17. Write a program to find sum of each digit in the given number using recursion.
18. Write a program to check the given number is a prime number or not?
19. Write a program to find the given number is Armstrong number or not?
20. Write a program to convert binary to decimal number.
21. Write a program to check the given number is binary number or not?
22. Write a program for Bubble Sort in java.
23. Write a program for Insertion Sort in java.
24. Write a program to implement hashcode and equals.
25. How to get distinct elements from an array by avoiding duplicate elements?
26. Write a program to get distinct word list from the given file.
27. Write a program to get a line with max word count from the given file.
28. Write a program to convert string to number without using Integer.parseInt() method.
29. Write a program to find two lines with max characters in descending order.
30. Write a program to find the sum of the first 1000 prime numbers.
31. Find longest substring without repeating characters.
32. Write a program to remove duplicates from sorted array.

20 String Algorithm based Coding Interview Questions

Here is my collection of some of the most frequently asked String based coding questions from
programming interview. Remember, there are many algorithms to solve the same problem,
and you should know that, mainly to handle follow-up question better. Also remember to
solve same question using both recursion and iteration, as interviewer really like to ask
iterative version if you come up with recursive algorithm and vice-versa. Nevertheless, if you
see your favorite question is not included in list, feel free to suggest, I will include it. You can
also post question asked to you on your interview and you have not find its solution yet. Some
questions are still unsolved or solution is not yet posted on my blog. Also difficult level
increases as you move questions.

1) How to Print duplicate characters from String? (​
solution​
)
programming interviews. You need to write a program in C, C++, Java or Python to print
duplicate characters from a given String, for example if String is ​
"Java"​
then program should
print ​
"a"​
. Bonus points if your program is robust and handle different kinds of input e.g.
String without duplicate, null or empty String etc. Bonus points if you also write unit tests for
normal and edge cases.

2) How to check if two Strings are anagrams of each other? (​
solution​
)
A simple coding problem based upon String, but could also be asked with numbers. You need
to write a Java program to check if two given strings are anagrams of Each other. Two strings
are anagrams if they are written using the same exact ​
letters​
, ignoring space, punctuation
and ​
capitalization​
. Each letter should have the same count in both strings. For example, ​
Army
and ​
Mary​
are anagram of each other.

3) How to program to print first non repeated character from String? (​
solution​
)
One of the most common string interview questions: Find the first non-repeated (unique)
character in a given string. for Example if given String is ​
"Morning"​
then it should print "M".
This question demonstrates efficient use of Hashtable. We scan the string from left to right
counting the number occurrences of each character in a Hashtable. Then we perform a
second pass and check the counts of every character. Whenever we hit a count of 1 we return
that character, that’s the first unique letter. Be prepared for follow-up question for
improving memory efficiency, solving it without hash table as well.

4) How to reverse String in Java using Iteration and Recursion? (​
solution​
)

Your task is to write a program to reverse String in Java without using StringBuffer class. You
also need to provide both iterative and recursive algorithm for String reversal. You can use
other String utility methods e.g. ​
charAt()​
,​
toCharArray()​
or ​
substring()​
from
java.lang.String​
class.

5) How to check if a String contains only digits? (​
solution​
)
You need to write a program to check a String contains only numbers by using Regular
expression in Java. You can use Java API but a solution without using Java API will be better
because that is what interviewer can always ask.

6) How to find duplicate characters in a String? (​
solution​
)
You need to write a program to print all duplicate character and their count in Java. For
example if given String is "Programming" then your program should print
g:2
r:2
m:2

7) How to count number of vowels and consonants in a String? (​
solution​
)
One of easiest String question you will ever see. You have to write a Java program which will
take a String input and print out number of ​
vowels​
and consonants on that String. For
example if input is "Java" then your program should print ​
"2 vowels and 2
consonants"​
. If you get this question on Interview, you should clarify that whether String
can contain numbers, special characters or not e.g. anything other than vowels and
consonants.

8) How to count occurrence of a given character in String? (​
solution​
)
If interviewer ask you to count occurrence of more than one character than you can either
use an array, hash table or ​
data structure. In order to solve this problem, you
are not allowed to do so. Your method must return count of given character, for example if
input String is "Java" and given character is 'a' then it should return 2. Bonus point if you
handle case, null and empty String and come up with unit tests.

9) How to convert numeric String to int? (​
solution​
)

A classical coding interview question based upon String. You need to write a method like
atoi() from C/C++, which takes a numeric String and return its int equivalent. For example, if
you pass "67263" to the program then it should return 67263. Make sure your solution is robust
i.e. it should be able to handle + and - character, null and empty String, integer overflow and
other corner cases. Bonus points if you come up with good unit test cases. By the way, if your
interviewer doesn't mention to you about ​
atoi()​
then you can also use Java API's
parseInt()​
or ​
valueOf()​
method to solve this problem.

10) How to replace each given character to other e.g. blank with %20? (solution)
Write a Java program to replace a given character in a String to other provided character, for
example if you are asked to replace each blank in a String with ​
%20​
, similar to URL encoding
done by browser, so that Server can read all request parameters. For example if input is "Java
is Great" and asked to replace space with %20 then it should be "​
Java%20is%20Great"​
.

11) How to find all permutations of String? (solution)
I have seen this String interview question on many interviews. It has a easy recursive solution
but thinks get really tricky when Interviewer ask you to solve this question without using
recursion. You can use Stack though. Write a program to print all permutations of a String in
Java, for example if input is ​
"xyz"​
then it should print ​
"xyz"​
,​
"yzx"​
,​
"zxy"​
,​
"xzy"​
,
"yxz"​
,​
"zyx".

12) How to reverse words in a sentence without using library method? (solution)
Write a function, which takes a String word and return sentence on which words are reversed
in order e.g. if input is "Java is best programming language", output should be "language
programming best is Java".

13) How to check if String is Palindrome?(solution)
Another easy coding question based upon String, I am sure you must have done this numerous
time. Your program should return true if String is Palindrome, otherwise false. For example, if
the input is ​
, the output should be true, if input is ​
output will be true, and
if input is ​
"Java"​
output should be false.

14) How to remove duplicate characters from String? (solution)

when I interview Java developers. then you can related its behavior to ​ indexOf()​ method from java. ​ second​ . third String is said to be a shuffle of first and second if it can be formed by interleaving the characters of first and second String in a way that maintains the left to right ordering of the characters from each string.g ​ remove(String word. You need to remove duplicate characters from a given string keeping only the first occurrences.This is one of the interesting String question.lang. and ​ third​ . If the target string cannot be found. which also has lots of variants. This is where many developer make mistake of shorting character array of String and removing duplicates. You need to write a Java method which will accept a String and a character to be removed and return a String. The function takes two strings as the input and returns the index where the second string is found. char ch)​ . because if you look closely original order of characters are retained in output. So.g. given these 3 strings write a function that detects whether third String is a valid shuffle of first and second String. third = ​ "dabecf"​is a valid shuffle since it preserves the character ordering of the two strings. indexOf()? (solution) You need to write a function to search for the existence of a string (target) in another string (source). For example. For example if input is "aaaaaaaaaaaaaaaaabbbbcddddeeeeee" it should return "a". You are given 3 strings: ​ first​ . which doesn't has that character e. similar to ​ how you remove duplicates from array​ . Can you get a linear solution (O(n)) if possible? 17) How to return highest occurred character in a String? (solution) You need to write a function to implement algorithm which will accept a string of characters and should find the highest occurrence of the character and display it. 18) Write a program to remove a given characters from String? (solution) One of my favorite coding question. You need to provide both iterative and recursive solution of this method and also has to ​ write JUnit tests . That destroys original order of characters and will not be correct solution in this case. given first = ​ "abc"​ and second = ​ "def"​ . if the input is ​ ‘bananas’​ the output will be ‘​ bans’​ . Pay attention to what output could be. If you are a Java developer. then return -1. For example. This question is also asked as Code and algorithm to check if a given short string is a substring of a main string.String class. 16) Write a program to check if a String contains another String e. 15) How to check if a String is valid shuffle of two String? (solution) One more difficult String algorithm based coding question for senior developers.

String Programming Interview Questions String is the primary and probably most common thing you come across on any programming language and so is with any programming interview. 3) Print all permutation of String both iterative and Recursive way? (​ solution) 4) Write a function to find out longest palindrome in a given string? ​ (solution) .to cover cases like null and empty String. input which only contains letter to be removed. 20) How to sort String on their length in Java? (solution) Write a Program to sort String on their length in Java? Your method should accept an array of String and return a sorted array based upon length of String. There is almost always a question on String whether its related to length or replace but I have always find one or two String programming questions on interviews. It's hard to think about an algorithm to solve this problem until you have practiced good. String which doesn't contain given character etc. Don't forget to write unit tests for your solution. 19) Write a program to find longest palindrome in a string? (solution) This is one of the tough coding question based upon String. What makes it more difficult is the constraint that your solution has O(n) time complexity and O(1) space complexity. 1) Write code to check a String is palindrome or not? (​ solution​ ​ ) Palindrome are those String whose reverse is equal to original.This can be done by using either StringBuffer ​ reverse()​ method or by technique demonstrated in the solution here. 2) Write a method which will remove any given character from a String? ​ (solution) hint​ : you can remove a given character from String by converting it into character array and then using ​ substring()​ method for removing them from output string.

and Performance.g. StringBuilder and StringBuffer in Java?​ (​ answer​ ) Main difference is that String is immutable but both StringBuilder and StringBuffer are mutable. 2) Why String is final in Java? ​ (​ answer​ ) String is final because of same reason it is immutable. Java designers knows that String will be used heavily in every single Java program. Security. 3) How to Split String in Java?​ (​ answer​ ) Java API provides several convenient methods to split string based upon any delimiter e. so they optimized it from the start. . You can even use regular expression to split a big string into several smaller strings. 4) Why Char array is preferred over String for storing password?​ (​ answer​ ) Programming questions on Array Array is one of the topics where most of programming questions is asked. semi colon or colon. There are many and many programming questions on Array and here I have included only some of them which is not very difficult to solve but some of array programming question can be extremely challenging​ . Couple of reasons which I think make sense is implementation of String pool.5) How to find first non repeated character of a given String?​ (​ solution​ ) 6) How to count occurrence of a given character in a String?​ (​ solution​ ) 7) How to check if two String are Anagram?​ (​ solution​ ) 8) How to convert numeric String to int in Java? (​ solution​ ​ ) Some more String related Questions which mostly appear in Java programming interviews: 1) What is difference between String. Also StringBuilder is not synchronized like StringBuffer and that's why faster and should be used for temporary String manipulation. so well prepare this topic. comma.

3. Here is a quick tip to solve this programming question: put the elements of the second array in the ​ Hashtable ​ and for every element of the first array.9) In an array 1-100 numbers are stored. 1.1. O/P all those elements from the first array that are not present in the hash table 13) How do you find second highest number in an integer array? ​ (​ solution​ ) 14) How to find all pairs in array of integers whose sum is equal to given number? (​ solution​ ) 15) How to remove duplicate elements from array in Java?​ (​ solution​ ) 16) How to find largest and smallest number in array?​ (​ solution​ ) 17) How to find top two maximum number in array?​ (​ solution​ ) LinkedList Programming Interview Questions 14) How do you find middle element of a linked list in single pass? To answer this programming question I would say you start with simple solution on which you traverse the LinkedList until you find the tail of linked list where it points to null to ​ find the .0. check whether it’s present in the hash or not. how do you find it? ​ (solution) One trick in this programming questions is by using HashMap or Hashtable .2.4. we can store number as key and its occurrence as value.5 find which number is not present in the second array. one number is missing how do you find it? (​ solution​ ) 10) In an array 1-100 exactly one number is duplicate how do you find it​ ? (​ solution​ ) 11) In an array 1-100 multiple numbers are duplicates. 12) Given two arrays.5 and 2.3. if number is already present in Hashtable then increment its value or insert value as 1 and later on print all those numbers whose values are more than one.

17) How do you reverse a singly linked list? ​ (solution) 18) Difference between linked list and array data structure?​ (​ answer​ ) Binary Tree Programming Interview Questions Binary tree or simply tree is one of favorite topic for most of interviewer and pose real challenge if you struggle with recursion. Programming questions on tree can become increasingly difficult when you think iterative but sometime can be very easy if you come with recursive solution.length of linked list ​ and then reiterating till middle. 15) How do you find 3rd element from last in single pass? ​ (​ solution​ ) This programming question is similar to above and can be solved by using 2 pointers. start second pointer when first pointer reaches third place. so when first pointer reaches end of linked second pointer will point to the middle element. After this answer interviewer will ask you find the middle element in single pass and there you can explain that by doing space-time trade-off you can use two pointers one incrementing one step at a time and other incrementing two step a time. 18) How do you find depth of binary tree? 19) Write code to print InOrder traversal of a tree? 20) Print out all leaf node of a binary tree? . 16) How do you find if there is any loop in singly linked list? How do you find the start of the loop? ​ (​ solution​ ) This programming question can also be solved using 2 pointers and if you increase one pointer one step at a time and other as two steps at a time they will meet in some point if there is a loop.

21) Write a method in Java to check if a tree is a binary search tree or not? 22) How to check if a tree is balanced or not in Java? Programming Questions on Searching and Sorting I have only included two programming questions related to searching and sorting but there are more can be finding on Google. 26) Write code to check whether a no is power of two or not? ​ (​ solution​ ) . 23) Write a program to sort numbers in place using quick sort ? ​ (​ solution​ ) 24) Write a program to implement binary search algorithm in Java or C++? ​ (solution) 25) How do you sort Java object using Comparator? ​ (​ answer​ ) This is another Java specific programming questions and you can check how to sort Object using Comparator and Comparable for answer. Purpose of these programming questions is to see whether programmer is familiar with essential search and sort mechanism or not. 26) Write code to implement Insertion Sort in Java?​ (​ solution​ ) 27) Write code to implement Bubble Sort in Java?​ (​ solution​ ) Programming Questions on Numbers Most of the programming questions are based on numbers and these are the ones which most of us did on college level and mind you they still has value I have seen programmers with experience of 3 years struggle with these programming questions and doesn't solve it some time and take a lot of time which simply shows that they are not in programming in there day to day work.

28) Write code to check whether an integer is Armstrong number or not? (​ solution​ ​ ) Here is a Java program to find Armstrong number. if input is 123 then your function will return false. 30) Write function to compute Nth Fibonacci number? Both iterative and recursive? (​ solution​ ) Check this Java program to print Fibonacci Series using recursion and iteration.g.27) Write a program to check whether a number is palindrome or not? ​ (​ solution​ ) Check out this post which shows how to reverse number in Java and can be used to find if its palindrome or not. 31) How to check if a number is binary? (​ solution​ ) For this question. 32) How to reverse an integer in Java? (​ solution​ ) 33) How to count number of set bits in given integer? (​ solution​ ) 34) How to find sum of digits of a number using recursion? (​ solution​ ) 35) How to swap two numbers without using temp variable? (​ solution​ ) 36) How to find largest of three integers in Java? (​ solution​ ) 37) Write a program to find prime factors of integer? (​ solution​ ) . 29) Write a program to find all prime number up to a given numbers? ​ (​ solution​ ) Here is another Java program to find prime numbers and print them. you can write similar program in C and C++. you need to write a function which will accept an integer and return true if it contains only 0 and 1 e. you can use same logic to write code in any other programming language like C and C++. By using logic demonstrated in this program. for 101 it should return true.

Question: What does the following Java program print?  . These programming questions are sometime based on problems faced by developer itself. You can refer it to answer this question. you can also check that. I have not included many Software design related programming question which I have shared on ​ Top 20 software design questions and answers​ . write a function to return number of ways to climb a ladder with n step. 31) Write a program to find out if two rectangles R1 and R2 are overlapping? 32) You need to write a function to climb n steps you can climb either 1 step at a time or 2 steps a time.38) How to add two integer without using arithmetic operator? (​ solution​ ) General Programming Interview Questions In this category of programming questions I have put questions which are not fit into any data structure but presents a real life problem and you need to provide solution. 33) Write code for Generate Random No in a range from min to max? 34) Write program for word-wrap which should work on any screen size? 35) Design an algorithm to find the frequency of occurrence of a word in an article? 36) Write a program to implement blocking queue in Java? 37) Write a program for producer-consumer problem? This article solves producer consumer problem using BlockingQueue in Java.

Anyway. 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. this is known as method hiding.​ MIN_VALUE​ . Similarly  you cannot override private method in sub class because it's not accessible there.MIN_VALUE​  is greater than 0.​ min(​ Double.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 no matter what.exit​  from try or catch block.MIN_VALUE is 2^(­1074)​ . ​ 0.​ out​ . The ​ Double. where ​ MIN_VALUE​  is  negative. a double constant whose  magnitude is the least among all double values.0d​ ));      }  }  Answer: This questions is tricky because unlike the ​ Integer​ .0 because ​ Double.public​  ​ class​  ​ Test​  {      ​ public​  ​ static​  ​ void​  ​ main​ (​ String​ [] args) {          ​ System. if  you create similar method with same return type and same method arguments in child  class then it will hide the super class method.​ println(​ Math. This question challenge  that misconcept by putting ​ return​  statement in try or catch block or calling  System. I have asked this  question to Java developer having experience up to 3 to 5 years and surprisingly almost  70% candidate got it wrong. but finally block will always execute.      Question : What will happen if you put return statement or System. ​ you can not override private or static method in Java​ . As I said method overriding is a good topic to ask  trick questions in Java.exit​  form try or catch. what  . both the​ MAX_VALUE​  and ​ MIN_VALUE​  of the ​ Double​  class are positive  numbers. So unlike the obvious answer.      Can you override private or static method in Java ?  Another popular Java tricky question. this  program will print 0.

one should use the  method call ​ Double. NaN. Answer of this question is much  more subtle then it looks like.0​  and  other rules that govern the arithmetic calculations involving them.      What will happen if we put a key object in a HashMap which is already there ?  . and ​ ­0.NaN​  always  evaluates to false. multiple inheritance of behaviour as well. because Java does support multiple inheritance of Type  by allowing interface to extend other interfaces. This distinction also get blur because of default method  of Java 8.0 / 0.INFINITY​ . even if x itself is a NaN. Also note that the comparison ​ x == Double. what Java doesn't support is multiple  inheritance of implementation.0 will return? will it throw  Exception? any compile time error?  Answer : This is another tricky question from Double class. See ​ Why  multiple inheritance is not supported in Java​  to answer this tricky Java question. To test if x is a NaN.      Question: What does the the expression 1. if C++ can support direct multiple inheritance than  why not Java is the argument Interviewer often give. Simple answer to this  question is that it will not throw ​ ArithmeticExcpetion​  and  return​ Double. Though Java developer  knows about double primitive type and Double class. this is very close to NULL there. while doing floating point  arithmetic they don't pay enough attention to​ Double. If you know  SQL. See ​ Can you  override private method in Java​  or more details.INFINITY​ . which now provides Java.      Does Java support multiple inheritance ?  This is the trickiest question in Java.isNaN(x)​  to check if given number is ​ NaN​  or not.you do is create another private method with same name in child class.

Question : What does the following Java program print?  public​  ​ class​  ​ Test​  {      ​ public​  ​ static​  ​ void​  ​ main​ (​ String​ [] args) ​ throws​  ​ Exception​  {          ​ char​ [] chars ​ =​  ​ new​  ​ char​ [] {​ '​ \u​ 0097'​ };          ​ String​  str ​ =​  ​ new​  ​ String​ (chars);          ​ byte​ [] bytes ​ =​  str​ . after than we are getting byte  array from that String and printing that byte.Entry object. Now Java will take  Key object form each entry and compare with this new key using equals() method. HashMap is also a popular topic to create confusing and tricky question  in Java. As a matter of  fact.​ out​ .​ toString(bytes));      }  }    Answer: The trikyness of this question lies on character encoding and how String to  byte array conversion works. if you run this program  on Linux or Solaris.getBytes()​  call will return a  byte array that contains one element with a value of ­105 ​ ((byte) 0x97)​ .​ println(​ Arrays. we are first creating a String from a  character array.This tricky Java questions is part of another frequently asked question. Each bucket contains a  linked list of Map. How HashMap  works in Java. In this program.  that's not what the program prints and that's why this question is tricky. the output of the program is operating system and locale dependent. it is reasonable to guess that the ​ str. However.​ getBytes();          ​ System. which just has one character​ '\u0097'​ . which contains both Key and Value. See ​ How  HashMap works in Java​  for more tricky Java questions from HashMap. Since ​ \u0097 ​ is within the 8­bit range of  byte primitive type. Same key will result in  same hashcode and will end up at same position in bucket. you will get different values. if you put the same key again than it will replace the  old mapping because HashMap doesn't allow duplicate keys.  . the above program prints [63]. if  that return true then value object in that entry will be replaced by new value. On a  Windows XP with the US locale. Answer of this question is.

When we call ​ str.  To answer this question correctly. This  explains the output we get from runing this program on Windows machines with a US  locale. So It's possible that if same  character encoding is not used during both encoding and decoding then retrieved value  may not be correct. can we override it with a  method which throws RuntimeException?  One more tricky Java questions from overloading and overriding concept.  it is ​ UTF­8​  and on Windows with a US locale. ?) in all encodings.      What is the issue with following implementation of compareTo() method in Java  public​  ​ int​  compareTo(​ Object​  o){     ​ Employee​  emp ​ =​  (​ Employee​ ) emp;  .getBytes()​  without specifying a character  encoding scheme. the default encoding is​ Cp1252​ . The default encoding scheme is operating system and locale dependent. Answer is you  can very well throw super class of RuntimeException in overridden method but you can  not do same if its checked Exception. The rule that maps each Unicode  character into a byte array is called a character encoding. you need to know about how Unicode characters are  represented in Java char values and in Java strings. the JVM uses the default character encoding of platform to do the  job.      If a method throws NullPointerException in super class. t​ o convert a string to a byte array​ . See ​ Rules of method overriding in Java​  for more  details. Java will always translate  Unicode characters not recognized by the encoding to 63. No matter which character encoding scheme is used. On Linux.getBytes()​ . which represents the  character U+003F (the question mark. In simple word. Java  iterate through all the characters that the string represents and turn each one into a  number of bytes and finally put the bytes together. and what role character encoding  plays in ​ String.

Question : Consider the following Java code snippet. This Java question can be tricky even for experienced and senior programmer. If id becomes negative than ​ subtraction may  overflow​  and produce incorrect result.  who are not really exposed to deadlock and race conditions. and two threads T1 and T2 are modifying  these values as following. See ​ How to override compareTo method in Java  for complete answer of this Java tricky question for experienced programmer.​ out​ . Key point here is order. which is initializing two  variables and both are not volatile.​ id;  }  where id is an integer number ?  Well three is nothing wrong in this Java question until you guarantee that id is always  positive. See ​ how to avoid deadlock in Java​  for a sample code example. This Java question becomes tricky when you can't guaranteed that id is  positive or negative. tricky part is.      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. both are not synchronized  int​  x ​ =​  0;  boolean​  bExit ​ =​  ​ false​ ;    Thread​  1 (not ​ synchronized​ )  x ​ =​  1;   bExit ​ =​  ​ true​ ;    Thread​  2 (not ​ synchronized​ )  if​  (bExit ​ ==​  ​ true​ )   System.​ id ​ ­​  o​ .   ​ return​  this​ .​ println(​ "x="​  ​ +​  x);  . if  you acquire resources in a particular order and release resources in reverse order you  can prevent deadlock.

without  requiring an instantiation of the class to which it belongs. the compilers and tools (like  JavaDoc​ . It also  includes browser plugins for applet execution. which is executed by the JVM. because it is aware of the specific instruction lengths and  other particularities of the underlying hardware platform.  . compile and execute Java  applications.  Each Java source file is compiled into a bytecode file. because method overriding is based upon dynamic binding at runtime and static  methods are statically binded at compile time. without  having to be rewritten or recompiled by the programmer for each separate platform.  2.}  public​  ​ String​  getDescription(​ String​  obj){     ​ return​  obj;  }  and  public​  ​ void​  getDescription(​ String​  obj){     ​ return​  obj;  }      General Questions about Java  1. What is JVM ? Why is Java called the “Platform Independent Programming Language”  ?​  A Java virtual machine (JVM) is a process ​ virtual machine​  that can execute Java ​ bytecode​ . The Java Development Kit (JDK) is the full  featured Software Development Kit for Java. in order for a user to develop. What is the Difference between JDK and JRE ?​  The Java Runtime Environment (JRE) is  basically the Java Virtual Machine (JVM) where your Java programs are being executed.  3. and ​ Java Debugger​ ). A user cannot override ​ static methods  in Java​ . including the JRE. Java was  designed to allow application programs to be built that could be run on any platform. What does the “static” keyword mean ? Can you override private or static method in  Java ?​  The static keyword denotes that a member variable or method can be accessed. A Java  virtual machine makes this possible. A static method is not associated with any  instance of a class so the concept is not applicable.

What is the difference between an Interface and an Abstract class ?​  Java provides and  supports the creation both of​ abstract classes​  and interfaces. Though. When an object is passed by reference. but is able to implement more than one  interfaces. Java does support copy constructors like C++.  . Does Java support multiple inheritance ?​  No. an abstract  class may contain both abstract and non­abstract methods. it must implement all its declared  methods. even if changes are made to that object. but the  difference lies in the fact that Java doesn’t create a default copy constructor if you don’t write  your own. a class may not implement all declared methods of an abstract  class.  Also check out the ​ Abstract class and Interface differences for JDK 8​ .  ● A class may implement a number of Interfaces.  9. but can be invoked if it contains a main method. the sub­class must also be declared as abstract.  8. Thus. but can extend only one abstract  class. Thus. An abstract class may  contain non­final variables. it  doesn’t affect the original value. but they differ in the following features:  ● All methods in an interface are implicitly abstract.  ● Variables declared in a Java interface is by default final.  10. this means that the  actual object is not passed. are also reflected in all places. Java does not support multiple inheritance.  Each class is able to extend only on one class. A member of an abstract class can  either be private.  ● Members of a Java interface are public by default. rather a reference of the object is passed. Both implementations share some  common characteristics. protected or public. However. Finally. in this case. On the other hand. any changes made  by the external method.own unique parameter list. An abstract class also  cannot be instantiated. What are pass by reference and pass by value ?​  When an object is passed by value.  ● Abstract classes can implement interfaces without even providing the implementation  of interface methods.  ● In order for a class to implement an interface.  ● An interface is absolutely abstract and cannot be instantiated. this  means that a copy of the object is passed.

How do you ensure that N threads can access N resources without deadlock ?​  A very  simple way to avoid deadlock while using N threads is to impose an ordering on the locks and  force each thread to follow that ordering. The result is that both processes wait endlessly. Each Java ​ Collection​  contains the ​ iterator​  method that returns an ​ Iterator  instance.  16.is basically a guardian that watches over a sequence of synchronized code and ensuring that  only one thread at a time executes a synchronized piece of code. before proceeding. Thus. which is an ordered collection and can contain duplicate elements. while some other collections don’t. What’s a deadlock ?​  A condition that occurs when ​ two processes are waiting for each other  to complete​ . The thread is not allowed to execute the code until it obtains the lock.  20. Each monitor is associated  with an object reference. Why Collection doesn’t extend Cloneable and Serializable interfaces ?​  The ​ Collection  interface specifies groups of objects known as elements.  Java Collections  18. ​ 21. The most basic interfaces that reside in the Java Collections Framework are:  ● Collection​ . which represents a group of objects known as its elements. which is an object that maps keys to values and cannot contain duplicate keys. What are the basic interfaces of Java Collections Framework ?​  ​ Java Collections Framework  provides a well designed set of interfaces and classes that support operations on a collections  of objects. What is an Iterator ?​  The ​ Iterator​  interface provides a number of methods that are able to  iterate over any​ Collection​ . Each concrete implementation of a  Collection​  can choose its own way of how to maintain and order its elements.  the concrete implementations of collections should decide how they can be cloned or serialized. if all threads lock and unlock the mutexes in the  same order.  17.  19. The semantics and the implications of  either cloning or serialization come into play when dealing with actual implementations.  ● List​ . Some collections  allow duplicate keys. Thus.  ● Map​ .  ● Set​ . which is a collection that cannot contain duplicate elements. no deadlocks can arise. Iterators are ​ capable of removing elements from the underlying collection​  during the  iteration. What differences exist between Iterator and ListIterator ?​  The differences of  these elements are listed below:  .

the ​ hashCode​  method is used in order to determine where the  specified key will be stored. a ​ HashMap​  uses  the ​ hashCode​  and ​ equals​ methods to determine the index of the key­value pair and to detect  duplicates. What is difference between fail­fast and fail­safe ?​  The ​ Iterator's​  fail­safe property works  with the clone of the underlying collection and thus. Some important  characteristics of a ​ HashMap​  are its capacity. its load factor and the threshold resizing. etc. replacing an element. nor null values.concurrent are fail­safe. Fail­fast iterators throw a​ ConcurrentModificationException​ .  25. If the key exists. while the collection classes  in java. getting the index position for previous  and next elements.  22. the ​ HashMap   calculates the hash value of the key and stores the pair in the appropriate index inside the  collection.  23. More specifically. What differences exist between HashMap and Hashtable ?​  Both the ​ HashMap​  and  Hashtable​  classes implement the Map interface and thus.● An ​ Iterator​  can be used to traverse the ​ Set​  and ​ List​  collections. its value is updated with the new value. How HashMap works in Java ?​  A ​ HashMap in Java stores key­value pairs​ . while the ​ ListIterator​  can  be used to iterate only over ​ Lists​ . it is not affected by any modification in the  collection. Since different keys may produce the same hash value. Therefore.util package are fail­fast. the implementation of both methods is crucial to the accuracy and efficiency  of the ​ HashMap​ .util.  . the ​ equals  method is used. When the put method is invoked. they differ in the following features:  ● A ​ HashMap​  allows the existence of null keys and values. in order to put and retrieve  elements to and from the collection respectively. such  as adding an element.  ● The ​ Iterator​  can traverse a collection only in forward direction.  ● The ​ ListIterator​  implements the ​ Iterator​  interface and contains extra functionality.  However. in order to determine whether the specified key actually exists in the collection  or not.  24. The ​ HashMap  requires a hash function and uses ​ hashCode​  and equals methods. have very similar characteristics. All the collection classes in java. while  fail­safe iterator never throws such an exception. while the ​ ListIterator​  can  traverse a ​ List​  in both directions. What is the importance of hashCode() and equals() methods ?​  In Java. while a ​ Hashtable​  doesn’t allow  neither null keys.

the insertion operation for  an unordered array takes constant time of O(1). Java provides the ​ Comparator​  interface.​  Java provides  the ​ Comparable​  interface.  31. we can  provide a Comparator that is responsible for ordering the elements of the ​ PriorityQueue​ . we usually use  the Big­O notation to chose the best implementation to use. based on a priority  heap and its elements are ordered in their natural order. based on time. At the time of its creation. or  those objects that don’t have any comparator associated with them. which is O (n). It returns a negative integer. This method  compares two objects. equal to. What is the tradeoff between using an unordered array versus an ordered array ?​  The  major advantage of an ordered array is that the search times have time complexity of O(log n).28. called​ compare​  and ​ equals​ . it returns a  negative integer. zero. only if the specified object is also a comparator and  it imposes the same ordering as the comparator. What is Comparable and Comparator interface ? List their differences.  compared to that of an unordered array. because the elements with higher  values must be moved to make room for the new element. The Big­O notation can also be used to describe other behavior such as  memory consumption. or a positive integer to indicate that the input object is less than. Since the collection classes are actually data structures. The first method compares its two input arguments and  imposes an order between them. Specifically. The disadvantage of an ordered array is  that the insertion operation has a time complexity of O(n). called ​ compareTo​ . The method returns true. or greater than the second. Finally. in order to impose an order between them. A  PriorityQueue​  doesn’t allow ​ null values​ . Big­O notation can give a good indication about performance for large amounts of  data. What do you know about the big­O notation and can you give some examples with  respect to different data structures ?​  The ​ Big­O notation​  simply describes how well an  algorithm scales or performs in the worst case scenario as the number of elements in a data  structure increases. those objects that doesn’t provide natural ordering. Instead. What is Java Priority Queue ?​  The ​ PriorityQueue​  is an unbounded queue. or a positive integer to  indicate that the first argument is less than. which contains only one method.  . equal or  greater than the existing object. The second  method requires an object as a parameter and aims to decide whether the input object is equal  to the comparator. zero. which contains two  methods. memory and  performance.  30. the Java  PriorityQueue​  is not thread­safe and it requires O(log(n)) time for its enqueing and dequeing  operations.  29.

● Return zero­length collections or arrays as opposed to returning a null in case the  underlying collection is actually empty. in order for the resources to be reclaimed and reused. instead of an ​ ArrayList​ . What is the purpose of garbage collection in Java. What is the difference between HashSet and TreeSet ?​  The ​ HashSet​  is Implemented using  a hash table and thus. something which is not possible with ​ Enumerations​ .  34. readability.  ● Use immutable classes provided by the Java Development Kit (JDK) as a key in a  Map.  ● Program in terms of interface not implementation. the ​ Iterator​  is  much safer compared to ​ Enumeration​ . and contains  methods have time complexity of O(logn). The add. because other threads are not able to modify the collection  object that is currently traversed by the iterator. is  very crucial for its performance. Thus. by using  Generics you avoid the​ ClassCastException​  during runtime. the add. What are some of the best practices relating to the Java Collection framework ?  ● Choosing the right type of the collection to use. What’s the difference between Enumeration and Iterator interfaces ?​  ​ Enumeration​  is  twice as fast as compared to an Iterator and uses very less memory. The elements in a ​ TreeSet​  are sorted. Also. remove. a ​ TreeSet​  is implemented using  a tree structure. and robustness. in order to avoid the implementation of the ​ hashCode​  and equals methods for our  custom class. and when is it used ?​  The purpose  of garbage collection is to identify and discard those objects that are no longer needed by the  application.  . On the other hand.  ● Always use Generics for type­safety.  33. Also.  ● Some collection classes allow us to specify their initial capacity. remove. its elements are not ordered. we shall use an ​ Array​ . and contains methods of  a ​ HashSet​  have constant time complexity O(1). we can use it to avoid  rehashing or resizing. and thus.32. For example if the size of the elements is fixed and  know a priori. ​ Iterators​ allow the caller to remove elements  from the underlying collection. However. based on the application’s needs.  Garbage Collectors  35. if we have an  estimation on the number of elements that will be stored.

the  serial collector is usually adequate for most small applications (those requiring heaps of up to  approximately 100MB on modern processors). However.  37. Dead objects are those which will never be accessible by the  application. If you look carefully at the output of the garbage collector. Live objects are accessible by the application and will not be a  subject of garbage collection. What does System.36.  38. When is the finalize() called ? What is the purpose of finalization ?​  The finalize method  is called by the garbage collector. in order to start a garbage collection. If an object reference is set to null. this it is up to the Java Virtual  Machine (JVM) to start the garbage collection immediately or later in time.  42.gc() and Runtime. the object will be available for garbage collection in the next  cycle of the garbage collector.  .gc() methods do ?​  These methods can be used as  a hint to the JVM. it  can trigger a full garbage collection.  40. This is the reason why correct sizing  of PermGen space is important to avoid frequent full garbage collections. What is the difference between Serial and Throughput Garbage collector ?​  The  throughput garbage collector uses a parallel version of the young generation collector and is  meant to be used with applications that have medium to large data sets. just before releasing the object’s memory. Heap memory  consists of live and dead objects. What is structure of Java Heap ? What is Perm Gen space in Heap ?​  The ​ JVM has a  heap​  that is the runtime data area from which memory for all class instances and arrays is  allocated. will the Garbage Collector immediately free the  memory held by that object ?​  No. Such objects occupy the  heap memory space until they are eventually collected by the garbage collector. but have not been collected by the garbage collector yet. Also check our  article​ Java 8: PermGen to Metaspace​ .  39. On the other hand. Does Garbage collection occur in permanent generation space in JVM ?​  Garbage  Collection does occur in PermGen space and if PermGen space is full or cross a threshold. Heap memory for objects is reclaimed by an  automatic memory management system which is known as a garbage collector. It is created at the JVM start­up. When does an Object becomes eligible for Garbage collection in Java ?​  A Java object  is subject to garbage collection when it becomes unreachable to the program in which it is  currently used. It is normally  advised to release resources held by the object inside the finalize method.  you will find that PermGen space is also garbage collected.  41.

47. What is the importance of finally block in exception handling ?​  A finally block will  always be executed. etc.  database connections.  45. which is called by the Java  Virtual Machine (JVM) just before an object is garbage collected. What is the difference between Exception and Error in java ?​  ​ Exception​  and ​ Error​  classes  are both subclasses of the ​ Throwable​  class. so the callers of that method can guard against possible  exceptions. The ​ Exception​  class is used for exceptional conditions  that a user’s program should catch. The ​ Error​ class defines exceptions that are not excepted to  be caught by the user program. What are the two types of Exceptions in Java ? Which are the differences between  them ?​  Java has two types of exceptions: checked exceptions and unchecked exceptions. Finalize is a protected method of the Object class.  if they can be thrown by the execution of the method or the constructor. On the contrary. What will happen to the Exception object after exception handling ?​  The ​ Exception  object will be garbage collected in the next garbage collection. checked exceptions must be declared  in a method or a constructor’s throws clause.  Last thing to mention is that the finally block is used to release resources like I/O buffers.Exception Handling  43. the throws clause is used to  indicate those exceptions that are not handled by a method. On the other hand. multiple exceptions are separated by a comma. Even in the case where the  catch statement is missing and an exception is thrown.  45. How does finally block differ from finalize() method ?​  A finally block will be executed  whether or not an exception is thrown and is used to release those resources held by the  application.  44. and propagate outside  the method or constructor boundary.  46. See here for tips on ​ Java exception handling​ . whether or not an exception is actually thrown.  Unchecked exceptions do not need to be declared in a method or a constructor’s throws clause. Finally. the finally block will still be executed. Each method must explicitly specify  which exceptions does not handle. What is the difference between throw and throws ?​  The throw keyword is used to  explicitly raise a exception within the program.  Java Applets  .

without having to  concern themselves with the underlying details of a particular database.A pool of database connections is obtained at start up by the application server and  is maintained in a pool. Also. Explain the role of Driver in JDBC. this cost is very high and a large number of resources is  consumed. ​ ResultSet​  and ​ Driver​ .forName method ?​  This method is used to method is used to  load the driver that will establish a connection to the database.​  The JDBC Driver provides vendor­specific  implementations of the abstract classes provided by the JDBC API. the request is returned to the pool and can be used to satisfy  future requests. Stored procedures may take input values from the user  and may return a result. What is the advantage of PreparedStatement over Statement ?​  PreparedStatements are  precompiled and thus. ​ JDBC enables developers to write database applications in Java​ .​  A​ CallableStatement​  is used to execute stored procedures.JDBC  72.  75.The method that prepares a ​ CallableStatement​  is the following:  1  CallableStament. Especially. which is used to prepare a  CallableStatement.  73. A request for a connection is served by a ​ connection residing in the  pool​ . when the number of  database clients increases. because it offers  security and modularity. What is the use of CallableStatement ? Name the method. Stored procedures  are stored and offered by a database.​ their performance is much better​ . What does Connection pooling mean ?​  The interaction with a database can be costly.  76.  Remote Method Invocation (RMI)  . The usage of stored procedures is highly encouraged. PreparedStatement objects can  be reused with different input values to their queries.sql package:​ Connection​ .prepareCall();  77.  74.  PreparedStatement​ . ​ CallableStatement​ . In the end of the connection. ​ Statement​ .  regarding the opening and closing of database connections. What is the purpose Class. Each driver must provide  implementations for the following classes of the java. What is JDBC ?​  JDBC is an abstraction layer that allows users to choose between  databases.

81. A class that implements a  remote interface should declare the remote interfaces being implemented. This  layer interprets and manages references made from clients to the remote service  objects.  ● Remote Reference Layer​ : The second layer of the RMI architecture deals with the  interpretation of references made from the client to the server’s remote objects. What is the basic principle of RMI architecture ?​  The RMI architecture is based on a very  important principle which states that the definition of the behavior and the implementation of that  behavior. Check some ​ RMI Tips here​ . Remote Method Invocation (RMI)  can also be seen as the process of activating a method on a remotely running object. What is the role of Remote Interface in RMI ?​  The Remote interface serves to identify  interfaces whose methods may be invoked from a non­local virtual machine. as well as some firewall penetration  strategies. define the  constructor for each remote object and provide an implementation for each remote method in all  remote interfaces.  . It provides basic connectivity.78. RMI offers  location transparency because a user feels that a method is executed on a locally running  object. are separate concepts. RMI allows the code that defines the behavior and the code  that implements the behavior to remain separate and to run on separate JVMs. Any object that is a  remote object must directly or indirectly implement this interface. What are the layers of RMI Architecture ?​  The RMI architecture consists of the following  layers:  ● Stub and Skeleton layer​ : This layer lies just beneath the view of the developer.  80.  ● Transport layer​ : This layer is responsible for connecting the two JVM participating in  the service. This layer is based on TCP/IP connections between machines in a  network. This  layer is responsible for intercepting method calls made by the client to the interface  and redirect these calls to a remote RMI Service. with support for direct transfer  of serialized Java classes and distributed garbage collection. The connection is a one­to­one (unicast) link. What is RMI ?​  The Java Remote Method Invocation (Java RMI) is a Java API that performs  the object­oriented equivalent of remote procedure calls (RPC).  79.

which is responsible for executing the method on the remote object.  ● It unmarshals the return value or an exception if the method has not been  successfully executed. which can be used at a later time. while the  rebind method is responsible for rebinding the specified name to a new remote object.  Each method of the Naming class takes as one of its arguments a name that is a String in URL  format.  ● Start the rmiregistry. What are the steps involved to make work a RMI program ?​  The following steps must be  involved in order for a RMI program to work properly:  ● Compilation of all source files. What is the role of the java. the binding is replaced.rmi.  ● It waits for the result of the method invocation and execution.  ● It returns the value to the caller. What is the role of stub in RMI ?​  A stub for a remote object acts as a client’s local  representative or proxy for the remote object. The caller invokes a method on the local stub.  83. In case a  binding exists for that name.  85.  84. What is meant by binding in RMI ?​  Binding is the process of associating or registering a  name for a remote object.  ● Run the client program.  .rmi. it undergoes the following steps:  ● It initiates a connection to the remote JVM containing the remote object.82.Naming class provides  methods for storing and obtaining references to remote objects in the remote object registry. in order to look up that remote  object. What is the difference between using bind() and rebind() methods of Naming Class ?  The bind method bind is responsible for binding the specified name to a remote object.  ● It marshals the parameters to the remote JVM.  ● Generatation of the stubs using rmic.  ● Start the RMIServer. A remote object can be associated with a name using the bind or rebind methods of the  Naming class. When a stub’s method is  invoked.Naming Class ?​  The java.  86.

88. provide dynamic content and manage state information that  does not exist in the stateless HTTP protocol. Each servlet must implement it either directly or  indirectly.  92. Thus. Since RMI  involves remote object references across JVM’s. a servlet is a  .servlet.​  When an application wants to pass its memory  objects across a network to another host or persist it to storage. Servlets are mostly used to process or store  data submitted by an HTML form.  90. and later.GenericServlet or javax. called object  serialization where an object can be represented as a sequence of bytes and includes the  object’s data. either by extending javax. Explain Marshalling and demarshalling.  Servlets  91.  93.servlet.​  The core abstraction that must be implemented by  all servlets is the javax. What is DGC ? And how does it work ?​  DGC stands for Distributed Garbage Collection. in order to be stored on  disk. What is a Servlet ?​  ​ The servlet​  is a Java programming language class used to process  client requests and generate dynamic web content.  Remote Method Invocation (RMI) uses DGC for automatic garbage collection. which use downloaded  code. and the types of data stored in the  object. What is the purpose of using RMISecurityManager in RMI ?​  RMISecurityManager  provides a security manager that can be used by RMI applications.  89.  Finally.Servlet interface. The class loader of RMI will not download any classes from remote locations.servlet. This process is called marshalling and the revert  operation is called demarshalling. the in­memory representation  must be converted to a suitable format.HTTPServlet. What is the difference between an Applet and a Servlet ?​  An Applet is a client side java  program that runs within a Web browser on the client machine.​  Java provides a mechanism. On the other hand. Explain the architechure of a Servlet. garbage collection can be quite difficult.87. Explain Serialization and Deserialization. as well as information about the object’s type. DGC  uses a reference counting algorithm to provide automatic memory management for remote  objects. Deserialisation is the reverse process of converting  an object from its flattened state to a live object. each servlet is able to serve multiple requests in parallel using multithreading.http. serialization can be seen as a way of flattening objects. if the  security manager has not been set. read back and reconstituted.

the Servlet  object handles all subsequent requests coming from that client. Finally. What is the difference between GenericServlet and HttpServlet ?​  GenericServlet is a  generalized and protocol­independent servlet that implements the Servlet and ServletConfig  interfaces. ​ doPOST​ : The POST method overcomes the limit imposed by the GET request.  Finally. Check ​ Servlet examples here​ .  On the other hand. used almost exclusively for the Web. Finally.​  On every client’s request. Also. Thus.  which contain various types of markup language and dynamic content in response to requests. and is embedded with a  servlet tag. Those servlets extending the GenericServlet class shall override the service method.  97.  96. When a Web page is accessed by a browser. the Servlet Engine loads the  servlets and invokes its init methods.  the values of the request are made visible and thus. while a servlet does not have a user interface. a service­oriented web application implements the endpoint of a web  service. Instead. the servlet is removed by calling the server’s destroy  method. Then. There are two types of web applications: presentation­oriented and  service­oriented. A presentation­oriented Web application generates interactive web pages. the Web server  . What is meant by a Web Application ?​  A Web application is a dynamic extension of a  Web or application server. by  sending the values of the request inside its body. Explain the life cycle of a Servlet. your servlet must extend the HttpServlet instead. sensitive information must not be passed in  that way. the sensitive information passed through a POST request is  not visible to an external client. The most frequent use of SSI is to include the contents of one or more files into a  Web page on a Web server. by invoking the service method  for each request separately. there is no limitations on the number of  values to be sent across. there is a limit on the number of characters  and subsequently on the number of values that can be used in a client’s request.An applet can use the user interface  classes. In general. in order for the servlet to be initialized. Furthermore. a servlet waits for client’s HTTP  requests and generates a response in every request.server side component that runs on the web server.  95. What is a Server Side Include (SSI) ?​  Server Side Includes (SSI) is a simple interpreted  server­side scripting language. in order to develop an HTTP servlet for use on the Web that serves requests using the  HTTP protocol.  94. What is the difference between doGet() and doPost() ?​  ​ doGET​ : The GET method appends  the name­value pairs on the request’s URL.  98. a Web application can be seen as a collection of servlets installed under a  specific subset of the server’s URL namespace.