Friday 18 September 2015

Java Exception and Error Interview Questions


Here is my list of frequently asked questions from Java Error and Exception topics in various programming interviews to Java and J2EE developers.  I have also shared my answers for these questions for quick revision, and provided source for more in depth understanding. I have tried to include questions of various difficulty level, including simplest of simple for freshers and some tricky questions for senior Java developers. If you think, there is a good question, which is not included in this list, please feel free to share it via comment. You can also share error handling questions asked to you on interviews or any question, for which you don’t know the answer.


1) What is Exception in Java?
This is always been first interview question on Exception and mostly asked on fresher level interviews. I haven't seen anybody asking about what is Exception in senior and experienced level interviews, but this is quite popular at entry level. In simple word Exception is Java’s way to convey both system and programming errors. In Java Exception feature is implemented by using class likeThrowable, Exception, RuntimeException and keywords like throw, throws, try, catch and finally. All Exception are derived form Throwable class. Throwable further divides errors in too category one is java.lang.Exception and other is java.lang.Error.  java.lang.Error deals with system errors like java.lang.StackOverFlowError orJava.lang.OutOfMemoryError while Exception is mostly used to deal with programming mistakes, non availability of requested resource etc.

2) What is difference between Checked and Unchecked Exception in Java ?
This is another popular Java Exception interview question appears in almost all level of Java interviews. Main difference between Checked and Unchecked Exception lies in there handling. Checked Exception requires to be handled at compile time using try, catch and finally keywords or else compiler will flag error. This is not a requirement for Unchecked Exceptions. Also all exceptions derived from java.lang.Exception classes are checked exception, exception those which extends RuntimeException, these are known as unchecked exception in Java. You can also check next article for more differences between Checked and Unchecked Exception.


3) What is similarity between NullPointerException and ArrayIndexOutOfBoundException in Java?
This is Java Exception interview question was not very popular, but appears in various fresher level interviews, to see whether candidate is familiar with concept of checked and unchecked exception or not. By the way answer of this interview question is both of them are example of unchecked exception and derived form RuntimeException. This question also opens door for difference of array in Java and C programming language, as arrays in C are unbounded and never throw ArrayIndexOutOfBoundException.


4) What best practices you follow while doing Exception handling in Java ?
This Exception interview question in Java is very popular while hiring senior java developer of Technical Lead. Since exception handling is crucial part of project design and good knowledge of this is desirable. There are lot of best practices, which can help to make your code robust and flexible at same time, here are few of them:

1) Returning boolean instead of returning null to avoid NullPointerException at callers end. Since NPE is most infamous of all Java exceptions, there are lot of techniques and coding best practices to minimize NullPointerException. You can check that link for some specific examples.

2) Non empty catch blocks. Empty catch blocks  are considered as one of the bad practices in Exception handling because they just ate Exception without any clue, at bare minimum print stack trace but you should do alternative operation which make sense or defined by requirements.

3) Prefer Unchecked exception over checked until you have a very good reason of not to do so. it improves readability of
code by removing boiler plate exception handling code
.
4) Never let your database Exception flowing till client error. since most of application deal with database and SQLException is a checked Exception in Java you should consider handling any database related errors in DAO layer of your application and only returning alternative value or something meaningful RuntimeException which client can understand and take action.

5) calling close() methods for connections, statements, and streams on finally block in Java.

I have already shared lot of these in my post Top 10 Java exception handling best practices, you can also refer that for more knowledge on this topic.

5) Why do you think Checked Exception exists in Java, since we can also convey error using RuntimeException ?
This is a controversial question and you need to be careful while answering this interview question. Though they will definitely like to hear your opinion, what they are mostly interested in convincing reason. One of the reason I see is that its a design decision, which is influenced by experience in programming language prior to Java e.g. C++. Most of checked exceptions are in java.io package, which make sense because if you request any system resource and its not available, than a robust program must be able to handle that situation gracefully. By declaring IOException as checked Exception, Java ensures that your provide that gracefully exception handling. Another possible reason could be to ensuring that system resources like file descriptors, which are limited in numbers, should be released as soon as you are done with that using catch or finally block. Effective Java book from Joshua Bloch has couple of items in this topic, which is again worth reading.


6) What is difference between throw and throws keyword in Java?
One more Java Exception interview questions from beginners kitty. throw and throws keyword may look quite similar, especially if you are new to Java programming and haven't seen much of it. Though they are similar in terms that both are used in Exception handling, they are different on how and where they are used in code. throws keyword is used in method signature to declare whichchecked exception method can throw, you can also declare unchecked exception, but that is not mandatory by compiler. This signifies lot of things like method is not going to handle Exception instead its throwing it, if method throws checked Exception then caller should provide compile time exception handling etc. On the other hand throw keyword is actually used to throw any Exception. Syntactically you can throw any Throwable (i.e. Throwable or any class derived from Throwable) , throw  keyword transfers control of execution to caller so it can be used in place of return keyword. Most common example of using throw in place of return is throwing UnSupportedOperationException from an empty method as shown below :

private static void show() {
    throw new UnsupportedOperationException("Not yet implemented");
}

See this article for more differences between these two keywords in Java.


7) What is Exception chaining in Java?
Exception chaining is a popular exception handling concept in Java, where another exception is thrown in response of an exception and creating a chain of Exceptions. This technique mostly used to wrap a checked exception into an unchecked or RuntimeException. By the way if you are throwing new exception due to another exception then always include original exception so that handler code can access root cause by using methods like getCause() and initCause().


8) Have you written your own custom Exception in Java? How do you do that?
Ofcourse most of us has written custom or business Exceptions like AccountNotFoundExcepiton. Main purpose of asking this Java Exception interview question is to find out how you use this feature. This can be used for sophisticated and precise exception handling with tweak involved in whether you would choose a checked or unchecked exception. By creating a specific exception for specific case, you also gives lot of options to caller to deal with them elegantly. I always prefer to have a precise exception than a general exception. Though creating lots of specific exceptions quickly increase number of classes in your project, maintaining a practical balance between specific and general exceptions are key to success.


9) What changes has been introduced in JDK7 related to Exception handling in Java ?
A relatively new and recent Exception interview question in Java. JDK7 has introduced two major feature which is related to Error and Exception handling,  one is ability to handle multiple exception in one catch block, popularly known as multi cache block and other is ARM blocks in Java 7 for automatic resource management, also known as try with resource. Both of these feature can certainly help to reduce boiler plate code required for handling checked exceptions in Java and significantly improves readability of code. Knowledge of this feature, not only helps to write better error and exception code in Java, but also helps to do well during interviews. I also recommend reading Java 7 Recipes book to get more insight on useful features introduced in Java 7, including these two.


10) Have you faced OutOfMemoryError in Java? How did you solved that?
This Java Error interview questions is mostly asked on senior level Java interviews and here interviewer is interested on your approach to tackle dangerous OutOfMemoryError. Admit it we always face this error no matter which kind of project you are working so if you say no it doesn't go very well with interviewer. I suggest even if you are not familiar or not faced it in reality but have 3 to 4 years of experience in Java, be prepare for it. At the same time, this is also a chance to impress interviewer by showing your advanced technical knowledge related to finding memory leaks, profiling and debugging. I have noticed that these skills almost always creates a positive impression. You can also see my post on how to fix java.lang.OutOfMemoryError for more detail on this topic.


11) Does code form finally executes if method returns before finally block or JVM exits ?
This Java exception interview question can also be asked in code format, where given a code with System.exit() in try block and something in finally block. It’s worth knowing that, finally block in Java executes even when return keyword is used in try block. Only time they don’t execute is when you call JVM to exit by executing System.exit(0)from try block in Java.


12) What is difference in final, finalize and finally keyword in Java?
Another classic interview question in core Java, this was asked to one of my friend on his telephonic interview for core Java developer with Morgan Stanley. final and finally are keyword, while finalize is method. final keyword is very useful for creating ad Immutable class in Java By making a class final, we prevent it from being extended, similarly by making a method final, we prevent it from being overridden,. On the other hand, finalize() method is called  by garbage collector, before that object is collected, but this is not guaranteed by Java specification. finally keyword is the only one which is related to error and exception handling and you should always have finally block in production code for closing connection and resources. See here for more detailed answer of this question.



13) What is wrong with following code :

 public static void start() throws IOException, RuntimeException{
    throw new RuntimeException("Not able to Start");
 }

 public static void main(String args[]) {
    try {
          start();
    } catch (Exception ex) {
            ex.printStackTrace();
    } catch (RuntimeException re) {
            re.printStackTrace();
    }
 }


This code will throw compiler error on line where RuntimeException  variable “re” is written on catch block. since Exception is super class of RuntimeException, all RuntimeException thrown by start() method will be captured by first catch block and code will never reach second catch block and that's the reason compiler will flag error as  “exceptionjava.lang.RuntimeException has already been caught".


14) What is wrong with following code in Java:

