Top 50 Java Programming Interview Questions – JournalDev

Java Programming Interview Questions are constantly the deciding factor in any Java interview. Whether you are a novice in Java or an technical programmer, you will be tested for your coding skills in the interview. so, it ’ s a good theme to brush up your coding skills before you face the interview .

Java Programming Interview Questions

I am providing 50+ Java programming questions to test your coding skills. It ’ sulfur good for beginners angstrom well as experience Java developers. The best contribution is that some of the questions are from the latest releases ( Java 14 ). If you can write Java programs using the latest features, it means you keep yourself up to date, which will work in your prefer.

1. How to reverse a String in Java?

It might be storm, but there is no invert ( ) utility method in the String class. But, it ’ s a very dim-witted tax. We can create a character array from the bowed stringed instrument and then iterate it from the end to start. We can append the characters to a string builder and finally return the change by reversal bowed stringed instrument .

public class StringPrograms {

	public static void main(String[] args) {

		String str = "123";
		System.out.println(reverse(str));
	}

	public static String reverse(String in) {
		if (in == null)
			throw new IllegalArgumentException("Null is not valid input");

		StringBuilder out = new StringBuilder();

		char[] chars = in.toCharArray();

		for (int i = chars.length - 1; i >= 0; i--)
			out.append(chars[i]);

		return out.toString();
	}
}

Bonus Points : Adding nothing check in the method and using StringBuilder for appending the characters. Easy to Miss : The index in Java starts from 0. so, we have to start at “ chars.length – 1 ” in the for loop .

2. How to swap two numbers without using a third variable?

It ’ s a slightly catchy interview. It ’ s a three steps process. It ’ s better visualized in code.

int a = 10;
int b = 20;

b = b + a; // now b is sum of both the numbers
a = b - a; // b - a = (b + a) - a = b (a is swapped)
b = b - a; // (b + a) - b = a (b is swapped)

We can ’ thyroxine render multiple variables in Java. Since Java is Pass-by-Value and these are crude data types, their values won ’ t change. For model, below swap function will not change the input signal integer values .

public static void swapNumbers(int a, int b) {
    b = b + a;
	a = b - a;
	b = b - a;
}

public static void main(String[] args) {
	int a = 10;
	int b = 20;
	swapNumbers(a, b);
	System.out.printf("a is %d, b is %d", a, b); // a is 10, b is 20
}

3. Java Program to check if a vowel is present in the string?

We can use regular expression to check if the string contains vowels or not .

public class StringContainsVowels {

	public static void main(String[] args) {

		System.out.println(stringContainsVowels("Hello")); // true
		System.out.println(stringContainsVowels("TV")); // false

	}

	public static boolean stringContainsVowels(String input) {

		return input.toLowerCase().matches(".*[aeiou].*");

	}

}

4. Java program to check if the given number is Prime?

We can write a simple program to divide the given number “ n ” from 2 to n/2 and check the remainder. If the remainder is 0, then it ’ s not a prime total .

public class PrimeNumberCheck {

	public static void main(String[] args) {

		System.out.println(isPrime(19)); // true
		System.out.println(isPrime(49)); // false
	}

	public static boolean isPrime(int n) {
		if (n == 0 || n == 1) {
			return false;
		}
		if (n == 2) {
			return true;
		}
		for (int i = 2; i <= n / 2; i++) {
			if (n % i == 0) {
				return false;
			}
		}

		return true;
	}
}

But, this is not very memory and time-efficient. For a given number N, if there is a premier number M between 2 to √N ( square etymon of N ) that evenly divides it, then N is not a prime number. You can read more about it here.

5. Fibonacci Series using recursion

We can use a for loop to print fibonacci series .

public static void printFibonacciSeries(int count) {
	int a = 0;
	int b = 1;
	int c = 1;
	for (int i = 1; i <= count; i++) {
		System.out.print(a + ", ");
		a = b;
		b = c;
		c = a + b;
	}
}

The fibonacci number is generated by adding the previous two numbers – F ( N ) = F ( N-1 ) + F ( N-2 ). We can use recursion to print fibonacci series .

public class FibonacciNumbers {
	public static int fibonacci(int n) {
		if (n <= 1)
			return n;
		return fibonacci(n - 1) + fibonacci(n - 2);
	}

	public static void main(String args[]) {
		int n = 10;
		System.out.println(fibonacci(n));
	}
}

