Java Programming Coding Interview Questions 1 | Code Factory


Donate : Link

Medium Blog : Link

Applications : Link

1. BigDecimal to work with currencies

– Why You Should Never Use Float and Double for Monetary Calculations

– Make cents with BigDecimal

– Choosing data type for monetary Calculation

package com.example.java;

import java.math.BigDecimal;

/**
 * @author code.factory
 *
 */
public class BigDecimalExample {
	public static void main(String... strings) {
		float f1 = 1.25f;
		float f2 = 1.05f;
		System.out.println("Float f1 - f2 : " + (f1 - f2));

		double d1 = 1.25;
		double d2 = 1.05;
		System.out.println("Double d1 - d2 : " + (d1 - d2));

		BigDecimal b1 = new BigDecimal("1.25");
		BigDecimal b2 = new BigDecimal("1.05");
		System.out.println("BigDecimal(\"\") b1 - b2 : " + (b1.subtract(b2)));

		BigDecimal b3 = new BigDecimal(1.25);
		BigDecimal b4 = new BigDecimal(1.05);
		System.out.println("BigDecimal() b3 - b4 : " + (b3.subtract(b4)));
	}
}

Output :

Float f1 - f2 : 0.20000005
Double d1 - d2 : 0.19999999999999996
BigDecimal("") b1 - b2 : 0.20
BigDecimal() b3 - b4 : 0.1999999999999999555910790149937383830547332763671875

2. How to access protected variables in another class in Inheritance

package com.example.java.programming;

/**
 * @author code.factory
 *
 */
public class Child extends Parent {
	Child() {
		System.out.println(protectedStr); // accessible
	}
	public static void main(String... args) {
		System.out.println(protectedStr); // not accessible
		System.out.println(new Child().protectedStr); // accessible
		System.out.println(new Parent().protectedStr); // accessible
	}
}

class Parent {
	protected String protectedStr;
}

Why does this work? -> Because you’ve inherited the class. That means you’ve got all of its methods and it’s variables. Now, because your method and variable is protected, it also means that it can be accessed from the subclass.

3. equals() and hashCode()

package com.example.java.programming;

import java.util.HashSet;
import java.util.Set;

public class EqualHashcode {

	public static void main(String... args) {
		Employee e1 = new Employee(1, "parth");
		Employee e2 = new Employee(2, "parth");
		
		System.out.println(e1 == e2);
		System.out.println(e1.equals(e2));
		
		Set<Employee> set = new HashSet<Employee>();
		set.add(e1);
		set.add(e2);
		
		System.out.println(set);
	}

}

class Employee {
	
	int id;
	String name;
	
	public Employee(int id, String name) {
		this.id = id;
		this.name = name;
	}

	@Override
	public boolean equals(Object arg0) {
		Employee e = (Employee) arg0;
		return this.name.equals(e.name);
	}

	@Override
	public int hashCode() {
		return this.name.charAt(0);
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + "]";
	}

}

Output :

false
true
[Employee [id=1, name=parth]]

4. Wrapper class MIN-VALUE

package com.example.java.programming;

/**
 * @author code.factory
 *
 */
public class WrapperMinValue {
	public static void main(String... args) {
		System.out.println(Math.min(Integer.MIN_VALUE, 0.0d));
		System.out.println(Math.min(Float.MIN_VALUE, 0.0d));
		System.out.println(Math.min(Double.MIN_VALUE, 0.0d));
		
		System.out.println(Integer.MIN_VALUE);
		System.out.println(Float.MIN_VALUE);
		System.out.println(Double.MIN_VALUE);
	}
}

Output :

-2.147483648E9
0.0
0.0
-2147483648
1.4E-45
4.9E-324

5. Daemon and User Thread

package com.example.java.programming;

public class DaemonTest {