public class SuperClass {  
    public void start() throws IOException{
        throw new IOException("Not able to open file");
    }
}

public class SubClass extends SuperClass{  
    public void start() throws Exception{
        throw new Exception("Not able to start");
    }
}

In this code compiler will complain on sub class where start() method gets overridden. As per rules of method overriding in Java, an overridden method can not throw Checked Exception which is higher in hierarchy than original method. Since here start() is throwing IOException in super class, start() in sub class can only throw either IOException or any sub class of IOException but not super class of IOException e.g. Exception.


15) What is wrong with following Java Exception code:

public static void start(){
   System.out.println("Java Exception interivew question Answers for Programmers");
}

public static void main(String args[]) {
   try{
      start();
   }catch(IOException ioe){
      ioe.printStackTrace();
   }
}
  
In this Java Exception example code, compiler will complain on line where we are handling IOException, since IOException is a checked Exception and start() method doesn't throw IOException, so compiler will flag error as "exception java.io.IOException is never thrown in body of corresponding try statement", but if you change IOException to Exception compiler error will disappear because Exception can be used to catch all RuntimeException which doesn't require declaration in throws clause. I like this little tricky Java Exception interview question because its not easy to figure out result by chaining IOException to Exception. You can also check Java Puzzlers by Joshua Bloch and Neil Gafter for some tricky questions based on Java Errors and Exceptions.

These are some of Java Error and Exception interview questions, I have mostly seen in both fresher and experienced level of Java interviews. There are a lot more questions on Exception which I haven't included and if you think you have a good question missed out than let me know and I will make effort to include it on this list of java exceptions question and answers. One last question of Java Exception I am leaving for you guys is "Why Java Exception considered to be better alternative of returning error codes" , let me know what is your thought on this list of Java Exception interview questions and answers.



Tuesday 8 September 2015

Coding interview Questions

1)      Given an integer array like - 5, 4, 3, 6, 7, 6, 5, 5

A).Find out which element is repeating max number of times and how many times it is being repeated

B).Optimize the code using exception handling for boundary conditions

Solution:

package swain.coding;

import java.util.Arrays;

public class RepeatingNumber {

       public static void main(String[] args) {
              int[] numbers = { 1, 5, 23, 23, 13, 5, 3, 7, 7, 9, 10, 12, 10, 4 };
              findRepeatingNumber(numbers);
       }

       public static void findRepeatingNumber(int[] numbers) {
              try {
                     Arrays.sort(numbers);
                     int count = 1;
                     for (int i = 1; i < numbers.length; i++) {
                           if (numbers[i] == numbers[i - 1]) {
                                  ++count;
                           } else {
                                  if (count > 1) {
                                         System.out.println("Duplicate : " + numbers[i - 1]
                                                       + " Repeating : " + count);
                                  }
                                  count = 1;
                           }
                           if ((numbers.length - 1) == i) {
                                  if (count > 1) {
                                         System.out.println("Duplicate : " + numbers[i - 1]
                                                       + " Repeating : " + count);
                                  }
                           }
                     }
              } catch (Throwable e) {
                     throw new RuntimeException();
              }
       }

}

Output:

Duplicate : 5 Repeating : 2
Duplicate : 7 Repeating : 2
Duplicate : 10 Repeating : 2

Duplicate : 23 Repeating : 2




2) Remove duplicates charecter in string ?


packageswain.javainterviewhub.blogspot.in;

public class JavaInterviewHub extends Test {

       public static void main(String[] args) {
              String str = "sitansu sekhar swain";
              System.out.println(test(str));
       }

       public static String test(String str) {
              boolean seen[] = new boolean[333];
              StringBuilder sb = new StringBuilder(seen.length);
              for (int i = 0; i < str.length(); i++) {
                     char ch = str.charAt(i);
                     if (!seen[ch]) {
                           seen[ch] = true;
                           sb.append(ch);
                     }
              }
              return sb.toString();
       }

}

Output:

sitanu ekhrw

3) WAP to find how many number of times each number appeared in the given array [3,1,6,8,12,.....] and find what is the most appeared number and should use single loop.

4) Write a algorithm to find least combination mean minimum number of combinations use for a given number suppose take 40(minimum combination is 20+20) from the given array [5,10,20,50];

5) Given a sorted array which was rotated n number of times, WAP to find the index of the smallest element and also the number of rotations using the smallest element index .Input can any  one of the following array.

1,2,3,4,5,
2,3,4,5,1,
3,4,5,1,2,
4,5,1,2,3,
5,1,2,3,4


6. Find peak value of  given series 1 3 4 5 15 8 9 1.

