Last-Minute Java Programs Preparation for Interview

1. Write a Java program to reverse a string.

The provided Java program demonstrates various techniques to reverse a given string. It offers three methods for string reversal:

package com.javainfotech;

public class StringReverse {
	
	public static void main(String[] args) {
		//Using StringBuffer
		String res = reverseUsingStringBuffer("JavaInfotech");
		System.out.println("Reverse String - "+res);
		String result = reverseUsingIterate("JavaInfotech");
		System.out.println("Reverse String - "+result);
		String results = reverseUsingRecursive("JavaInfotech");
		System.out.println("Reverse String - "+results);
	}
	
	//Using StringBuffer
	public static String reverseUsingStringBuffer(String str){
		StringBuffer sb = new StringBuffer(str);
		return sb.reverse().toString();
	}
	//Using Iterating 
	public static String reverseUsingIterate(String str){
		char[]  ch = str.toCharArray();
		String s ="";
		for(int i=ch.length-1;i>=0;i--){
			s = s+ch[i];
		}
		return s;
	}
	//Using Recursive
	public static String reverseUsingRecursive(String str){
		if((str==null) || (str.length()<=1)){
			return str;
		}
		return reverseUsingRecursive(str.substring(1))+str.charAt(0);
	}
}

2. How do I reverse the number?

package com.javainfotech.program;

public class ReverseNumber {

	public static void main(String[] args) {
		reverseNumber(54321);
	}

	public static void reverseNumber(int n) {
		int reversed = 0;
	    while (n > 0) {
	        int lastDigit = n % 10;
	        if (lastDigit == 0 && reversed == 0) {
	            n /= 10;
	            continue;
	        }
	        reversed = reversed * 10 + lastDigit;
	        n /= 10;
	    }
	    System.out.println("Reverse Number :"+reversed);
	}
}

3. Write a program in Java that counts the occurrences of each character in the string and returns a Map<String, Long>, where the key is a String representing a character, and the value is a Long representing the number of times that character appears in the string.

package com.javainfotech.program;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

public class FindDuplicate {

	public static void main(String args[]) {
		String str = "javainfotech";
		
		//Solution 1: Basic
		Map<Character,Integer> map = new HashMap<Character,Integer>();
		char[] ch = str.toCharArray();
		for(int i=0;i<ch.length;i++) {
			if(map.containsKey(ch[i])) {				
				map.put(ch[i], map.get(ch[i])+1);
			}else {
				map.put(ch[i], 1);
			}
		}
		
		for(Entry<Character, Integer>  e : map.entrySet()) {
			System.out.println(e.getKey()+" -> "+e.getValue());
		}
		
		//Solution 2: Using Java 1.8 with Stream API
		Map<String,Long> mapResult = str.chars()
				.mapToObj(c-> String.valueOf((char) c))
				.collect(Collectors.groupingBy(c->c, Collectors.counting()));
				
		mapResult.forEach((st,n)-> System.out.println(st+" -> "+n));
		
	}
}

4. How do I create an immutable class in Java?

package com.javainfotech.String;
public final class ImmutableExample {
	
	private final int id;
	private final String name;
	
	public ImmutableExample(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public String getName() {
		return name;
	}
}

5. Can you write the output of the below progaram?

package com.javainfotech.String;

public class StringConcatation {
	
	public static void main(String[] args){
		System.out.println("Test"+12+10);
		System.out.println(12+10+"Test");
		System.out.println("Test"+12+10+"Example");
		System.out.println("Test"+12+"Example"+10);
		System.out.println(10+12+"Test"+12+"Example"+10);
	}
}

6. Van Eck’s sequence is a number sequence where each term is defined based on the previous terms. The sequence starts as follows:

  • a(1) = 0
  • a(2) = 0
  • For n > 2, a(n) is the number of terms since the last occurrence of the value a(n-1).

For example:

  • a(1) = 0
  • a(2) = 0
  • a(3) = 1 (because 0 last occurred at position 1)
  • a(4) = 2 (because 0 last occurred at position 2)
  • a(5) = 1 (because 1 last occurred at position 3)
  • a(6) = 1 (because 2 last occurred at position 4)

Write a Java program that calculates and prints the Nth term of Van Eck’s sequence. The program should take an integer N as input and return the Nth term of the sequence.

Input:

  • An integer N (1 <= N <= 10^5)

Output:

  • The Nth term of Van Eck’s sequence.

Example:

For N = 5, the output should be 1.

For N = 6, the output should be 1.

package com.javainfotech.sequence;
public class VanECKSequence {

	static int MAX = 25;	
	static int[] seq = new int[MAX];	
	public static void vanEckSequence(){		
		for(int i=0;i<MAX-1;i++){
			for(int j=i-1;j>=0;j--){
				if(seq[j]==seq[i]){
					seq[i+1]=i-j;
					break;
				}
			}
		}
	}
	public static void main(String[] args) {
		vanEckSequence();
		for(int i=0;i<seq.length-1;i++){
			System.out.print(seq[i]+", ");
		}
	}
}
Output:
0, 0, 1, 0, 2, 0, 2, 2, 1, 6, 0, 5, 0, 2, 6, 5, 4, 0, 5, 3, 0, 3, 2, 9, 

7. Can you write progaram to sort the number given in an array?

package com.javainfotech;

public class SortArray {

	public static void main(String[] args) {
		int[] arr = {1,3,5,8,6,5,24,87,65,43,22,12};
		
		int temp, count = arr.length;
		for(int i=0;i<count;i++){
			for(int j=i+1;j<count;j++){
				if(arr[i]>arr[j]){
					temp = arr[i];
					arr[i] = arr[j];
					arr[j] = temp;
				}
			}
			System.out.print(arr[i]+", ");
		}		
	}
}
Output:
1, 3, 5, 5, 6, 8, 12, 22, 24, 43, 65, 87

8. Given an array of integers num and an integer target, find two numbers in the array that add up to target and return their indices.

  • Input: num = [1, 4, 9, 12], target = 5
  • Output: [0, 1]
  • Explanation: Because num[0] + num[1] == 5, we return [0, 1].
package com.javainfotech.arrays;
import java.util.Arrays;
public class TwoSum {
	public static void main(String[] args) {
		//Create array
		int[] num = {1, 4, 9, 12};
		int target = 5;
		int[] result = getTwoSum(num,target);
		System.out.println("Result indices : "+Arrays.toString(result));
	}	
	//Method create to get the indices
	public static int[] getTwoSum(int[] num, int target) {
        int[] ans = new int[2];
        for(int i=0;i<num.length;i++) {
        	for(int j=i+1;j<num.length;j++) {        		
        		if(num[i]+num[j]==target) {
        			ans[0]=i;
        			ans[1]=j;
        			return ans;//Return indices
        		}
        	}        
        }
        return new int[] {-1,-1};
    }
}

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply