Google

Sep 23, 2011

Java coding interview questions and answers

Core Java Coding Questions and Answers for beginner to intermediate level

Q1 Q2 Q3 Q4 Q5 - Q8 Q9 Q10 Q11 Q12 - Q14 Q15

These Java coding questions and answers are extracted from the book " Core Java Career Essentials. Good interviewers are more interested in your ability to code rather than knowing the flavor of the month framework.


Q. Can you write an algorithm to swap two variables?
A.


package algorithms;

public class Swap {
    
    public static void main(String[ ] args) {
        int x = 5;
        int y = 6;
        
        //store 'x' in a temp variable
        int temp = x;
        x = y;
        y = temp;
        
        System.out.println("x=" + x + ",y=" + y);
   }
}


Q. Can you write  code to bubble sort { 30, 12, 18, 0, -5, 72, 424 }?
A.

package algorithms;
import java.util.Arrays;

public class BubbleSort {

    public static void main(String[ ] args) {
        Integer[ ] values = { 30, 12, 18, 0, -5, 72, 424 };
        int size = values.length;
        System.out.println("Before:" + Arrays.deepToString(values));

        for (int pass = 0; pass < size - 1; pass++) {
            for (int i = 0; i < size - pass - 1; i++) {
                // swap if i > i+1
                if (values[i] > values[i + 1])
                    swap(values, i, i + 1);
            }
        }

        System.out.println("After:" + Arrays.deepToString(values));
    }

    private static void swap(Integer[ ] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
} 


Q. Is there a more efficient sorting algorithm?
A. Although bubble-sort is one of the simplest sorting algorithms, it's also one of the slowest. It has the O(n^2) time complexity. Faster algorithms include quick-sort and heap-sort. The Arrays.sort( ) method uses the quick-sort algorithm, which on average has O(n * log n) but can go up to O(n^2) in a worst case scenario, and this happens especially with already sorted sequences.

Q. Write a program that will return whichever value is nearest to the value of 100 from two given int numbers?
A. You can firstly write the pseudo code as follows:

  • Compute the difference to 100.
  • Find out the absolute difference as negative numbers are valid.
  • Compare the differences to find out the nearest number to 100.
  • Write test cases for +ve, -ve, equal to, > than and < than values.
package chapter2.com;



public class CloseTo100 {

    

    public static int calculate(int input1, int input2) {

         //compute the difference. Negative values are allowed as well 

        int iput1Diff = Math.abs(100 - input1);

        int iput2Diff = Math.abs(100 - input2);

        

        //compare the difference

        if (iput1Diff < iput2Diff) return input1;
        else if (iput2Diff < iput1Diff) return input2;
        else return input1;          //if tie, just return one
    }
    
    public static void main(String[ ] args) {
        //+ve numbers
        System.out.println("+ve numbers=" + calculate(50,90));
        
        //-ve numbers
        System.out.println("-ve numbers=" + calculate(-50,-90));
        
        //equal numbers
        System.out.println("equal numbers=" + calculate(50,50));
        
        //greater than 100
        System.out.println(">100 numbers=" + calculate(85,105));

        System.out.println("<100 numbers=" + calculate(95,110));
    } 
}



Output:

+ve numbers=90
-ve numbers=-50
equal numbers=50
>100 numbers=105
<100 numbers=95


Q. Can you write a method that reverses a given String?
A.
public class ReverseString {

    

    public static void main(String[ ] args) {

        System.out.println(reverse("big brown fox"));

        System.out.println(reverse(""));       

    }



    public static String reverse(String input) {

        if(input == null || input.length( ) == 0){

            return input;

        }

       

        return new StringBuilder(input).reverse( ).toString( ); 

    }

}


It is always a best practice to reuse the API methods as shown above with the StringBuilder(input).reverse( ) method as it is fast, efficient (uses bitwise operations) and knows how to handle Unicode surrogate pairs, which most other solutions ignore. The above code handles null and empty strings, and a StringBuilder is used as opposed to a thread-safe StringBuffer, as the StringBuilder is locally defined, and local variables are implicitly thread-safe.

Some interviewers might probe you to write other lesser elegant code using either recursion or iterative swapping. Some developers find it very difficult to handle recursion, especially to work out the termination condition. All recursive methods need to have a condition to terminate the recursion.


public class ReverseString2 {
    