a) And if there is more than one peak value in series it should return the min peak value.
b) If there in no peak value it should return -1.


7. Please advice, Minimum loop required to print below Pattern (can be n*n).
4 4 4 4 4 4 4 4 3 3 3 3 3 4 4 3 2 2 2 3 4 4 3 2 1 2 3 4 4 3 2 2 2 3 4 4 3 3 3 3 3 4 4 4 4 4 4 4 4

Please check solution I used i.e. 3...


8. Second  highest and second minimum number in an  integer array.




String and Arrays Coding interview Questions

String
1) How to Print duplicate characters from String?
To start with, we have a simple String related coding question frequently asked in 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.

Solution:
packageswain.codding.String;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class FindDuplicateCharacters {
       public static void main(String[] args) {
              Scanner scanner = new Scanner(System.in);
              System.out.println("Enter any value: ");
              printDuplicateCharacters(scanner.nextLine());
              printDuplicateCharacters(scanner.next());
       }

       public static voidprintDuplicateCharacters(String word) {
              char[] charecters = word.toCharArray();

              Map<Character, Integer> map = new HashMap<Character, Integer>();
              for (Character ch : charecters) {
                     if (map.containsKey(ch)) {
                           map.put(ch, map.get(ch) + 1);
                     } else {
                           map.put(ch, 1);
                     }
              }
              System.out.printf("list of duplicate charecter of string '%s'%n", word);
              for(Map.Entry<Character, Integer> entry : map.entrySet()) {
                     if (entry.getValue() > 1) {
                           System.out.printf("%s : %d %n", entry.getKey(), entry.getValue());
                     }
              }

       }
}

Output:

Enter any value: 
sitansu
list of duplicate charecter of string 'sitansu'
s : 2 

himanshu
list of duplicate charecter of string 'himanshu'
h : 2 

2) How to check if two Strings are anagrams of each other?
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.


Solution:
packageswain.codding.String;

import java.util.Arrays;

public class StringAnagramTest {

       public static void main(String[] args) {
              isAnagram("word", "wrdo");
              isAnagram("swain", "sitansu");

       }

       public static void isAnagram(String word, String anagram) {
              char[] wordArray = word.toCharArray();
              char[] anagramArray = anagram.toCharArray();
              Arrays.sort(wordArray);
              Arrays.sort(anagramArray);
              if (Arrays.equals(wordArray, anagramArray)) {
                     System.out.println("Two string are anagram");
              } else {
                     System.out.println("Two string are not anagram");
              }
       }

}
Output:

Two string are anagram
Two string are not anagram

3) How to program to print first non repeated character from String?
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.


Solution:
packageswain.codding.String;

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

public class FirstNonRepeatedChar {

       public static void main(String[] args) {
              Scanner scanner = new Scanner(System.in);
              System.out.println("Enter any String value ");

              System.out.println("First Non Repeat character is " + getFirstNonRepeatedChar(scanner.nextLine()));
              System.out.println("First Non Repeat character is " + getFirstNonRepeatedChar(scanner.next()));

       }

       public static chargetFirstNonRepeatedChar(String word) {
              char[] character = word.toCharArray();
              Map<Character, Integer> map = new HashMap<Character, Integer>();
              for (Character ch : character) {
                     if (map.containsKey(ch)) {
                           map.put(ch, map.get(ch) + 1);
                     } else {
                           map.put(ch, 1);
                     }

              }
              for(Map.Entry<Character, Integer> entry : map.entrySet()) {
                     if (entry.getValue() == 1) {
                           return entry.getKey();
                     }
              }
              throw new RuntimeException("didn't find any non repeated Character");
       }
}
Output:

Enter any String value
sitansu
First Non Repeat character is a
swain

First Non Repeat character is a

4) How to reverse String in Java using Iteration and Recursion?
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.

Solutions:


packageswain.javainterviewhub.blogspot.in;

public class StringReverseExample {

       public static void main(String[] args) {
              String str = "This is sitansu";
              System.out.println(newStringBuffer(str).reverse().toString());

              // using iterative
              System.out.println(reverse(str));

              // using recursion
              System.out.println(reverseRecursively(str));

       }

       public static String reverse(String str) {

              StringBuffer sb = new StringBuffer();
              char[] charArray = str.toCharArray();
              for (int i = charArray.length - 1; i >= 0; i--) {
                     sb.append(charArray[i]);
              }

              return sb.toString();

       }

       public static String reverseRecursively(String str) {
              if (str.length() < 2) {
                     return str;
              }
              return reverseRecursively(str.substring(1)) + str.charAt(0);
       }

}

Output:
usnatis si sihT
usnatis si sihT
usnatis si sihT

5) How to check if a String contains only digits?
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.


Solutions:

packageswain.javainterviewhub.blogspot.in;

importjava.util.regex.Pattern;

public classCheckStringContainsOnlyDigit {

       public static void main(String[] args) {
              // Regular expression in Java to check if String is number or not
              Pattern pattern = Pattern.compile(".*[^0-9].*");
              // Pattern pattern = Pattern.compile(".*\\D.*");
              String[] inputs = { "123", "-123", "123.12", "abcd123" };

              for (String input : inputs) {
                     System.out.println("does " + input + " is number : " + !pattern.matcher(input).matches());
              }

              // Regular expression in java to check if String is 6 digit number or not
              String[] numbers = { "123", "1234", "123.12", "abcd123", "123456" };
              Pattern digitPattern = Pattern.compile("\\d{6}");
              // Pattern digitPattern = Pattern.compile("\\d\\d\\d\\d\\d\\d");

              for (String number : numbers) {
                     System.out.println("does " + number + " is 6 digit number : " + digitPattern.matcher(number).matches());
              }

       }

}

Output:
does 123 is number : true
does -123 is number : false
does 123.12 is number : false
does abcd123 is number : false
does 123 is 6 digit number : false
does 1234 is 6 digit number : false
does 123.12 is 6 digit number : false
does abcd123 is 6 digit number : false
does 123456 is 6 digit number : true


6) How to find duplicate characters in a String?
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


Solution:


package swain.coding;

import java.util.Arrays;

public class RepeatingNumber {

       public static void main(String[] args) {
              int[] numbers = { 1, 5, 23, 23, 13, 5, 3, 7, 7, 9, 10, 12, 10, 4 };
              findRepeatingNumber(numbers);
       }

       public static void findRepeatingNumber(int[] numbers) {
              try {
                     Arrays.sort(numbers);
                     int count = 1;
                     for (int i = 1; i < numbers.length; i++) {
                           if (numbers[i] == numbers[i - 1]) {
                                  ++count;
                           } else {
                                  if (count > 1) {
                                         System.out.println("Duplicate : " + numbers[i - 1]
                                                       + " Repeating : " + count);
                                  }
                                  count = 1;
                           }
                           if ((numbers.length - 1) == i) {
                                  if (count > 1) {
                                         System.out.println("Duplicate : " + numbers[i - 1]
                                                       + " Repeating : " + count);
                                  }
                           }
                     }
              } catch (Throwable e) {
                     throw new RuntimeException();
              }
       }

}

Output:

Duplicate : 5 Repeating : 2
Duplicate : 7 Repeating : 2
Duplicate : 10 Repeating : 2
Duplicate : 23 Repeating : 2

7) How to count number of vowels and consonants in a String?
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.

Solution:


packageswain.codding.String;

import java.util.Scanner;

public class CountVowelNConsonant {

       public static void main(String[] args) {
              Scanner scanner = new Scanner(System.in);
              System.out.println("Enter any string.");
              System.out.println();
              countVowel(scanner.nextLine());
       }

       public static void countVowel(String str) {

              char[] chArray = str.toCharArray();
              int totalCount = 0;
              int countVowel = 0;
              int countConsonant;
              for (char ch : chArray) {
                     if (ch != ' ') {
                           totalCount++;
                     }

                     switch (ch) {
                     case 'a':
                           ;
                     case 'e':
                           ;
                     case 'i':
                           ;
                     case 'o':
                           ;
                     case 'u':
                           ;
                           countVowel++;
                           break;
                     }
              }
              System.out.println("Total count " + totalCount + " vowel count " + countVowel + " consonant count " + (totalCount - countVowel));
       }
}



Output:

Enter any string.

this is sitansu
Total count 13 vowel count 5 consonant count 8


8) How to count occurrence of a given character in String?
If interviewer ask you to count occurrence of more than one character than you can either use an array, hash table or any additional 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.

Solution:

packageswain.coding;

public classCountCharacters {

          public static voidmain(String[] args) {
                   String str = "Today is monday";
                   intcountOccurance = 0;

                   // counting occurrence of character with loop
                   for (int i = 0; i < str.length(); i++) {
                             if(str.charAt(i) == 'a') {
                                      countOccurance++;
                             }
                   }

                   System.out
                                      .println("count of character 'a' on String: 'Today is Monday' using for loop  "
                                                          + countOccurance);

                   // a more elegant way of counting occurrence of character in String
                   // using foreach loop
                   countOccurance = 0;
                   for (char ch : str.toCharArray()) {
                             if (ch == 'a') {
                                      countOccurance++;
                             }
                   }
                   System.out
                                      .println("count of character 'a' on String: 'Today is Monday' using for loop  "
                                                          + countOccurance);

          }

}

Output:
count of character 'a' on String: 'Today is Monday' using for loop  2
count of character 'a' on String: 'Today is Monday' using for loop  2


9) How to convert numeric String to int?
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?
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?
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?
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?
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 "radar", the output should be true, if input is "madam" output will be true, and if input is "Java" output should be false.
14) How to remove duplicate characters from String?
This is one of the interesting String question, which also has lots of variants. You need to remove duplicate characters from a given string keeping only the first occurrences. For example, if the input is ‘bananas’ the output will be ‘bans’. Pay attention to what output could be, because if you look closely original order of characters are retained in output. This is where many developer make mistake of shorting character array of String and removing duplicates, similar to how you remove duplicates from array. That destroys original order of characters and will not be correct solution in this case.


15) How to check if a String is valid shuffle of two String?
One more difficult String algorithm based coding question for senior developers. You are given 3 strings: first,  second, and  third.  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. For example, given first = "abc" and second = "def",  third = "dabecf"  is a valid shuffle since it preserves the character ordering of the two strings. So, given these 3 strings write a function that detects whether third String is a valid shuffle of first and second String.

16) Write a program to check if a String contains another String e.g. indexOf()?
You need to write a function to search for the existence of a string (target) in another string (source). The function takes two strings as the input and returns the index where the second string is found. If the target string cannot be found, then return -1. If you are a Java developer, then you can related its behavior to indexOf() method from java.lang.String class. This question is also asked as Code and algorithm to check if a given short string is a substring of a main string. Can you get a linear solution (O(n)) if possible?

17) How  to return highest occurred character in a String?
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. For example if input is "aaaaaaaaaaaaaaaaabbbbcddddeeeeee" it should return "a".

18) Write a program to remove a given characters from String?
One of my favorite coding question, when I interview Java developers. You need to write a Java method which will accept a String and a character to be removed and return a String, which doesn't has that character e.g remove(String word, char ch).  You need to provide both iterative and recursive solution of this method and also has to write JUnit tests to cover cases like null and empty String, input which only contains letter to be removed, String which doesn't contain given character etc.

19) Write a program to find longest palindrome in a string?
This is one of the tough coding question based upon String. It's hard to think about an algorithm to solve this problem until you have practiced good. What makes it more difficult is the constraint that your solution has O(n) time complexity and O(1) space complexity.

20) How to sort String on their length in Java?
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. Don't forget to write unit tests for your solution.

Arrays

1. How to find missing number in integer array of 1 to 100? 
This is one of the most simple array problem you will see, mostly asked in telephonic round of Interview. You have given an integer array which contains numbers from 1 to 100 but one number is missing, you need to write a Java program to find that missing number in array. You cannot use any open source library or Java API method which solves this problem. One trick to solve this problem is calculate sum of all numbers in array and compare with expected sum, the difference would be the missing number.

2. How to find duplicate number on Integer array in Java? 
An array contains n numbers ranging from 0 to n-2. There is exactly one number is repeated in the array. You need to write a program to find that duplicate number. For example, if an array with length 6 contains numbers {0, 3, 1, 2, 3}, then duplicated number is 3. Actually this problem is very similar to previous one and you can apply the same trick of comparing actual sum of array to expected sum of series to find out that duplicate. This is generally asked as follow-up question of previous problem.


3. How to check if array contains a number in Java? 
Another interesting array problem, because array doesn't provide any builtin method to check if any number exists or not. This problem is essentially how to search an element in array. There are two options sequential search or binary search. You should ask interviewer about whether array is sorted or not, if array is sorted then you can use binary search to check if given number is present in array or not. Complexity of binary search is O(logN). BTW, if interviewer say that array is not sorted then you can still sort and perform binary search otherwise you can use sequential search. Time complexity of sequential search in array is O(n).

4. How to find largest and smallest number in unsorted array? 
This is a rather simple array 
interview question. You have given an unsorted integer array and you need to find the largest and smallest element in the array. Of course you can sort the array and then pick the top and bottom element but that would cost you O(NLogN) because of sorting, getting element in array with index is O(1) operation.