6. Check if a List of integers contains only odd numbers?

We can use for closed circuit and check each element one by one if they are odd or not .

public static boolean onlyOddNumbers(List list) {
	for (int i : list) {
		if (i % 2 == 0)
			return false;
	}
	return true;
}

If the list is huge, we can use parallel stream for fast march .

public static boolean onlyOddNumbers(List list) {
	return list
			.parallelStream() // parallel stream for faster processing
			.anyMatch(x -> x % 2 != 0); // return as soon as any elements match the condition
}

7. Palindrome Check

A palindrome drawstring is one whose revoke is besides the lapp string. So we can reverse the input string and check if both strings are equal or not. We can besides use the String charAt ( int index ) method to check for palindrome string.

boolean checkPalindromeString(String input) {
	boolean result = true;
	int length = input.length();
	for(int i=0; i < length/2; i++) {
		if(input.charAt(i) != input.charAt(length-i-1)) {
			result = false;
			break;
		}
	}
	return result;
}

8. How to remove Whitespaces from String

We can use Character.isWhitespace ( ) method to remove whitespaces from the string .

String removeWhiteSpaces(String input){
	StringBuilder output = new StringBuilder();
	
	char[] charArray = input.toCharArray();
	
	for(char c : charArray) {
		if (!Character.isWhitespace(c))
			output.append(c);
	}
	
	return output.toString();
}

9. How to remove leading and trailing whitespaces from a string?

Java String class contains two methods to remove leading and trailing whitespaces – trim ( ), and strip ( ). The strip ( ) method acting was added to the String course in Java 11. however, the clean ( ) method acting uses Character.isWhitespace ( ) method acting to check if the character is a whitespace. This method acting uses Unicode code points whereas the shipshape ( ) method acting identifies any character having codepoint value less than or equal to ‘ U+0020 ’ as a whitespace character. The denude ( ) method acting is the recommend way to remove whitespaces because it uses the Unicode standard .

String s = "  abc  def\t";
		
s = s.strip();
		
System.out.println(s);

Since String is immutable, we have to assign the strip ( ) output to the string .

10. Sorting an array in Java?

This question requires a deep sympathize of sorting in Java. If you look at the Arrays utility class, there are many overload sort ( ) methods to sort primitive american samoa well as to object arrays. If you are sorting a primitive array in the natural ordain, then it ’ randomness very simple. Just use the Arrays.sort ( ) method .

int[] array = {1, 2, 3, -1, -2, 4};

Arrays.sort(array);

System.out.println(Arrays.toString(array));

But, if you want to sort an array of Objects, then the aim must implement Comparable interface. If you want to specify the sort criteria, then you can pass the Comparator for the sorting logic. You should read more about them at – Comparable and Comparator in Java .

11. How to Create a Deadlock Scenario Programatically?

Deadlock is a particular scenario in the multi-threaded environment where two or more threads are blocked everlastingly. The deadlock situation arises with at least two threads and two or more threads. Let ’ s write a elementary course of study to create a deadlock .

public class ThreadDeadlock {

    public static void main(String[] args) throws InterruptedException {
        Object obj1 = new Object();
        Object obj2 = new Object();
        Object obj3 = new Object();
    
        Thread t1 = new Thread(new SyncThread(obj1, obj2), "t1");
        Thread t2 = new Thread(new SyncThread(obj2, obj3), "t2");
        Thread t3 = new Thread(new SyncThread(obj3, obj1), "t3");
        
        t1.start();
        Thread.sleep(5000);
        t2.start();
        Thread.sleep(5000);
        t3.start();
        
    }

}

class SyncThread implements Runnable{
    private Object obj1;
    private Object obj2;