    public String reverse(String str) {
        // exit or termination condition
        if ((null == str) || (str.length( )  <= 1)) {
            return str;
        }
        
        // put the first character (i.e. charAt(0)) to the end. String indices are 0 based. 
        // and recurse with 2nd character (i.e. substring(1)) onwards  
        return reverse(str.substring(1)) + str.charAt(0);
    }
}

There are other solutions like
public class ReverseString3 {
    
    public String reverse(String str) {
        // validate
        if ((null == str) || (str.length( )  <= 1)) {
            return str;
        }
        
        char[ ] chars = str.toCharArray( );
        int rhsIdx = chars.length - 1;
        
        //iteratively swap until exit condition lhsIdx < rhsIdx is reached
        for (int lhsIdx = 0; lhsIdx < rhsIdx; lhsIdx++) {
            char temp = chars[lhsIdx];
            chars[lhsIdx] = chars[rhsIdx];
            chars[rhsIdx--] = temp;
        }
        
        return new String(chars);
    }
} 



Or
 
public class ReverseString4 {
     
    public String reverse(String str) {
        // validate
        if ((null == str) || (str.length( )  <= 1)) {
            return str;
        }
         
        
        char[ ] chars = str.toCharArray( );
        int length = chars.length;
        int last = length - 1;
         
        //iteratively swap until reached the middle
        for (int i = 0; i < length/2; i++) {
            char temp = chars[i];
            chars[i] = chars[last - i];
            chars[last - i] = temp;
        }
         
        return new String(chars);
    }
    
    
    public static void main(String[] args) {
      String result = new ReverseString4().reverse("Madam, I'm Adam");
      System.out.println(result);
   }
} 

Relevant must get it right coding questions and answers


Labels: , ,

14 Comments:

Anonymous Anonymous said...

Below will also work for reversing string

public String reverse(String str)
{
if ((null == str) || (str.length( ) <= 1))
return str;

char reverse[]= new char[10];

for(int i=0;i<str.length();i++)
reverse[i] = str.toCharArray()[str.length()-1-i];

return new String(reverse);
}

9:04 PM, June 07, 2012  
Anonymous Anonymous said...

You can also see this article, it has code to reverse String in Java using recursion

8:07 PM, September 03, 2012  
Blogger PapoO Jutt said...

hnmm...well written :)

3:25 PM, September 06, 2012  
Blogger HowToDoInJava.com said...

Its mostly asked in terms of call by value or call by reference. right ??

5:18 PM, March 05, 2013  
Blogger suresh said...

Hi ,I have scenario can any one pls help me out..

static String string[][]={{"A","B","C","U","E"},
{"S","T","R","W","Q"},
{"H","I","J","K","L"},
{"M","N","O","P","Q"},
{"F","G","X","Y","Z"}};

the above 5*5 matrix contains alphabets .I want you find a pattern "super" from the above matrix..please share logic..

1:32 AM, April 06, 2013  
Anonymous java2novice said...

very nice. for more java examples visit http://java2novice.com site

10:40 PM, March 11, 2014  
Blogger Unknown said...

This comment has been removed by the author.

6:34 PM, May 26, 2014  
Blogger Unknown said...

Question NO 4 ( near to 100) , can easily get by

public static int calculate(int input1, int input2) {
return input1 > input2 ? input1 : input2;
}

6:37 PM, May 26, 2014  
Blogger Unknown said...

if the numbers are 95 and 110, which is nearer?

11:15 PM, May 26, 2014  
Blogger Unknown said...

Ah ... yes , right sir . I need additional checking is range between 0 to 100 . :) Thanks

12:42 PM, May 27, 2014  
Blogger Unknown said...

Good to see when you start asking the right questions.

1:01 PM, May 27, 2014  
Blogger Unknown said...

Also, consider -ve numbers as well :)

1:03 PM, May 27, 2014  
Anonymous AndrĂ© Pinto said...

Arrays.sort uses TimSort since Java 7:

http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6804124

7:21 AM, June 23, 2014  
Anonymous AndrĂ© Pinto said...

For primitives it uses a dual pivot-QuickSort:
http://stackoverflow.com/a/4018380/43046

7:24 AM, June 23, 2014  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home