5. How to find all pairs on integer array whose sum is equal to given number? 
This is an intermediate level of array coding question, its neither too easy nor too difficult. You have given an integer array and a number, you need to write a program to find all elements in array whose sum is equal to the given number. Remember, array may contain both positive and negative numbers, so your solution should consider that. Don't forget to write unit test though, even if interviewer is not asked for it, that would separate you from lot of developers. Unit testing is always expected from a professional developer.

6.  How to find repeated numbers in an array if it contains multiple duplicate? 
This is actually the follow-up question of problem 2, how to find duplicate number on integer array. In that case, array contains only one duplicate but what if it contains multiple duplicates? Suppose, an array contains n numbers ranging from 0 to n-1 and there are 5 duplicates on it, how do you find it? You can use the approach, we have learned in similar String based problem of finding repeated characters in given String.

7. Write a program to remove duplicates from array in Java? 
This is another follow-up question from problem 2 and 6. You have given an array which contains duplicates, could be one or more. You need to write a program to remove all duplicates from array in Java. For example if given array is {1, 2, 1, 2, 3, 4, 5} then your program should return an array which contains just {1, 2, 3, 4, 5}. This array question is also comes at intermediate category because there is no way to delete an element from array. If substituting with another value is not an option then you need to create another array to mimic deletion.

8. How to sort an array in place using QuickSort algorithm? 
You will often see sorting problems on array related questions, because sorting mostly happen on array data structure. You need to write a program to implement in place quick sort algorithm in Java. You can implement either recursive or iterative quick sort, its your choice but you cannot use additional buffer, array or list, you must sort array in place.

9.  Write a program to find intersection of two sorted array in Java?
Another interesting array interview question, where you need to treat array as Set. Your task is to write a function in your favorite language e.g. Java, Python, C or C++ to return intersection of two sorted array. For example, if the two sorted arrays as input are {21, 34, 41, 22, 35} and {61, 34, 45, 21, 11}, it should return an intersection array with numbers {34, 21}, For the sake of this problem you can assume that numbers in each integer array are unique.

10. There is an array with every element repeated twice except one. Find that element? 
This is an interesting array coding problem, just opposite of question related to finding duplicates in array. Here you need to find the unique number which is not repeated twice. For example if given array is {1, 1, 2, 2, 3, 4, 4, 5, 5} then your program should return 3. Also, don't forget to write couple of unit test for your solution.
Description: Java Array Interview Question Answer

11. How to find kth smallest element in unsorted array? 
You are given an unsorted array of numbers and k, you need to find the kth smallest number in the array. For example if given array is {1, 2, 3, 9, 4} and k=2 then you need to find the 2nd smallest number in the array, which is 2. One way to solve this problem is to sort the array in ascending order then pick the k-1th element, that would be your kth smallest number in array because array index starts at zero, but can you do better? Once you are able to solve this array coding question, you can solve many similar questions easily e.g. our next question.

12. How to find kth largest element in unsorted array? 
This problem is exactly same as previous question with only difference being finding kth largest element instead of kth smallest number. For example if given array is {10, 20, 30, 50, 40} and k = 3 then your program should return 30 because 30 is the 3rd largest number in array. You can also solve this problem by sorting the array in decreasing order and picking k-1th element. I often seen this array question on Java interviews with 2 to 3 years experienced guys.

13 How to find common elements in three sorted array? 
Now we are coming on territory of tough array questions. Given three arrays sorted in non-decreasing order, print all common elements in these arrays.

Examples:
input1 = {1, 5, 10, 20, 40, 80}
input2 = {6, 7, 20, 80, 100}
input3 = {3, 4, 15, 20, 30, 70, 80, 120}
Output: 20, 80


14. How find the first repeating element in an array of integers? 
Given an array of integers, find the first repeating element in it. We need to find the element that occurs more than once and whose index of first occurrence is smallest.

Examples:

Input:  input [] = {10, 5, 3, 4, 3, 5, 6}
Output: 5 [5 is the first element that repeats]


15. How to find first non-repeating element in array of integers? 
This array interview question is exactly opposite of previous problem, In that you need to find first repeating element while in this you need to find first non-repeating element. I am sure you can use similar approach to solve this problem, just need to consider non repeating element though.

16. How to find top two numbers from an integer array?
This is another one of the easy array questions you will find on telephonic round of Interviews, but its also little bit tricky. You are asked to find top two numbers not just the top or highest numbers? Can you think of how you would do it without sorting? before looking at solution.

17. How to find the smallest positive integer value that cannot be represented as sum of any subset of a given array?
This is another tough array question you will see on Amazon, Microsoft or Google. You have given a sorted array (sorted in non-decreasing order) of positive numbers, find the smallest positive integer value that cannot be represented as sum of elements of any subset of given set. What makes it more challenging is expected time complexity of O(n).