    public SyncThread(Object o1, Object o2){
        this.obj1=o1;
        this.obj2=o2;
    }
    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        System.out.println(name + " acquiring lock on "+obj1);
        synchronized (obj1) {
         System.out.println(name + " acquired lock on "+obj1);
         work();
         System.out.println(name + " acquiring lock on "+obj2);
         synchronized (obj2) {
            System.out.println(name + " acquired lock on "+obj2);
            work();
        }
         System.out.println(name + " released lock on "+obj2);
        }
        System.out.println(name + " released lock on "+obj1);
        System.out.println(name + " finished execution.");
    }
    private void work() {
        try {
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

All the three threads will be able to acquire a lock on the first object. But, they are using the divided resources and started in such a way that they will keep on waiting indefinitely to acquire the lock on the second object. We can use the java ribbon dump to detect the deadlocks. Read more at Deadlock in Java .

12. Find factorial of an integer?

The factorial of an integer is calculated by multiplying all the numbers from 1 to the given number. F ( newton ) = F ( 1 ) * F ( 2 ) …F ( n-1 ) * F ( newton ). We can use recursion to find the factorial of an integer .

public static long factorial(long n) {
	if (n == 1)
		return 1;
	else
		return (n * factorial(n - 1));
}

13. Revese a Linked List?

LinkedList descendingIterator ( ) returns an iterator that iterates over the chemical element in the reverse order. We can use this iterator to create a new Linked list with elements in the reverse ordering .

LinkedList ll = new LinkedList<>();

ll.add(1);
ll.add(2);
ll.add(3);
System.out.println(ll);

LinkedList ll1 = new LinkedList<>();

ll.descendingIterator().forEachRemaining(ll1::add);

System.out.println(ll1);

If you are looking from the data structures and algorithm position, read reversing a linked list .

14. How to implement Binary Search?

The array elements must be sorted for implementing binary star research. The binary search algorithm is based on the follow conditions. If the key is less than the middle element, then we nowadays need to search alone in the first half of the array.
If the cardinal is greater than the middle component, then we need to only search in the second half of the array.
And if the key is equal to the middle chemical element in the array, then the search ends.
last, if the key is not found in the wholly array, then it should return -1. This indicates that the chemical element is not award .

public static int binarySearch(int arr[], int low, int high, int key) {
	int mid = (low + high) / 2;

	while (low <= high) {
		if (arr[mid] < key) {
			low = mid + 1;
		} else if (arr[mid] == key) {
			return mid;
		} else {
			high = mid - 1;
		}
		mid = (low + high) / 2;
	}
	if (low > high) {
		return -1;
	}
	return -1;
}

15. Merge Sort in Java?

Merge classify is one of the most efficient sorting algorithm. It works on the principle of Divide and Conquers. It is based on the estimate of breaking down a list into respective sub-lists until each sublist consists of a single component. then merging those sublists in a manner that results in a grouped tilt .

public class MergeSort {

	public static void main(String[] args) {

		int[] arr = { 70, 50, 30, 10, 20, 40, 60 };

		int[] merged = mergeSort(arr, 0, arr.length - 1);

		for (int val : merged) {
			System.out.print(val + " ");
		}

	}

	public static int[] mergeTwoSortedArrays(int[] one, int[] two) {

		int[] sorted = new int[one.length + two.length];

		int i = 0;
		int j = 0;
		int k = 0;

		while (i < one.length && j < two.length) {

			if (one[i] < two[j]) {
				sorted[k] = one[i];
				k++;
				i++;
			} else {
				sorted[k] = two[j];
				k++;
				j++;
			}
		}

		if (i == one.length) {

			while (j < two.length) {
				sorted[k] = two[j];
				k++;
				j++;
			}
		}

		if (j == two.length) {

			while (i < one.length) {
				sorted[k] = one[i];
				k++;
				i++;
			}
		}

		return sorted;

	}

	public static int[] mergeSort(int[] arr, int lo, int hi) {

		if (lo == hi) {
			int[] br = new int[1];
			br[0] = arr[lo];

			return br;
		}

		int mid = (lo + hi) / 2;

		int[] fh = mergeSort(arr, lo, mid);
		int[] sh = mergeSort(arr, mid + 1, hi);

		int[] merged = mergeTwoSortedArrays(fh, sh);

		return merged;
	}

}

16. Create a Pyramid of Characters in Java?

form programs are used a bunch in interviews to understand the coherent think abilities of the interviewee. Pyramid patterns are very popular and once we get the logic on the way it ’ randomness created, writing code to achieve the same is an easy task. I have written an extensive post for different kind of pyramid patterns examples, read it here .

17. Check if two arrays contains same elements?

We will first create a determined of elements from both the arrays. then compare the elements in these sets to find if there is an element that is not portray in both the sets ?

package com.journaldev.programminginterviews;

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

public class ArraySameElements {

	public static void main(String[] args) {
		Integer[] a1 = {1,2,3,2,1};
		Integer[] a2 = {1,2,3};
		Integer[] a3 = {1,2,3,4};
		
		System.out.println(sameElements(a1, a2));
		System.out.println(sameElements(a1, a3));

	}

	static boolean sameElements(Object[] array1, Object[] array2) {
		Set uniqueElements1 = new HashSet<>(Arrays.asList(array1));
		Set uniqueElements2 = new HashSet<>(Arrays.asList(array2));
		
		// if size is different, means there will be a mismatch
		if(uniqueElements1.size() != uniqueElements2.size()) return false;
		
		for(Object obj : uniqueElements1) {
			// element not present in both?
			if (!uniqueElements2.contains(obj)) return false;
		}
		
		return true;
	}
}

18. Sum of all elements in integer array?

It ’ s a very simple plan. We can use for loop topology to iterate over the range elements and add them to get the final kernel .

int[] array = { 1, 2, 3, 4, 5 };

int sum = 0;

for (int i : array)
	sum += i;

System.out.println(sum);

19. Find second largest number in an array?

There are many ways to solve this problem. We can sort the array in natural ascending order and take the second gear last value. But, sorting is an expensive operation. We can besides use two variables to find the irregular largest value in a single iteration .

private static int findSecondHighest(int[] array) {
	int highest = Integer.MIN_VALUE;
	int secondHighest = Integer.MIN_VALUE;

	for (int i : array) {
		if (i > highest) {
			secondHighest = highest;
			highest = i;
		} else if (i > secondHighest) {
			secondHighest = i;
		}

	}
	return secondHighest;
}

20. How to Shuffle an Array in Java?

We can use Random class to generate random index numbers and shuffle the elements .

int[] array = { 1, 2, 3, 4, 5, 6, 7 };

Random rand = new Random();

for (int i = 0; i < array.length; i++) {
	int randomIndexToSwap = rand.nextInt(array.length);
	int temp = array[randomIndexToSwap];
	array[randomIndexToSwap] = array[i];
	array[i] = temp;
}
System.out.println(Arrays.toString(array));

We can run the shuffle code inside another for loop to shuffle multiple rounds.

21. How to find if a string is present in a text file?

We can use Scanner class to read the file contents occupation by wrinkle. then use String contains ( ) method to check if the string is present in the charge or not .

boolean findStringInFile(String filePath, String str) throws FileNotFoundException {
	File file = new File(filePath);

	Scanner scanner = new Scanner(file);

	// read the file line by line
	while (scanner.hasNextLine()) {
		String line = scanner.nextLine();
		if (line.contains(str)) {
			scanner.close();
			return true;
		}
	}
	scanner.close();
	return false;
}

The above code assumes that the bowed stringed instrument we are searching for in the file doesn ’ metric ton control newline characters .

22. How to print date in specific format?

We can use SimpleDateFormat class to get the date string into particular format .

String pattern = "MM-dd-yyyy";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

String date = simpleDateFormat.format(new Date());
System.out.println(date); // 06-23-2020

Recommended reading : Java SimpleDateFormat .

23. How to merge two lists in java?

We can use the addAll ( ) method acting to merge multiple lists in Java.

List list1 = new ArrayList<>();
list1.add("1");
List list2 = new ArrayList<>();
list2.add("2");

List mergedList = new ArrayList<>(list1);
mergedList.addAll(list2);
System.out.println(mergedList); // [1, 2]

24. How to Sort HashMap by values?

HashMap is not an order collection. so, sorting its entries doesn ’ t make any sense. But, we can sort the entries based on value and shop into LinkedHashMap. LinkedHashMap maintains the regulate of interpolation .

package com.journaldev.programminginterviews;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class SortHashMapByValue {

	public static void main(String[] args) {
		Map scores = new HashMap<>();

		scores.put("David", 95);
		scores.put("Jane", 80);
		scores.put("Mary", 97);
		scores.put("Lisa", 78);
		scores.put("Dino", 65);

		System.out.println(scores);

		scores = sortByValue(scores);

		System.out.println(scores);

	}

	private static Map sortByValue(Map scores) {
		Map sortedByValue = new LinkedHashMap<>();

		// get the entry set
		Set> entrySet = scores.entrySet();
		System.out.println(entrySet);

		// create a list since the set is unordered
		List> entryList = new ArrayList<>(entrySet);
		System.out.println(entryList);

		// sort the list by value
		entryList.sort((x, y) -> x.getValue().compareTo(y.getValue()));
		System.out.println(entryList);

		// populate the new hash map
		for (Entry e : entryList)
			sortedByValue.put(e.getKey(), e.getValue());

		return sortedByValue;
	}

}

25. remove all occurrences of a given character from input String?

String class doesn ’ triiodothyronine have any method to remove characters. We can use the replace ( ) method to create a newfangled string without the given character .

String str1 = "abcdABCDabcdABCD";
		
str1 = str1.replace("a", ""); 

System.out.println(str1); // bcdABCDbcdABCD

The string is immutable in Java. All the string manipulation methods return a newly string. then, it ’ mho necessary that we assign it to another variable .

26. How to get distinct characters and their count in a String?

We can create the fictional character align from the drawstring. then iterate over it and create a HashMap with the character as key and their count as value .

String str1 = "abcdABCDabcd";

char[] chars = str1.toCharArray();

Map charsCount = new HashMap<>();

for(char c : chars) {
	if(charsCount.containsKey(c)) {
		charsCount.put(c, charsCount.get(c)+1);
	}else
		charsCount.put(c, 1);
}

System.out.println(charsCount); // {a=2, A=1, b=2, B=1, c=2, C=1, d=2, D=1}

27. How to prove String is immutable programatically?

String s1 = "Java"; // "Java" String created in pool and reference assigned to s1

String s2 = s1; //s2 is also having the same reference to "Java" in the pool

System.out.println(s1 == s2); // proof that s1 and s2 have same reference

s1 = "Python"; 
//s1 value got changed above, so how String is immutable?

//well, in the above case a new String "Python" got created in the pool
//s1 is now referring to the new String in the pool 
//BUT, the original String "Java" is still unchanged and remains in the pool
//s2 is still referring to the original String "Java" in the pool

// proof that s1 and s2 have different reference
System.out.println(s1 == s2); 

System.out.println(s2); 
// prints "Java" supporting the fact that original String value is unchanged, hence String is immutable

28. Write a Program to showcase inheritance?

class Animal {
	String color;
}

class Cat extends Animal {
	void meuw(){
		System.out.println("Meuw");
	}
}

29. Write a Program to Show Diamond Problem with Multiple Inheritance?

Java doesn ’ triiodothyronine allow extending multiple classes. It ’ randomness to keep it simple and keep off diamond problem.

interface I {
	void foo();
}
class A implements I{
	public void foo() {}
}

class B implements I{
	public void foo() {}
}

class C extends A, B { // won't compile
	public void bar() {
		super.foo();
	}
}

In above exercise, if Java would have allowed multiple class inheritance, then which super foo ( ) method should get called ? There could be a mechanism to fix this, but Java speech developers thought it ’ s better to keep it simple by not allowing multiple inheritance .

30. Write a Program to show try catch example?

Let ’ s search at a simple try-catch obstruct code .

try {
	FileInputStream fis = new FileInputStream("test.txt");
}catch(FileNotFoundException e) {
	e.printStackTrace();
}

From Java 7 onwards, We can besides catch multiple exceptions in a individual trip up pulley. It ’ sulfur utilitarian when we have the lapp code in all the catch blocks .

public static void foo(int x) throws IllegalArgumentException, NullPointerException {
	// some code
}

public static void main(String[] args) {
	try {
		foo(10);
	} catch (IllegalArgumentException | NullPointerException e) {
		System.out.println(e.getMessage());
	}
}

31. Write a code to show NullPointerException

If we are calling a function on the “ nothing ”, it will throw NullPointerException .

public static void main(String[] args) {
	printString(null, 3);
	
}

static void printString(String s, int count){
	for (int i = 0 ; i < count; i++) {
		System.out.println(s.toUpperCase()); // Exception in thread "main" java.lang.NullPointerException
	}
}

That ’ randomness why it ’ s better to have nothing crack in place for early establishment.

static void printString(String s, int count){
	if(s == null) return;
	for (int i = 0 ; i < count; i++) {
		System.out.println(s.toUpperCase());
	}
}

We can besides throw IllegalArgumentException based on the stick out requirements .

32. How to Create a Record in Java?

Records is a preview feature introduced in Java 14. Records allow us to create a POJO class with minimal code. It automatically generates hashCode ( ), equals ( ), getter methods, and toString ( ) method code for the class. Records are final and implicitly extends java.lang.Record class .

import java.util.Map;
 
public record EmpRecord(int id, String name, long salary, Map addresses) {
}

Read more at Records in Java .

33. How to create Text Blocks in Java?

Java 13 added text blocks as a preview feature. We can create multiline strings using text blocks. The multiline string has to be written inside a pair of triple-double quotes.

String textBlock = """
		Hi
		Hello
		Yes""";

It ’ mho same as creating a string as “ Hi\nHello\nYes ” .

34. Show example of switch expressions and multi-label case statements

The switch expressions were added as a preview have in Java 12. It became a standard feature in Java 14 release. The below examples show throw expressions a well as multi-label case statements .

int choice = 2;

int x = switch (choice) {
case 1, 2, 3:
	yield choice;
default:
	yield -1;
};
System.out.println("x = " + x); // x = 2

We can besides use lambda expressions in switch expressions .

String day = "TH";
String result = switch (day) {
case "M", "W", "F" -> "MWF";
case "T", "TH", "S" -> "TTS";
default -> {
	if (day.isEmpty())
		yield "Please insert a valid day.";
	else
		yield "Looks like a Sunday.";
}

};
System.out.println(result); // TTH

35. How to Compile and Run a Java Class from Command Line?

Let ’ s say we have a class as downstairs .

public class Test {

public static void main(String args[]) {
		System.out.println("Hi");
	}

}

We can compile it using the comply code.

javac Test.java

For running the class, we can run the following command .

java Test

From the holocene releases, coffee instruction will take care of compilation besides if the class file is not present. If the class is in a box com.journaldev, then it should be inside the booklet com/journaldev. The command to compile and run will be as follows .

java com/journaldev/Test.java

If our course requires some extra JARs to compile and run, we can use the -cp coffee option .

java -cp .:~/.m2/repository/log4j/log4j/1.2.17/log4j-1.2.17.jar  com/journaldev/Test.java

36. How to create Enum in Java?

Let ’ s attend at a simple Enum.

public enum ThreadStates {
	START,
	RUNNING,
	WAITING,
	DEAD;
}

ThreadStates is the enum with fix constants fields START, RUNNING, WAITING, and DEAD. All Enum implicitly extends java.lang.Enum class and implements Serializable and comparable interfaces. Enum can have methods besides, read more at Enums in Java .

37. How to use forEach() method?

The forEach ( ) method acting provides a shortcut to perform an legal action on all the elements of an iterable. Let ’ s say we have to iterate over the number elements and print it .

List list = new ArrayList<>();

Iterator it = list.iterator();

while (it.hasNext()) {
	System.out.println(it.next());
}

We can use forEach ( ) method with lambda construction to reduce the code size .

List list = new ArrayList<>();

list.forEach(System.out::print);

38. Write an interface with default and static method?

Java 8 introduced nonpayment and inactive methods in interfaces. This has bridged the opening between interfaces and abstract classes .

public interface Interface1 {
	
	// regular abstract method
	void method1(String str);
	
	default void log(String str){
		System.out.println("I1 logging::"+str);
	}
	
	static boolean isNull(String str) {
		System.out.println("Interface Null Check");

		return str == null ? true : "".equals(str) ? true : false;
	}
}

Read more at Java 8 interface changes .

39. How do we create a Functional interface?

An interface with precisely one abstract method is called functional Interface. @ FunctionalInterface annotation is added so that we can mark an interface as functional interface. The major benefit of java 8 functional interfaces is that we can use lambda expressions to instantiate them and avoid using bulky anonymous class execution .

@FunctionalInterface
interface Foo {
	void test();
}

foster recitation : Java 8 Functional Interfaces.

40. Show an example of using lambda expressions in Java

Runnable is an excellent example of a functional interface. We can use lambda expressions to create a runnable .

Runnable r1 = () -> System.out.println("My Runnable");

You can learn everything about lambda expressions in this tutorial .

41. Show examples of overloading and overriding in Java

When a class have two or more methods with the same list, they are called overload methods .

class Foo {

	void print(String s) {
		System.out.println(s);
	}

	void print(String s, int count) {
		while (count > 0) {
			System.out.println(s);
			count--;
		}
	}
}

Recommended take : Method Overloading in Java. When a superclass method is besides implemented in the child course, it ’ s a encase of overriding .

class Base {
	void printName(){
		System.out.println("Base Class");
	}
}

class Child extends Base{
	@Override
	void printName(){
		System.out.println("Child Class");
	}
}

recommend Readings : Overriding in Java and Overriding volt Overloading .

42-49. Guess the Output of Code Snippets

Let ’ s spirit at 8 code snippets and guess their output .

  1. String s1 = "abc";
    String s2 = "abc";
    System.out.println("s1 == s2 is:" + s1 == s2);
    

    output : false explanation : The given statements output will be “ assumed ” because in java + operator precession is more than == operator. So the given formula will be evaluated to “ s1 == s2 is : rudiment ” == “ abc ” i.e delusive .

  2. String s3 = "JournalDev";
    int start = 1;
    char end = 5;
    System.out.println(start + end);
    System.out.println(s3.substring(start, end));
    

    output : ourn explanation : The given statements output will be “ ourn ”. First character will be mechanically type caste to int. After that since in java first character index is 0, so it will start from ‘ oxygen ’ and print public treasury ‘ north ’. bill that in String substring routine it leaves the end index .

  3. HashSet shortSet = new HashSet();
    for (short i = 0; i < 100; i++) {
    	shortSet.add(i);
    	shortSet.remove(i - 1);
    }
    System.out.println(shortSet.size());
    

    output : 100 explanation : The size of the shortSet will be 100. Java Autoboxing have has been introduced in JDK 5, indeed while adding the short to HashSet it will automatically convert it to Short object. Now “i-1” will be converted to an int while evaluation and after that it will autoboxed to Integer object but there is no Integer object in the HashSet, so it will not remove anything from the HashSet and finally its size will be 100.

  4. What will be the boolean “flag” value to reach the finally block?
    try {
    	if (flag) {
    		while (true) {
    		}
    	} else {
    		System.exit(1);
    	}
    } finally {
    	System.out.println("In Finally");
    }
    

    explanation : The last pulley will never be reached here. If flag will be TRUE, it will go into an infinite loop and if it ’ south faithlessly it ’ second exiting the JVM. So last block will never be reached here .

  5. String str = null;
    String str1="abc";
    System.out.println(str1.equals("abc") | str.equals(null));
    

    output : NullPointerException explanation : The given print affirmation will throw java.lang.NullPointerException because while evaluating the OR legitimate operator it will beginning evaluate both the literals and since str is null, .equals ( ) method acting will throw exception. Its always advisable to use abruptly circumference logical operators i.e “ || ” and “ & & ” which evaluates the literals values from leave and since the first actual will return dependable, it will skip the second literal evaluation .

  6. String x = "abc";
    String y = "abc";
    x.concat(y);
    System.out.print(x);
    

    output : rudiment explanation : The x.concat ( y ) will create a new bowed stringed instrument but it ’ s not assigned to x, so the value of x is not changed .

  7. public class MathTest {
    
    	public void main(String[] args) {
    		
    		int x = 10*10-10;
    		
    		System.out.println(x);
    	}
    
    }
    

    output : Runtime erroneousness explanation : This is a slippery motion, it looks like the test is about the regulate of execution of the mathematical operators and syntax of main method will get overlooked. It will produce Runtime error because independent method is not static, something like below .

    pankaj:bin pankaj$ java MathTest
    Error: Main method is not static in class MathTest, please define the main method as:
       public static void main(String[] args)
    
  8. public class Test {
    
    	public static void main(String[] args) {
    		try {
    			throw new IOException("Hello");
    		}catch(IOException | Exception e) {
    			System.out.println(e.getMessage());
    		}
    	}
    }
    

    output : Compile-Time Error

    explanation : It will be a compose prison term error as The exception IOException is already caught by the alternative exception .

update : question over to some more java coding interview questions .

50. Find 5 mistakes in the following code snippet

package com.journaldev.programming-interviews;

public class String Programs {

	static void main(String[10] args) {
		String s = "abc"
		System.out.println(s);
	}
}
  1. Package name can’t have hyphens.
  2. Class name can’t have whitespaces.
  3. The main method is not public, so it won’t run.
  4. The main method argument shouldn’t specify the size.
  5. The semicolon is missing in the string definition.

Conclusion

I have tried my best to include easy ampere well as slightly complex programming questions in this tutorial. besides, I have added code snippets and questions related to late changes in the Java features.
[ no_toc ]

source : https://gauday.com
Category : interview

We will be happy to hear your thoughts

Leave a reply

GauDay Crypto news and market tracking in real time
Logo
Enable registration in settings - general