	public static void main(String[] args) {
		new WorkerThread().start();

		try {
			Thread.sleep(7500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		System.out.println("Main Thread ending");
	}

}

class WorkerThread extends Thread {

    public WorkerThread() {
        // When false, (i.e. when it's a user thread),
        // the Worker thread continues to run.
        // When true, (i.e. when it's a daemon thread),
        // the Worker thread terminates when the main 
        // thread terminates.
        setDaemon(true); 
    }

    public void run() {
        int count = 0;

        while (true) {
            System.out.println("Hello from Worker "+count++);

            try {
                sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Output :

Hello from Worker 0
Hello from Worker 1
Main Thread ending

6. instanceof example

package com.example.java.programming;

import java.util.ArrayList;
import java.util.List;

/**
 * @author code.factory
 *
 */
public class Test {
	public static void main(String... strings) {
		ArrayList<Integer> in = new ArrayList<Integer>();
		System.out.println(in instanceof ArrayList); // true
		System.out.println(in instanceof List); // true
	}
}

7. Static Non Static Block

package com.example.java.programming;

/**
 * @author code.factory
 *
 */
public class StaticNonStaticBlock {

	public static void main(String... args) {
		new child1();
		System.out.println();
		new child1();
	}
}

class parent1 {

	static void beforeStaticBlock() {
		System.out.println("beforeStaticBlock");
	}
	
	static {
		beforeStaticBlock();
		System.out.println("A");
	}
	
	{
		System.out.println("B");
	}
	
	public parent1() {
		System.out.println("C");
	}
}

class child1 extends parent1 {

	static {
		System.out.println("D");
	}
	
	{
		System.out.println("E");
	}
	
	public child1() {
		System.out.println("F");
	}
}

Output :

beforeStaticBlock
A
D
B
C
E
F

B
C
E
F

8. String example

package com.example.java.programming;

public class StringTest {
	public static void main(String... args) {
		String str1 = "code";
		String str2 = str1;
		System.out.println(str1 == str2); // true
		str2 = "Code";
		System.out.println(str1 == str2); // false
		System.out.println(str1); // code
		System.out.println(str2); // Code
		
		String str3 = null;
		String str4 = null;
		System.out.println(str3 == str4); // true
	}
}

9. Fibonacci series

package com.example.java.programming;

/**
 * @author code.factory
 *
 */
public class Fibonacci {
	public static void main(String... args) {
		fibonacci(10);
	}
	
	public static void fibonacci(int no) {
		int first = 0, second = 1, curr = 1;
		System.out.print(curr + " ");
		for(int i=0; i<10; i++) {
			curr = first + second;
			System.out.print(curr + " ");
			first = second;
			second = curr;
		}
	}
}

Output :

1 1 2 3 5 8 13 21 34 55 89

10. How many time this recursion function will traverse?

package com.example.java.programming;

/**
 * @author code.factory
 *
 */
public class Test {
	public static void main(String... strings) {
		System.out.println(fibonacci(4, "MAIN"));
	}

	/* Used String (name) for easy understanding */
	/* It will return fibonacci number at given index */
	public static int fibonacci(int n, String name) {
		// System.out.println(n + " " + name);
		if (n == 1 || n == 2) {
			return 1;
		}
		return fibonacci(n - 1, "FIRST") + fibonacci(n - 2, "SECOND");
	}
}

Output:

fibonacci(4, "MAIN") -> 5
fib(4) - main
	fib(3) - first
		fib(2) - first
		fib(1) - second
	fib(2) - second

fibonacci(5, "MAIN") -> 9
fib(5) - main
	fib(4) - first
		fib(3) - first
			fib(2) - first
			fib(1) - second
		fib(2) - second
	fib(3) - second
		fib(2) - first
		fib(1) - second

fibonacci(6, "MAIN") -> 15
fib(6) - main
	fib(5) - first
		fib(4) - first
			fib(3) - first
				fib(2) - first
				fib(1) - second
			fib(2) - second
		fib(3) - second
			fib(2) - first
			fib(1) - second
	fib(4) - second
		fib(3) - first
			fib(2) - first
			fib(1) - second
		fib(2) - second

fibonacci(7, "MAIN") -> 25
fib(7) - main
	fib(6) - first
		fib(5) - first
			fib(4) - first
				fib(3) - first
					fib(2) - first
					fib(1) - second
				fib(2) - second
			fib(3) - second
				fib(2) - first
				fib(1) - second
		fib(4) - second
			fib(3) - first
				fib(2) - first
				fib(1) - second
			fib(2) - second
	fib(5) - second
		fib(4) - first
			fib(3) - first
				fib(2) - first
				fib(1) - second
			fib(2) - second
		fib(3) - second
			fib(2) - first
			fib(1) - second

11. Reverse Number

package com.example.java.programming;

/**
 * @author code.factory
 *
 */
public class ReverseNumber {
	public static void main(String[] args) {
		reverseNo(12345);
		System.out.println(reverseRec(12345, 0));
	}

	public static void reverseNo(int i) {
		int no = 0;
		while(i > 0) {
			no = (i % 10) + (no * 10);
			i = i / 10;
		}
		System.out.println(no); // 54321
	}

	public static int reverseRec(int i, int no) {
		if(i == 0) {
			return no;
		} else {
			no = (i % 10) + (no * 10);
			return reverseRec(i /= 10, no);
		}
	}
}

Output:

54321
54321

12. Armstrong Number

package com.example.java.programming;

/**
 * @author code.factory
 *
 */
public class ArmstrongNumber {
	public static void main(String... args) {
		armstrongNo(153);
	}
	
	public static void armstrongNo(int i) {
		int original = i;
		int no = 0, temp;
		while(i > 0) {
			temp = i % 10;
			no = no + (temp * temp * temp);
			i = i / 10;
		}
		System.out.println(original == no); // true

	}
}

13. Palindrom or not

package com.test;

/**
 * @author code.factory
 *
 */
public class Test {

	public static void main(String... strings) {
		isIntPalindrome(123);
		isIntPalindrome(1221);
		
		isStringPalindrome("MADAM");
		isStringPalindrome("MADAN");
	}

	private static void isIntPalindrome(int i) {
		int revNo = 0;
		int no = i;
		while(i > 0) {
			revNo = (i % 10) + (revNo * 10);
			i = i / 10;
		}
		System.out.println(no + ((no == revNo)? " is Palindrome" : " is not Palindrome"));
	}

	static void isStringPalindrome(String s) {
		int i = 0;
		int j = s.length() - 1;
		while (i < j) {
			if (s.charAt(i) != s.charAt(j)) {
				System.out.println(s + " is Not Palindrome");
				return;
			}
			i++;
			j--;
		}
		System.out.println(s + " is Palindrome");
	}
}

Output:

123 is not Palindrome
1221 is Palindrome

MADAM is Palindrome
MADAN is Not Palindrome

14. Leap Year

package com.example.java.programming;

/**
 * @author code.factory
 *
 */
public class LeapYear {
	public static void main(String... args) {
		leapYear(1900);
		leapYear(2000);
		leapYear(2100);
		leapYear(2200);
	}
	
	/**
	 * Leap Year is a year which is divisible by 4, 
	 * but we skip those years which are divisible by 100 but not by 400
	 * means 1700, 1800, 1900 are divisile by 100 but not by 400 so these are Not a Leap Year 
	 */
	public static void leapYear(int year) {
		System.out.println((year % 4 == 0) && !((year % 400 != 0) && (year % 100 == 0)));
		
		System.out.println((year % 400 == 0) || ((year % 100 != 0) && (year % 4 == 0)));
		
		if(year % 4 == 0) {
			if(year % 100 == 0 && year % 400 != 0) {
				System.out.println("no");
			} else {
				System.out.println("yes");
			}
		}
		System.out.println();
	}
}

Output :

false
false
no

true
true
yes

false
false
no

false
false
no

15. Create new Array or ArrayList using randomization functionality to it.

package com.test;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author code.factory
 *
 */
public class Test {

	public static void main(String... strings) {
		randomize( new ArrayList<Integer>(Arrays.asList(3, 4, 1, 5, 2, 8)));
		randomize( new ArrayList<Integer>(Arrays.asList(9, 8, 0, 1, 3)));
	}

	static void randomize(ArrayList<Integer> input) {
		System.out.println("Input: " + input);
		int length = input.size();
		int r1, swap;
		for (int i = 0; i < input.size(); i++) {
			r1 = (int) (Math.random() * length);
			swap = input.get(r1);
			input.set(r1, input.get(i));
			input.set(i, swap);
		}
		System.out.println("Output: " + input);
	}
}

Output:

Input: [3, 4, 1, 5, 2, 8]
Output: [5, 1, 2, 4, 8, 3]

Input: [9, 8, 0, 1, 3]
Output: [8, 9, 0, 1, 3]

16. Circular Number

  • Circular Number is cyclic permutations of the digits.
package com.codeFactory;

/**
 * @author code.factory
 *
 */
public class CircularNumber {

	public static void main(String... args) {
		circularNumber("1234");
	}

	public static String[] circularNumber(String noStr) {
		String[] str = new String[noStr.length()];
		for (int i = 0; i < noStr.length(); i++) {
			str[i] = "";
			for (int j = i; j < noStr.length(); j++) {
				str[i] += noStr.charAt(j);
			}
			for (int k = 0; k < i; k++) {
				str[i] += noStr.charAt(k);
			}
			System.out.println(str[i]);
		}
		return str;
	}
}

Output:

1234
2341
3412
4123

20. Find angle between hour and minute hand (Clock Angle Problem)

package com.example.java.programming.test;

public class CodeFactory {	
	public static void main(String[] args) {
		System.out.println(findAngle(1, 00));
	}
	
	private static int findAngle(int hour, int min) {
		/* hour multiply with 5 and 6 or 30 (because clock is 360 degree)
		 * so degree b/w hour is -> hour * 30 
		 * OR hour * (total minutes b/w hours) * (degree of each minutes) 
		 * Also add extra degree because as minutes changes from
		 * one angle to another, hour position is also changed.
		 * From any hour to its next hour there is 30 degree and
		 * clock have 60 minutes so we divide minutes to 2 (min / 2)
		 * */
		int h = (hour * 5 * 6) + (min / 2);
		
		/* Multiple minutes with 6 because clock is 360 degree
		 * and minutes are 60, So if we multiply minutes to 6 
		 * then we get degree of minutes
		 * */
		int m = min * 6;
		
		// calculate the angle difference
		int angle = Math.abs(h - m);
		 
		// consider shorter angle and return it
		return angle>180? 360-angle : angle;
	}

}

Output:

1:00
-> 30

2:30
-> 105

5:30
-> 15

9:00
-> 90

9:60
-> 60

21.

package com.example.java.programming;

import java.util.Arrays;

/**
 * @author code.factory
 */
public class Test {
	public static void main(String... strings) throws Exception {
		int arr[] = {9, 5, 9};
		System.out.println(Arrays.toString(add(arr)));
	}

	static int[] add(int arr[]) {
		int carry = 1, total;
		int result[] = new int[arr.length];
		for (int i = (arr.length - 1); i >= 0; i--) {
			total = arr[i] + carry;
			carry = total == 10 ? 1 : 0;
			result[i] = total % 10;
		}
		if (carry == 1) {
			result = new int[arr.length + 1];
			result[0] = 1;
		}
		return result;
	}
}

Output:

/* Time Complexity of this is O(n) */

{9, 5, 9}
-> [9, 6, 0]

{1, 5, 0}
-> [1, 5, 1]

{9, 9, 9, 9, 9}
-> [1, 0, 0, 0, 0, 0]

22. Find all Subsets of a Set.

package com.example.java.programming;

import java.util.Arrays;

/**
 * @author code.factory
 */
public class Test {
	public static void main(String... strings) throws Exception {
		int arr[] = { 1, 2, 3 };
		allSubsets(arr);
	}

	private static void allSubsets(int[] arr) {
		int subset[] = new int[arr.length];
		helper(arr, subset, 0, "Main");
	}

	private static void helper(int[] arr, int[] subsets, int i, String str) {
		print(i, str, subsets);
		if (i == arr.length) {
			print(subsets);
		} else {
			subsets[i] = 0;
			helper(arr, subsets, i + 1, "First");
			subsets[i] = arr[i];
			helper(arr, subsets, i + 1, "Second");
		}
	}

	private static void print(int[] arr) {
		System.out.print("{");
		for (int i : arr) {
			if (i != 0) {
				System.out.print(i + ", ");
			}
		}
		System.out.print("}");
		System.out.println();
	}
	
	private static void print(int count, String str, int[] subsets) {
		for(int i=0; i<count*2; i++) {
			System.out.print(" ");
		}
		System.out.println(str + " - " + Arrays.toString(subsets));
	}
}

Output:

{}
{3, }
{2, }
{2, 3, }
{1, }
{1, 3, }
{1, 2, }
{1, 2, 3, }

/* Explanation */
helper(0) - main [0, 0, 0]
	helper(1) - first [0, 0, 0]
		helper(2) - first [0, 0, 0]
			helper(3) - first [0, 0, 0]
			helper(3) - second [0, 0, 3]
		helper(2) - second [0, 2, 3]
			helper(3) - first [0, 2, 0]
			helper(3) - second [0, 2, 3]
	helper(1) - second [1, 2, 3]
		helper(2) - first [1, 0, 3]
			helper(3) - first [1, 0, 0]
			helper(3) - second [1, 0, 3]
		helper(2) - second [1, 2, 3]
			helper(3) - first [1, 2, 0]
			helper(3) - second [1, 2, 3]

23. Check if edit distance between two strings is one.

24. Print all permutations of a String in Java.

25. Find Second largest element in an array.

26. Find subarray with given sum
– Given an unsorted array of nonnegative integers, find a continuous subarray.

27. Program for array rotation

Write a function rotate(ar[], x) that rotates arr[] of size n by x elements.

array -> | 1 | 2 | 3 | 4 | 5 |
x = 1 -> | 2 | 3 | 4 | 5 | 1 |
x = 2 -> | 3 | 4 | 5 | 1 | 2 |

28. Write a program to calculate power(x, y)

29. Palindrome Counter

AAA -> {A, A, A, AA, AA, AAA} -> so return 6
ABA -> {A, B, A, AB, BA, ABA} -> so return 4
TACOCAT -> return 10

30. Rotate Matrix

31. Look-and-say or Count-and-say Sequence

1, 11, 21, 1211, 111221, 312211, ……
– 1 is read off as “one 1” or 11.
– 11 is read off as “two 1s” or 21.
– 21 is read off as “one 2, then one 1” or 1211.
– 1211 is read off as “one 1, one 2, then two 1s” or 111221.

32. Move All Zeroes to End of Array

Input: {51, 65, 32, 0, 48, 0, 0, 35}
Output: [51, 65, 32, 48, 35, 0, 0, 0]

Input: {41, 34, 6, 22, 0, 0, 54, 99, 0, 33, 0}
Output: [41, 34, 6, 22, 54, 99, 33, 0, 0, 0, 0]

33. Find Next Greater Number With Same Set of Digits

Input: 654925
Output: 654952

Input: 1432
Output: 2134

Input: 987654
Output: Next greater number not possible with same digit

Input: 1111
Output: Next greater number not possible with same digit

Input: 34
Output: 43

Input: 43
Output: Next greater number not possible with same digit

Leave a comment