Examples:

Input: {1, 3, 6, 10, 11, 15};
Output: 2

18. How to rearrange array in alternating positive and negative number? 
Given an array of positive and negative numbers, arrange them in an alternate fashion such that every positive number is followed by negative and vice-versa maintaining the order of appearance.
Number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear in the end of the array. This is also a difficult array problem to solve and you need lot of practice to solve this kind of problems in real interviews, especially when you see it first time. If you have time constraint then always attempt these kind of questions once you are done with easier ones. 

Example:

Input: {1, 2, 3, -4, -1, 4}
Output: {-4, 1, -1, 2, 3, 4}

Input: {-5, -2, 5, 2, 4, 7, 1, 8, 0, -8}
output: {-5, 5, -2, 2, -8, 4, 7, 1, 8, 0} 


19. How to find if there is a sub array with sum equal to zero? 
There is whole set of array related questions which are based upon sub-array or only selective elements of array e.g. from some range, this is one of such problem. Here you are given an array of positive and negative numbers, find if there is a sub-array with 0 sum.

Examples:

Input: {4, 2, -3, 1, 6}
Output: true 
There is a sub-array with zero sum from index 1 to 3.

20. How to remove duplicates from array in place? 
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2]. 

When you see a questions which asked you do to sorting or task in place, it means you cannot use additional array or buffer, but using couple of variables is fine.

21. How to remove a given element from array in Java?
This is another array coding questions similar to previous one. Here you don't have to find and remove duplicates but a given number. In this problem you are given an array and a value, remove all instances of that value in place and return the new length. The order of elements can be changed. It doesn't matter what you leave beyond the new length.


22. How to merge sorted array? 
Given two sorted integer arrays A and B, merge B into A as one sorted array. You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively. This is another intermediate array coding question, its not as simple as previous one but neither very difficult.


23. How to find sub array with maximum sum in an array of positive and negative number? 
Another array coding question based upon sub-array. Here you have to find the contiguous sub-array within an array (containing at least one number) which has the largest sum.

For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6. 

24. How to find sub array with largest product in array of both positive and negative number? 
In this problem, your task is to write a program in Java or C++ to find the contiguous sub-array within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6. 


25. Write a program to find length of longest consecutive sequence in array of integers? 
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Challenging part of this question is that your algorithm should run in O(n) complexity. 


26. How to find minimum value in a rotated sorted array? 
This is another advanced level array coding question and you should only attempt this one, once you have solved the easier ones. Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

Find the minimum element.

You may assume no duplicate exists in the array. One follow-up question of this question is What if duplicates are allowed? Would this affect the run-time complexity? How and why?


27. Given an array of of size n and a number k, find all elements that appear more than n/k times? 
Another tough array based coding questions from Interviews. You are given an array of size n, find all elements in array that appear more than n/k times. For example, if the input arrays is {3, 1, 2, 2, 1, 2, 3, 3} and k is 4, then the output should be [2, 3]. Note that size of array is 8 (or n = 8), so we need to find all elements that appear more than 2 (or 8/4) times. There are two elements that appear more than two times, 2 and 3.

1. Returns the largest sum of contiguous integers in the array
Example: if the input is (-10, 2, 3, -2, 0, 5, -15), the largest sum is 8

2. Return the sum two largest integers in an array

3. Given an array of integers write a program that will determine if any two numbers add up to a specified number N. Do this without using hash tables


28. How to reverse array in place in Java? 
Now let's see one of the most frequently asked array interview question. You need to write a program which accepts an integer array and your program needs to reverse that array in place, which means you cannot use additional buffer or array, but one or two variables will be fine. Of course you cannot use any open source library or Java API method to directly solve this problem, you need to create your own logic. Here is one such logic to solve this problem :
Description: Array Coding Interview Questions and Answers


29. Difference between array and linked list data structure? 
This is a theoretical questions from phone interviews. There are several differences between array and linked list e.g. array stores element in contiguous memory location while linked list stores at random places, this means linked list better utilizes the places. Consequently, its possible to have large linked list in limited memory environment compare to array of same size. Advantage of using array is random access it provides if you know the index, while in linked list you need to search an element by traversing which is O(n) operation.


30. How to check if array contains a duplicate number?
This may look a repeated question because we have already done similar question, but in this question, most from Java interviews, you need to write a contains() like method from Collections, which returns true or false if you pass an element and it is repeated or not.