Top 50+ Core Java Interview Questions

In this Java tutorial, we will Learn Top 50+ Core Java Interview Questions with detailed explanations. Whether, you are new in Java and looking for Core Java Interview Questions for Freshers, or Working in the Java domain for past few years, this article will definitely help you a lot. So, Let’s get started –

Prepare a Modern list of Core Java Interview Questions


Core Java Interview Questions are not so easy. That’s a tough fact! But, if you know how to tackle the problem systematically, then, you’ll get the correct direction to Ace your next Javarelated interview (and at the same time, ensure a better job position as well).

In this guide, we will learn different Java Programming Interview Questions based on a number of popular topics ranging from Arrays and String to Multi-threading and Concurrency.

Discloser*** Some of the questions have been directly taken from recent Core Java Interview Questions for experienced candidates taken by Amazon, Facebook, and Uber shared on Stack-Overflow.

Let’s begin your preparation with Table of contents –


50+ Core Java Interview Questions and Solutions

 

Tricky Fundamentals 

Solve the Core Java Interview Question

Q1. Find 6 mistakes in this Java code snippet?

package com.shubhamklogic.java-coding.interview.problems;

public class CheckIssues InProgram {

	static void Main(String[5] args) {
		String str = "xyz":
		System.out.println(s);
	}
}

 

Finding mistakes in a piece of code is a common core Java interview question pattern. In such problems, you’re given a piece of Java code with few syntactical issues, and you’ll have to find them. Here’s the code on Java-

Side Notes ***
Here are the mistakes in above code snippet –
  1. Java Package and Class’ name can’t have hyphens ‘-‘. Fix: java-coding to java.coding
  2. Class names in Java, can’t have whitespaces. Fix: Remove space between the class name”CheckIssues InProgram
  3. The main method is not specified as a public method, so it’ll not run.
  4. In Java, the name of ‘main‘ method must be in ‘small letters’.
  5. We can not specify the number of arguments inside the main() method.
  6. The colon ‘:‘ should be replaced with a semicolon ‘;‘ at the end of String object creation statement. Fix: Put a semicolon ‘;‘ at the end of String str = “xyz”;
  7. By the way, there is one more compile-time error, and that’s because of undefined variable ‘s‘. Here, the interviewer just check that whether you can find any extra bug or not.

Q2. Write a Java program to find Random number without using Math.random() method?

It’s an important Core Java Interview Question for all level Java developers. Let’s see how to use ThreadLocalRandom class to solve this Java interview question –

import java.util.concurrent.ThreadLocalRandom; 

public class RandomNumberProgram
{
    public static void main( String []arguments ) 
    { 
        // Default range is 0 to 999 to generate a list of Random numbers-
        int randomList1 = ThreadLocalRandom.current().nextInt(); 
        int randomList2 = ThreadLocalRandom.current().nextInt(); 
  
        // Printing random numbers-
        System.out.println("Random Integer : " + randomList1); 
        System.out.println("Random Integer : " + randomList2); 
  
        // The method nextDouble() would return Random values of double type-
        double randomDoubles1 = ThreadLocalRandom.current().nextDouble(); 
        double randomDoubles2 = ThreadLocalRandom.current().nextDouble(); 
  
        // Printing random values (of double type)
        System.out.println("Random Double : " + randomDoubles1); 
        System.out.println("Random Double : " + randomDoubles2); 
  
        // Method nextBoolean() would return boolean type random values-
        boolean randomBooleans1 = ThreadLocalRandom.current().nextBoolean(); 
        boolean randomBooleans2 = ThreadLocalRandom.current().nextBoolean(); 
  
        // Printing random Booleans 
        System.out.println("Random Boolean : " + randomBooleans1); 
        System.out.println("Random Boolean : " + randomBooleans2); 
    } 
}
/*                -: OUTPUT :-
    Random Integer : -2087413414
    Random Integer : 2010941294
    Random Double : 0.46600872829248874
    Random Double : 0.739558328779781
    Random Boolean : false
    Random Boolean : true                         */

 

 

Notes For You***
In the above Java code, We have used ThreadLocalRandom class to generate random numbers of different types. Also, I didn’t use the ‘Math.random() method’ as that was the criteria of the interviewer.
Here are the Top 4 ways to generate Random numbers in Java, that you can check for further learnings.

Solve Condition based Core Java Interview Questions
It’s basically a flow chart, that represents how the control flows when we run a program having some conditional code. If you are facing difficulty in understanding it, chances are your fundamentals are not perfect. Here is Java In-Depth: Become a Complete Java Engineer! course on Udemy by Dheeru M. where, he explained all the basic to advanced level Java concepts including Arrays, String, Collections, and more. You should have a look in it to be better in Java.

Q3. Which condition would be executed in below Java code?

The below Java code snippet contains 2 conditions (with if blocks), and your task is to explain which one will be executed-

public class ProgramBySKL
{
    public static void main(String []arguments)
    {
        int num1 = 100;
        int num2 = 100;
        if(num1 == num2){      // Condition 1
            System.out.println("Numbers are Equal");
        }
        if(num1 =! num2){      // Condition 2
            System.out.println("Numbers are NOT Equal");
        }
    }
}

 

Side Notes***
You might be thinking that the output of the above Java coding question would be “Numbers are Equal”. But wait, go back and pay some attention to the // Condition 2 of the above code.
Now, you might already know, that the program would not even run, and will give an ERROR: bad operand type Integer for unary operator ‘!‘. The problem is with =!  symbols in Condition 2, which was not understood by Java. Fix: Replace =! with not equal to operator != and re-run the code. Now, It will print “Numbers are Equal“.

Q4. Find the output of the below Java program?

Try to find the output of this program-

public class FindOutputExample
{
    public static void main(String []arguments)
    {
        String website1 = "ShubhamKLogic.com";
        String website2 = "ShubhamKLogic.com";
        System.out.println("website1 == website2 :: " + website1 == website2 );
        // Output: website1 == website2 :: false
    }
}

 

Side Notes***
Here, in the System.out.print() method, we have used the Equality Operator ==, The given statement output will be β€œfalse” because, in Java, the precedence of String concatenate operator + is more than == operator.
So the given expression will be evaluated as β€œwebsite1 == website2 :: ShubhamKLogic.com” == β€œabc” that not same strings or simply false.

Q5. What would be the size of HashSet object ‘theSet’?

Finding the size of theSet HashSet object-

import java.util.HashSet;
public class SizeOfHashSetExample
{
    public static void main(String []arguments)
    {
        HashSet theSet = new HashSet();
        for (short i = 0; i < 100; i++) {
            theSet.add(i);               // Adding the current number
            theSet.remove(i - 1);   // Removing the previous number
        }
        System.out.println( theSet.size() );
    }
}

 

Notes For You***
In the above Java code, a number of Java features have been implemented (like- Autoboxing, Collection API etc). By the way, if you’re thinking that the size of theSet would be 0 (zero), then you are wrong actually!
The HashSet class’ add() and remove() methods take Object as an parameter. Java will use its autoboxing feature, so when we’ll add() and pass the primitive short to HashSet<Short> theSet, Java will automatically convert it to Short type object (using autoboxing). Now β€œi-1” will be converted to an int value while calculation and after that it will autoboxed to Integer object.
But there is no Integer object in theSet, so it will not remove anything from the HashSet and finally print the size of theHash = 100.

Array-based Questions 

Practice Array Based Core Java Interview Questions
The above diagram shows the internal architecture of Array. It’s a data-structure, that does not only allow us to store data, but also provides useful methods to perform operations on them. Linked-List, Array-List, Tree are a few of other important Data structures, and Interviewers definitely ask from them.

To prepare all Data-structure related topics, you should check Data Structures in Java – Part I on Udemy where Balazs explained each and every concept in detail. And, to develop and build projects based on Java with Data structure, you must check the Practice Java by Building Projects course on Udemy, where Tim taught all the Object Oriented Programming principles with Java and developed 3 dynamic apps from scratch.

Q6. How to remove Whitespaces from String using char Array?

To solve this question, we have to check for each character and remove it from the String-

package com.shubhamklogic.java.interview.questions;

public class RemoveWhiteSpacesExample
{
    public static void main(String []arguments)
    {
        System.out.println(whiteSpaceRemover( "ShubhamKLogic .com" ));
        System.out.println(whiteSpaceRemover( "Learn Programming With ShubhamKLogic.com" ));
    }

    // Method- responsible for removing white spaces...
    public static String whiteSpaceRemover( String theString )
    {
        StringBuilder theResult = new StringBuilder();
        
        char[] charArray = theString.toCharArray();      // Creating a char array.
        
        for(char c : charArray) {
            if (!Character.isWhitespace(c))     // Checking- if 'c' contains a whitespace or not!
                theResult.append(c);                  // If not, then append that character in result.
        }
        
        return theResult.toString();
    }
}

/*         -: OUTPUT :-
      ShubhamKLogic.com
      LearnProgrammingWithShubhamKLogic.com
*/

 

Notes For You***
Here is one possible solution to this question. You can make use of StringBuilder and Character utility classes-
The Character class’ static method isWhiteSpace() takes a character and returns true if that character is whitespace otherwise it returns false.

Q7. How to Sort an array in Java?

It’s mostly asked Core Java Interview Questions, which is also asked with different criterias using with or without. But, let’s see the fundamental solution-

package com.shubhamklogic.java.interview.questions;

import java.util.Arrays;

public class SortArrayExample {

    public static void main(String[] arguments) {

        int[] array = { 10, 30, 20, -11, -22, 44 }; // Creating an unsorted array

        Arrays.sort(array); // Sorting array- using utility class Arrays.sort() method,

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

/*          -: OUTPUT :-
     [-22, -11, 10, 20, 30, 44]
*/

 

Notes For You***
If you are aware of the Arrays utility class, there are many overloaded sort() methods to sort objects as well as primitive arrays.

BTW, there are few popular Sorting algorithms as well, such as Bubble sort, Quick sort etc. You can Learn these Java Algorithms below.

Q8. How will you find Smallest and Largest Element in an Array?

Here’s an easy solution to find Smallest and Largest Element in an Array-

package com.shubhamklogic.java.interview.questions;

public class PA1Example {

    public static void main(String[] args) {

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

        int theSmallest = arr[0];                               // Step 1 : First element will be treated as the largest and smallest number (initially)
        int theLargest = arr[0];

        for (int i = 1; i < arr.length; i++) {                 // Step 2

            if (arr[i] > theLargest)                               // Step 3
                theLargest = arr[i];
            else if (arr[i] < theSmallest)                    // Step 4
                theSmallest = arr[i];

        }
        System.out.println("Smallest : " + theSmallest);            // Finally...
        System.out.println("Largest : " + theLargest);

    }
}

//  -: Output :-
     Smallest : 10
     Largest : 180

 

Notes For You***
Here is the Step-by-Step explaination of above Java Program:
Step 1– Firstly, Initialise two variable- theLargest and theSmallest with the first element of array : arr[0]
Step 2– Iterate over array
Step 3– If current element is greater than theLargest, then assign current element to theLargest.
Step 4– If current element is smaller than theSmallest, then assign current element to theSmallest.
Finally– You will get smallest and largest element.

Q9. How to convert Java String into byte[]?

Here’s the easiest method to get a byte array from a String-

package com.shubhamklogic.java.interview.questions;

import java.util.Arrays;
import java.nio.charset.*;

public class StringToByteArraySolution {

    public static void main(String[] args) {

        String string = "ShubhamKLogic";
        byte[] bytes = string.getBytes();
        System.out.println("\nBytes( Simple Print)  = " + Arrays.toString(bytes));

        bytes = string.getBytes(Charset.forName("UTF-8"));
        System.out.println("\nBytes(Charset UTF-8)  = " + Arrays.toString(bytes));

        bytes = string.getBytes(StandardCharsets.UTF_8);                                                 // Platform Independent and Java 7+ only 
        System.out.println("\nBytes(Standerd UTF-8) = " + Arrays.toString(bytes));
    }
}

/*        -: Output :-

Bytes( Simple Print)  = [83, 104, 117, 98, 104, 97, 109, 75, 76, 111, 103, 105, 99]
Bytes(UTF-8)          = [83, 104, 117, 98, 104, 97, 109, 75, 76, 111, 103, 105, 99]
Bytes(Standerd UTF-8) = [83, 104, 117, 98, 104, 97, 109, 75, 76, 111, 103, 105, 99]     */

 

Notes For You***
In the above solution, If you’ve noticed, then you know that the bytes array contained
the US-ASCII values of each character ( A=65, B=66…, a=97, b=98…)
Beware: The string.getBytes() method is Platform Dependent method,
To make it more robust, choose string.getBytes(StandardCharsets.UTF_8) for getting
bytes array

Q10. How many ways do you know to print a Java array?

First of all, It’s not a Java Interview Question, But I’ve added this question here, so that you can get to know all the different ways of print an array in one place.
Here’re a few of the easiest methods to print a 1-d and 2-d arrays:

package com.shubhamklogic.java.interview.questions;
import java.util.*;
import java.util.stream.*;

public class ArrayPrintingWays {

    public static void main(String[] args) {

        // Method 1: A Simple Array:
        String[] array = new String[] {
            "John",
            "Shubham",
            "Bob"
        };
        System.out.println("\n\nMethod 1) Array = " + Arrays.toString(array));


        // Method 2: A Nested Array:
        String[][] nestedArray = new String[][] {
            {
                "John",
                "Shubham"
            }, {
                "SKL",
                "Alex"
            }
        };

        // System.out.println(Arrays.toString(deepArray));      
        // This would NOT work! It will print just Memory Address
        // Output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]

        System.out.println("\n\nMethod 2) NestedArray = " + Arrays.deepToString(nestedArray));


        // Method 3: Using Java Lambda Expression:
        System.out.print("\n\nMethod 3) Array = ");
        Arrays.asList(array).stream().forEach(
            element - > System.out.print(element + " ")
        );


        // Method 4: Using Java Stream API:
        System.out.println("\n\nMethod 4) Array = ");
        Stream.of(array).forEach(System.out::println);

    }
}

/*        -: Output :-
Method 1) Array = [John, Shubham, Bob]

Method 2) NestedArray = [[John, Shubham], [SKL, Alex]]

Method 3) Array = John  Shubham  Bob

Method 4) Array =
                       John
                       Shubham
                       Bob
*/

 

Beware: Please note, The Method-3 and Method-4 to print Java Array uses the Java Lambda expression and stream API, If you’re using Java 7 or its previous version, you could not use those methods, as Lambda Expressions and Stream API are available from Java 8.

Q11. How to Implement Binary search of an array?

Binary Search in an important Java Interview Question. To search an element using binary search, the array elements must be in sorted order. Here’s the complete implementation of Binary Search in Java-

package com.shubhamklogic.java.interview.questions;

import java.util.*;

public class BinarySearchExample
{
	public static void main( String []args)
	{	      
                      // INDEX =     0    1    2    3   4    5   6
		int []theArray = { 10,70,40,50,70,80,90 };        // a sorted array...
		int theNumber = 70;                                          // the number to find...
		
		System.out.println( "Array : "+ Arrays.toString( theArray ) );
		
		int foundAt = binarySearch( theArray, 0, theArray.length-1, theNumber);
		
		if( foundAt < 0 )
			System.out.println( "Num "+ theNumber + " --> Not Found" );
		else
			System.out.println("Num "+ theNumber + " --> Found at index = "+ foundAt);
    }

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

        while (low <= high) 
        {
            if (arr[mid] < target)                                             // The 1st Case...
                low = mid + 1;
            else if (arr[mid] == target)                                  // The 2nd Case...
                return mid;
            else                                                                           // The 3rd Case...
                high = mid - 1;
            
            mid = (low + high) / 2;
        }
        if (low > high)                                                             // Final Case
        {
            return -1;
        }
        return -1;
    }
}
/*         -: OUTPUT :-
    Array : [10, 30, 40, 50, 70, 80, 90]
    Num 70 --> Found at index = 4
*/
Side Notes ***

The Binary Search works on 4 different cases in order to find an element from a sorted array.

First Case: In binary search, if the target is less than the middle element, then we need to search only in the first half section of the whole array.
Second Case: If the target is greater than the middle element, then we need to only search in the second half section of the array.
Third Case: And if the target is exactly equal to the middle element in the array, then the binary search ends and returns its index in the array.
Final Case: The last case is, if the target element was not found in the whole array, then the method should return -1 (negative value). It indicates- the element is not present in the array.

String-based Questions 

Q12. How to reverse a String in Java?

It might be a little surprising, but the Java String class doesn’t have any particular reverse() method to reverse a String. Here is a complete program to reverse a String in Java-

package com.shubhamklogic.java.interview.questions;

public class StringReverseExample
{
    public static void main(String[] args) 
    {
		String theString = "ABCDEFG";
		System.out.println( theString + " <---> " + reverse(theString) );
    }

    public static String reverse(String theString) 
    {
        try{                                                                         // Checking for a valid input String...
            if (theString == null)
                throw new Exception("Invalid input");
        }catch( Exception e ){
            System.out.println(e.getMessage());
            return null;
        }

        StringBuilder reversedString = new StringBuilder();

	char[] chars = theString.toCharArray();        // Creating a char array to store string's characters...

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

	return reversedString.toString();
    }
}
/*                -: OUTPUT :-
     ABCDEFG <----> GFEDCBA
*/

 

Notes For You***
Added a try-catch block to check if the String is valid or contains a null value.

Q13. What is the output of the given Java code?

Here is a Java program, in which you have to tell- the output of the program:

package com.shubhamklogic.java.interview.questions;

public class GuessTheOutputSeries
{
    public static void main(String[] args) {
        foo(null);                                            // calling method foo()
    }
    public static void foo(Object o) {      // foo( takes Object )
        System.out.println("The Object method");
    }
    public static void foo(String s) {      // foo( takes String object )
        System.out.println("The String method");
    }
}
/*     -: OUTPUT :-
    The String method
*/
Notes For You***
The above Java interview coding solution would print “String method” as the most specific overloaded method would get executed.
First of all, null is not treated as an object in Java. But we know that any object reference type can contain null in Java.
Java String is an object of the class java.lang.String. Here, Java chooses to call the overloaded method with the most specific parameters, that would be String because the String class is more specific than it’s super class- The Object class.

Q14. How many String objects are created by the below code?

It’s one of the tricky Core Java Interview Questions that confuse even experienced developers as well. Have a look at the Java code below, and try to find- How many String objects are created here.

package com.shubhamklogic.java.interview.questions;

public class CountObjectsExample
{
    public static void main(String[] args)
	{
		String s = new String("ShubhamKLogic (dot) com");
	}
}

 

Notes For You***
The answer is- Two Strings.  When you’ll execute the above Java code, 2 objects of java.lang.String type will be created.
It’s because, when the new operator is used to create a String object, if that object doesn’t present in the Java String Pool, it will first be created in the pool, and then again in the Heap memory area as well.

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

Here is a possible solution to this Core Java Interview Question (using something known as Regex / RegExp or) Regular Expression.

package com.shubhamklogic.java.interview.questions;

public class VowelCheckExample
{
       public static void main(String[] args) 
       {
		System.out.println( checkForVowels("ShubhamKLogic") );  
		System.out.println( checkForVowels("SKL") );
                System.out.println( checkForVowels("Java") );
	}
	public static boolean checkForVowels(String message) 
       {
        String vowelCheckerRegex = ".*[aeiou].*";
        return message.toLowerCase().matches( vowelCheckerRegex );
	}
}
/*  -: OUTPUT :-
             true
             false
             true          */

 

Notes For You***
Regex plays an important role String#split() method as well which is used for splitting a String by any literal or special character. Here’s a complete tutorial of Top 5 use cases of split() method in Java.

Q16. Write a Java program to Defang an (IPv4) IP Address.

A defanged version of an IP address replaces every period or dot “.” with “[.]”
Let’s say, you have an input IP address = “1.1.1.1” then output should be = “1[.]1[.]1[.]1”
Here’s a solution for this interview question-

package com.shubhamklogic.java.interview.questions;

public class IPAddressDefangingExample
{
    public static void main(String[] args) 
    {
        String ip = "255.255.255.1";
        ip=ip.replace(".","[.]");
        System.out.println( ip );
    }
}
/*     -: OUTPUT :-
    255[.]255[.]255[.]1
*/

 

Notes For You***
You can use the String#replace() method to solve this question.

Q17. How to convert a String into small letters without using string.toLowerCase()?

You can convert any String into small letters of English alphabet by implementing the below convertIntoLowerCase() method-

package com.shubhamklogic.java.interview.questions;

public class CustomLowerCaseExample
{
    public static void main(String[] args) 
    {
        System.out.println( convertIntoLowerCase("ShubhamKLogic.com") );
        System.out.println( convertIntoLowerCase("Learn To Code...") );
        System.out.println( convertIntoLowerCase("PROGRAMMING...") );
    }
    public static String convertIntoLowerCase(String theString) 
    {
        char[] arr = theString.toCharArray();
        for (int i = 0; i < arr.length; i++)
            if ('A' <= arr[i] && arr[i] <= 'Z')         // If the character is within the range of A - Z
                arr[i] = (char) (arr[i] - 'A' + 'a');   // Replace that character with it's small letter
        return new String(arr);
    }
}
/*     -: OUTPUT :-
    shubhamklogic.com
    learn to code...
    programming...
*/

 

Notes For You***
Check the comments that are put in the above code to understand what is happening in this code-

Q18. Write a Java Program to Find Roman numbers of Given Integers?

It’s also one of the Tricky Java Interview Questions asked by different companies.

package com.shubhamklogic.java.interview.questions;

public class RomanNumberToIntegerExample
{
    public static void main(String[] args) 
    {
        System.out.println( convertIntToRoman(50) );
        System.out.println( convertIntToRoman(1000) );
        System.out.println( convertIntToRoman(777) );   
    }
    public static String convertIntToRoman(int num) 
    {
        String M[] = {"", "M", "MM", "MMM"};                                                                    // Range from 1000 to 3000
        String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};          // Range from 100 to 900
        String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};      // Range from 10 to 90
        String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};                          // Range from 1 to 9
        return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10];           // Calculating & Returning Roman Numbers...
    }

}
/*  -: OUTPUT :-
           L
           M
           DCCLXXVII      */

 

Notes For You***
Here, I’ve created multiple String arrays to store some most specific roman numbers in convertIntToRoman() method. The above solution can convert Integers into Roman numbers ranging from 1 to 3000.

Q19. How do I convert a String to an int in Java?

It’s one of the most important Java Coding Interview Questions, and you’ll use its solution probably more than a thousand times. Here, I’m going to show you 2 safe and secure ways of doing this-

package com.shubhamklogic.java.interview.questions;

public class StringToInt
{
    public static void main(String[] args) 
    {
        String strNum = "4455";

        Integer x = Integer.valueOf(strNum);   // Method - 1

        int y = Integer.parseInt(strNum);      // Method - 2

        System.out.println("1st Integer x = "+ x);
        System.out.println("2nd Integer y = "+ y);
    }
}
/*          -: OUTPUT :-
       1st Integer x =  4455
      2nd Integer y =  4455        */

 

Notes For You***
There is a major difference between the Method – 1 and Method – 2
  • valueOf() method returns a new or cached instance of java.lang.Integer
  • parseInt() method returns primitive int.
    And you’ll have to use them wisely according to the return value if you want to stay away from error and bugs.

Next Q20 to Q24 are based on Splitting a String with different delimiters-

Q20. How to Split a String in Java by . (dot)?

Syntax: The String#split() method has 2 variants ( or overloaded methods) and both return 1-dimensional array of String type.

split( String regularExpression )                     // returns String [ ]
split( String regularExpression, int limit )    // returns String [ ]

 

The solution:

package com.shubhamklogic.java.interview.questions;

public class SplitStringByDotExample
{
    public static void main(String[] args) 
    {
        // String theFileNameWithExtension = "HelloPlanet.java";
        // String theFileName = theFileNameWithExtension.split(".")[0];   // Runtime Error
        // String theExtension = theFileNameWithExtension.split(".")[1];   // Runtime Error


        // The correct way to split the file name and extension...

        String theFileNameWithExtension = "HelloEarth.java";
        String theFileName = theFileNameWithExtension.split("\\.")[0];     // placed 2 backslashes \\ before the . dot
        String theExtension = theFileNameWithExtension.split("\\.")[1];

        System.out.println("File Name With Extension : "+ theFileNameWithExtension);
        System.out.println("File Name                : "+ theFileName);
        System.out.println("Extension                : "+ theExtension);
    }
}
/*  OUTPUT: 
      ------------
     File Name With Extension : HelloEarth.java
     File Name                : HelloEarth
     Extension                : java                                    */

 

Notes For You***
Warning!!! Be careful while using String#split() as it throws a runtime error (see in above code snippet).
To learn more about splitting a string by . dot, I’ve already shared A Complete Tutorial on that. So, check it.

Q21. How to split a String by | (pipe)?

Here is the solution to this problem-

package com.shubhamklogic.java.interview.questions;

import java.util.Arrays;

public class SplitByPipes {

    public static void main(String[] arguments) {

        String stringWithPipes = "12345|abcd|123numberText";
        String[] splittedParts = stringWithPipes.split("\\|");        // LITERAL pipe | symbol
        System.out.println(Arrays.toString(splittedParts));

        /*
           -: Output :- 
                12345,
                abcd,
                123numberText
        */
    }
}

 

Notes For You***
Pipe | is a special character for Java’s regular expression, so put 2 backslashes before the pipe.
To learn more about splitting a string by | pipe symbol, I’ve already shared A Complete Tutorial on it. So, check it.

Q22. How to split String in Java within a limit?

Here is the solution to this problem-

package com.shubhamklogic.java.interview.questions;

import java.util.Arrays;

public class LimitedSplitExample {

    public static void main(String[] arguments) {

        String stringPhNum = "101-2001-300003";                      // String containing dash or hyphens (-) 
        String[] fullParts = stringPhNum.split("-");                      // Splitting string by dash (-) 
        String[] onlyLimitedParts = stringPhNum.split("-", 2); // Limiting the results to split till maximum 2 values

        System.out.println("All the Parts    : " + Arrays.toString(fullParts));
        System.out.println("Limited Parts    : " + Arrays.toString(onlyLimitedParts));
    }
}
/*  -: Output :-
         All the Parts      : [101, 2001, 300003]
         Limited Parts   : [101, 2001-300003]
*/

 

Notes For You***
When we pass regex as 1st argument and limit as 2nd argument, the split() would return only a limited number of splitted parts.
To learn more about splitting a string according to the limit, I’ve already shared A Complete Tutorial on it.

Q23. How to split a string using a dash or the hyphen (–)?

Here (check your previous post)-

package com.shubhamklogic.java.interview.questions;

import java.util.Arrays;

public class SplitByHyphenExample {
    
    public static void main(String[] arguments) {
        
        String strPhoneNo = "ABC-1011-FGHI-20222";      // A string containing dash or hyphen (-)
        String[] partsPhoneNum = strPhoneNo.split("-"); // Splitting the string by - hyphen (or dash)

        System.out.println(Arrays.toString(partsPhoneNum));
    }
}
/*             -: Output :-
    [ABC, 1011, FGHI, 20222]     */

 

Notes For You***
In the above program, I’ve passed a hyphen or dash ‘‘ as a delimiter to split the String (with no limit). And you can compare its output.

Q24. How to split a string in Java using Comma (,)?

Here is how to split a string using a comma (,) as a delimiter –

package com.shubhamklogic.java.interview.questions;

import java.util.Arrays;

public class SecondSplitExample
{
    public static void main( String[] arguments)
    {
        String allBooks = "Java,Data structure,C++,Python";         // A string containing comma (,) 
        String[] theArrayOfBooks = allBooks.split(",");             // Splitting the string by , comma
        System.out.println(Arrays.toString( theArrayOfBooks ));
    }
}
/*          -: Output :-
Index: 0       1           2        3              4
    [Java, Data structure, C++, Python]
*/

 

Notes For You***
There is no need to put double backslashes before the comma (,) as its’ not a meta-character in Java Regex Domain.

Q25. How to Remove Leading and Trailing whitespaces from a String?

Here is how you can remove those whitespace in Java-

package com.shubhamklogic.java.interview.questions;

public class RemoveWhitespacesProgram {

    public static void main(String[] arguments) {

        String websiteName = "  ShubhamKLogic    com  \t";
        websiteName = websiteName.trim();                          // Prints: "ShubhamKLogic    com"
        System.out.println(websiteName);
    }
}

 

Notes For You***
The above solution will only remove the leading and trailing whitespaces not the inner whitespaces.

Q26. How to remove all occurrences of a given Character from a String?

You might be surprised after knowing that, the java.lang.String class doesn’t have any direct method to remove a particular character from it. Here is a possible solution to achieving it-

package com.shubhamklogic.java.interview.questions;

public class RemoveCharOccuranceExmple{

    public static void main( String[] arguments){

        String websiteForCoders = "ShubhamKLogic.com";
		
        websiteForCoders = websiteForCoders.replace("o", "");    // Removing 'o' from string

        System.out.println( websiteForCoders );

    }
}

/*  -: Output :-
    ShubhamKLgic.com  */

 

Notes For You***
In above solution, we’ve used the replace() method, which has 3 variants:
– public String replace(char oldChar, char newChar)
– public String replaceAll(String regularExpression, String replaceString)
– public String replaceFirst(String replaceString, String replaceString) // Only first occurrence…

Q27. How to get unique characters and their count in a String?

Here is a possible solution by using HashMap Data Structure.
In Java Collection API, there is a class HashMap, which doesn’t accept duplicate objects (in this case- Character objects), and we will take advantage of it.

package com.shubhamklogic.java.interview.questions;

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

public class GetUniqueCharExample {

    public static void main(String[] arguments) {

        String msg = "GoodJavaProgramming";

        char[] allChars = msg.toCharArray();

        Map < Character, Integer > charCounterMap = new HashMap < > ();

        for (char c: allChars) {

            if (charCounterMap.containsKey(c))
                charCounterMap.put(c, charCounterMap.get(c) + 1);

            else
                charCounterMap.put(c, 1);

        }

        System.out.println("All Unique Characters of \"" + msg + "\": " + charCounterMap);

    }
}

/*                          -: Output :-
All Unique Characters of "GoodJavaProgramming":
{P=1, a=3, r=2, d=1, v=1, G=1, g=2, i=1, J=1, m=2, n=1, o=3}       */

 

Notes For You***

Here is the explaination of above code-
– Create the character array from the string,
– Then iterate over the array and create a HashMap#put() method,
– Make sure each character would be passed as a key and their count as value,
– If that character will already exist, control will go inside the “if block”,
– Else, if that character occurred for the first time, the control will go inside the “else block”,
– At the end, just print the calculated Map.

Q28. How to check if a String is Numeric in Java?

We can solve this Java Programming Interview Question by using Wrapper Class method – parseXXYYZZ(). In this method, just replace ‘XXYYZZ‘ with Int, Float or Double. Here is a Complete soution of it:

package com.shubhamklogic.java.interview.questions;

public class CheckNumericExample {

    public static void main(String[] arguments) {

        String age1 = "22";
        String age2 = "22 years";

        if (isNumeric(age1))
            System.out.println("age1 is Numeric");          // if block will EXECUTE...
        else
            System.out.println("age1 is NOT Numeric");

        if (isNumeric(age2))
            System.out.println("age2 is Numeric");
        else
            System.out.println("age2 is NOT Numeric"); // else block will EXECUTE...

    }
    public static boolean isNumeric(String str) {

        try {
            Double.parseDouble(str);                                  // Checking for Number, If successfully parsed, return true...
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}

/*        -: Output :-
        age1 is Numeric
        age2 is NOT Numeric         */

 

Notes For You***
However, you can use the Java Regular Expressions in java.lang.String matches() method, for eg:
string.matches(“-?\\d+(\\.\\d+)?”); This RegEx will match a Number with optional ‘-‘ and decimal.
Beware, when using regEx, as Regular Expressions would not work for Hexadecimal Numbers.

Q29. How to convert a Java string into a Date object?

Suppoach you have a date as string in “MMMM DD YYYY” format and you want complete information about that particular date, here is a possible solution for this Java Interview Question-

package com.shubhamklogic.java.interview.questions;

import java.util.Date;
import java.util.Locale;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class ConvertStringToDate {

    public static void main(String[] arguments) throws ParseException {

        String birthdayStr = "March 27, 1997";
        DateFormat theFormat = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);

        Date date = theFormat.parse(birthdayStr);
        System.out.println("\"" + birthdayStr + "\" Converted into ==> \n" + date);
    }
}

/*        -: Output :-
"March 27, 1997" Converted into ==>
Thu Mar 27 00:00:00 IST 1997            */

 

Notes For You***
We have used Date, Locale, DateFormat and SimpleDateFormat classes that are available from Java 8.
Beware when using the parse() method, as it throws an exception “ParseException“. Make sure you handle it properly (BTW, In above solution, I’ve left it over to Java).

Q30. How to remove last character of String without replace() method?

It’s a basic level Java Interview Question, and you might already know how to solve it. Here is a possible solution-

package com.shubhamklogic.java.interview.questions;

public class RemoveLastCharExample {

    public static void main(String[] arguments) {

        String siteWithExtraDot = "Java <=> ShubhamKLogic.com.";

        siteWithExtraDot = removeLastChar(siteWithExtraDot);

        System.out.println(siteWithExtraDot);
    }

    public static String removeLastChar(String str) {

        if (str == null || str.length() == 0) {
            return str;
        }
        return str.substring(0, str.length() - 1);

    }
}

/*        -: Output :-
Java <=> ShubhamKLogic.com        */

 

Notes For You***
Make sure, you don’t forget to check for null value (otherwise you’ll face a NullPointerException).
In the above code snippet, If you’ll try with replace(“.” , “”) it will replace all instances of the . dot

Q31. How to capitalize first character of each word in String?

At first look, such Core Java Interview Questions may seem too easy, but It’s NOT.
There are so many test cases tied with this question, and you will have to pay attention a bit more deeply on all of them. BTW, there’s no direct method provided by Java Team to solve such questions, but no worry, here’s an efficient solution, that works absolutely fine for almost all of the cases.

package com.shubhamklogic.java.interview.questions;

public class CapitalizeRequiredWordsSolution {

    public static void main(String[] arguments) {

        String[] messages = { // Sample sentences...

            // Test Case 1: A SIMPLE USAGE
            "cApItAlIzE my string after WHITE SPACES",

            // Test Case 2: WITH CUSTOM-DELIMITER USAGE
            "capitalize my string AFTER SPACES, BEFORE'APEX, and #AFTER AND BEFORE# NUMBER SIGN (#)",

            // Test Case 3: WITH MULTIPLE CUSTOM-DELIMITER
            "capitalize my string ONLY before'and''after'''APEX"

            // (SKIPPING REST OF THE CASES UPTO YOU...)
        };

        for (int i = 0; i < messages.length; i++) {
            String capitalizedMsg = capitalizeAllWords(messages[i]); // Calling custom build method...
            System.out.println("Before==>\"" + messages[i] + "\"");
            System.out.println("After ==>\"" + capitalizedMsg + "\"");
        }
    }
    public static String capitalizeAllWords(String giantString) {

        char[] allChars = giantString.toLowerCase().toCharArray(); // Point 1
        boolean found = false;

        for (int i = 0; i < allChars.length; i++) {                                      // Point 2

            if ( !found && Character.isLetter(allChars[i]) ) {                    // Point 3

                allChars[i] = Character.toUpperCase(allChars[i]);
                found = true;

            } else if (Character.isWhitespace(allChars[i]) || allChars[i] == '.' || allChars[i] == '\'') { // You can add any other Separator or Character here...
                found = false;
            }
        }
        return giantString.valueOf(allChars);                                            // Final Point
    }
}

/*                -: Output :-
Before==>"cApItAlIzE my string after WHITE SPACES"
After ==>"Capitalize My String After White Spaces"

Before==>"capitalize my string AFTER SPACES, BEFORE'APEX, and #AFTER AND BEFORE# NUMBER SIGN (#)"
After ==>"Capitalize My String After Spaces, Before'Apex, And #After And Before# Number Sign (#)"

Before==>"capitalize my string ONLY before'and''after'''APEX"
After ==>"Capitalize My String Only Before'And''After'''Apex"               */

 

Notes For You***
Check out below points in above code snippet-
Point 1 : Converting into char[] array
Point 2 : Traverse each character of the sentence
Point 3 : If delimiters not found and the current char is a letter [a-z or A-Z]
Final Point : Return the Calculated String.
In the above solution, I’ve used 3 methods of Character class: isLetter(), isWhitespace() and toUpperCase() and their names are Self Explaining- What they do?

Q32. How to check if two Strings are Anagrams in Java?

By the way, If you are unaware of the term Anagram, here is that-
Anagrams mean- Two Strings having the same characters in a different order.
Few Example: “Listen” = “Silent”
“The eyes” = “They see”
Here’s the easiest way to check if two Strings are Anagrams or not-

package com.shubhamklogic.java.interview.questions;

public class AnagramSolution {

    public static void main(String[] args) {

        String word1 = "shubhamklogic.com";
        String word2 = "com.logicShubhamk";

        System.out.println(word1 + " AND " + word2 + " ARE ANAGRAMS ? :: " + isAnagram(word1, word2));

    }

    public static boolean isAnagram(String word1, String word2) {

        if (word1.length() != word2.length())
            return false;

        for (int i = 0; i < word1.length(); i++) {

            char ch1 = word1.toLowerCase().charAt(i);
            int index = word2.toLowerCase().indexOf(ch1);

            // If index of any character is -1, then the two given strings are not anagrams
            // If index of character is not equal to -1, then remove the chacter from the
            // String and check till the end...

            if (index != -1) {
                word2 = word2.substring(0, index) +
                    word2.substring(index + 1, word2.length());
            } else
                return false;
        }
        return word2.isEmpty();
    }
}

/*                    -: Output :-
    shubhamklogic.com AND com.logicshubhamk ARE ANAGRAMS ? :: true    */

 

Notes For You***
It simple to check if two strings are anagram or not-
If the index of any character is -1, then the two given strings are not anagrams,
If the index of character is not equal to -1, then remove the character from the
The above solution is a Case In-Sensitive solution, which means- for above Java code, “ShubhamKLogic.com” and “shubhamklogic.com” are Anagrams, as it doesn’t care about Capital or Small letter.

Q33. How will you find all substrings of a String?

Here’s the easiest method to list down all substrings of a String-

package com.shubhamklogic.java.interview.questions;

public class AllSubstringSolution {

    public static void main(String[] args) {

        String word = "SKL";
        System.out.println("All possible substrings of word SKL are: ");

        for (int i = 0; i < word.length(); i++) {

            for (int j = i + 1; j <= word.length(); j++) {
                System.out.println(word.substring(i, j));

            }
        }
    }
}

/*        -: Output :-
All possible substrings of word SKL are: 
S
SK
SKL
K
KL
L
*/

 


Collection-based Questions 

Q34. How to remove duplicates from ArrayList in Java?

It’s one of the most Important Core Java Interview based on Collections API, and a number of Java Developers face trouble when solving it. Here is it’s one liner solution-

package com.shubhamklogic.java.interview.questions;
import java.util.*;
public class RemoveDuplicatesSolution {

    public static void main(String[] arguments) {

        List < String > list = new ArrayList < String > ();
        list.add("Practice");
        list.add("Java Interview");
        list.add("Java Interview");
        list.add("@ShubhamKLogic.com");
        list.add("@ShubhamKLogic.com");
        list.add("@ShubhamKLogic.com");

        System.out.println("========= With Duplicate Element =======\n");
        System.out.println(list);

        list = new ArrayList < String > (new LinkedHashSet < String > (list));              // One line Solution...

        System.out.println("=========== Without Duplicates ===========\n");
        System.out.println(list);
    }
}

/*        -: Output :-

========= With Duplicate Element =======

[Practice, Java Interview, Java Interview, @ShubhamKLogic.com, @ShubhamKLogic.com, @ShubhamKLogic.com]

=========== Without Duplicates ===========

[Practice, Java Interview, @ShubhamKLogic.com]          */

 

Notes For You***
In above solution I’ve used the LinkedHashSet class, which is an ordered version of HashSet that maintains a doubly-linked List across all elements.

Q35. How to Revese a Linked List?

Here’s again a one-liner solution to reverse any linked list:

package com.shubhamklogic.java.interview.questions;

class Node                                                             // Creating a class for nodes of Linked List...
{
    int data;
    Node next;

    Node(int data, Node next) {
        this.data = data;
        this.next = next;
    }
}

public class ReverseLinkedListSolution {

    public static void printList(Node head) // Helper method to print nodes' values of given linked list
    {
        Node ptr = head;
        while (ptr != null) {
            System.out.println(ptr.data + " -> ");
            ptr = ptr.next;
        }

        System.out.println("null");
    }

    public static Node reverse(Node head) // Reverse method for List
    {
        Node prev = null;
        Node current = head;


        while (current != null)                            // Traversing the list
        {

            Node next = current.next;                   // Focus: store the next node

            current.next = prev;                             // Manage the current node

            prev = current;
            current = next;
        }
        return prev;                                              // Fixing the head to point to the new front
    }

    public static void main(String[] args) // Iterative method to reverse a linked list
    {
        int[] keys = { 1,  2, 3, 4, 5, 6 }; // Input keys

        Node head = null;
        for (int i = keys.length - 1; i >= 0; i--) {
            head = new Node(keys[i], head);
        }
        System.out.println("\n===== Before =====");
        printList(head);
        head = reverse(head);
        System.out.println("\n===== After ======");
        printList(head);
    }
}

/*    -: OUTPUT :-

===== Before =====
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null

===== After ======
6 -> 5 -> 4 -> 3 -> 2 -> 1 -> null
*/

 

Q36. How to merge two lists in Java?

Here is a possible solution of this Java Interview Questions-

package com.shubhamklogic.java.interview.questions;

import java.util.*;
public class MergeListsSolution {

    public static void main(String[] arguments) {

        List < String > listA = new ArrayList < > ();
        listA.add("10");
        listA.add("20");
        List < String > listB = new ArrayList < > ();
        listB.add("40");

        List < String > mergedList = new ArrayList < > (listA);
        mergedList.addAll(listB);
        System.out.println(mergedList);
    }

}

/*   -: Output :-
    [10, 20, 40]
*/

 

Q37. How to Sort HashMap by values?

It’s also, one of the mostly asked Core Java Interview Questions. Here is one of its possible solution using Java LinkedHashMap class-

package com.shubhamklogic.java.interview.questions;

import java.util.*;

public class SortHashMapSolution {

    public static void main(String[] arguments) {

        Map < String, Integer > persons = new HashMap < > ();

        persons.put("David", 95);
        persons.put("SKL", 22);
        persons.put("Mary", 97);
        persons.put("Lisa", 78);
        persons.put("Dino", 65);

        System.out.println("====== BEFORE: UnSorted ======");
        System.out.println(persons);

        persons = sortMapByValue(persons);

        System.out.println("====== AFTER : Sorted =======");
        System.out.println(persons);
    }

    private static Map < String, Integer > sortMapByValue(Map < String, Integer > persons) {

        Map < String, Integer > sortedMapByValue = new LinkedHashMap < > ();

        // Getting the Map.EntrySet object...
        Set < Map.Entry < String, Integer >> entrySet = persons.entrySet();

        // Creating the List of Map.EntrySet
        List < Map.Entry < String, Integer >> entryList = new ArrayList < > (entrySet);

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

        // Populating the map with sorted values
        for (Map.Entry < String, Integer > e: entryList)
            sortedMapByValue.put(e.getKey(), e.getValue());

        return sortedMapByValue;
    }

}

/*                 -: Output :-

====== BEFORE: UnSorted ======
{SKL=22, Dino=65, David=95, Mary=97, Lisa=78}

====== AFTER : Sorted =======
{SKL=22, Dino=65, Lisa=78, David=95, Mary=97}		*/

 

Notes For You***
You might already know, HashMap does not store elements in an ordered manner.
But, we can sort the lists’ entries based on it’s value- by storing into a Java Class- LinkedHashMap.

Remember-

  • The LinkedHashMap object maintains the order of inserted elements and we can use it in this scenario.
  • Map.Entry is an interface, which is defined inside the body of Map class.

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

To solve this question, we can take advantage of Map class in Java Collections. Here is its solution-

package com.shubhamklogic.java.interview.questions;

import java.util.*;

public class DistinctCharAndCountSolution {

    public static void main(String[] arguments) {

        String string = "ShubhamKLogic.com.com.SKL";

        char[] allChars = string.toCharArray();

        Map < Character, Integer > charsCount = new HashMap < > ();

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

        System.out.println("====== Count of Individual Characters ======");
        System.out.println(charsCount);

    }
}

/*                           -: Output :-
====== Count of Individual Characters ======
{a=1, b=1, c=3, g=1, h=2, i=1, K=2, L=2, m=3, .=3, o=3, S=2, u=1}  */

 

Notes For You***
The java.util.HashMap#containsKey() method is used for verifying whether a particular key is being mapped into the HashMap or not.
It accepts the key element as a parameter and returns true if that element is mapped in the map.

Multi Threading-based Questions 

Q39. How to print odd-even numbers using threads in Java?

It’s one of the important Core Java Interview Questions for Experienced developers as well. In this problem, You are given two threads and you need to print odd numbers using one thread while even numbers using another thread.
You need to print odd-even numbers in natural order up to MAX_VALUE.

package com.shubhamklogic.java.interview.questions;

public class OddEvenWithThread {

    boolean odd;
    int count = 1;
    int MAX_VALUE = 10;

    public void printOdd() {

        synchronized(this) {

            while (count < MAX_VALUE) {

                while (!odd) {

                    try {

                        wait();

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.println("Odd Thread :" + count);

                count++;
                odd = false;
                notify();                                           // Notifying the other thread...I'm done!
            }
        }
    }

    public void printEven() {

        try {

            Thread.sleep(1000);

        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        synchronized(this) {

            while (count < MAX_VALUE) {

                while (odd) {

                    try {

                        wait();

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }

                System.out.println("Even thread :" + count);

                count++;
                odd = true;
                notify();                                          // Notifying the other thread...I'm done!
            }
        }
    }

    public static void main(String[] args) {

        OddEvenWithThread oep = new OddEvenWithThread(); // Creating the Object
        oep.odd = true;

        Thread td1 = new Thread(new Runnable() { // Creating 1st thread

            @Override
            public void run() {
                oep.printEven();
            }
        });

        Thread td2 = new Thread(new Runnable() { // Creating 2nd thread

            @Override
            public void run() {
                oep.printOdd();
            }
        });

        td1.start(); // 1st thread is ready to run()
        td2.start(); // 2nd thread is ready to run()

        try {

            td1.join();
            td2.join();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
/*  -: Output :-

Odd Thread : 1
Even thread :2
Odd Thread : 3
Even thread :4
Odd Thread : 5
Even thread :6
Odd Thread : 7
Even thread :8
Odd Thread : 9
Even thread :10
*/

 

Notes For You***
In above Thread-based solution, I’ve used join() method in the main(). It causes the currently running threads to stop executing until the thread it joins with completes its task.

Learn Multi-Threading for Core Java Interview Questions

Q40. How do you kill a Thread in Java?

You may be surprised after knowing, Java threads can not be killed explicitly, but the stopping of a thread is done in an indirect and cooperative way.
The thread is asked to stop their remaining execution and the thread can then shutdown gracefully.
However, a volatile boolean field is used, and the thread periodically checks and terminates when it’s updated with the corresponding value. Here is the solution of terminating a thread whenever desired:

public void run() {
    try {
        while (!interrupted()) {
            // ...
        }
    } catch (InterruptedException exception)
    /* Exit code for thread */
}
}

public void cancel() {
    interrupt();
}

 

Notes For You***
One thing that you should take of is, if your code becomes more complex, you should avoid using a boolean to check whether the thread should terminate or not.
If you use volatile resource as a field modifier, that will be more reliable for sure.
Another more efficient solution can be using a while loop for killing a Thread in Java.
One thing that you should be aware of is, Each thread has already a boolean flag interrupted status and you can definitely use it via a method.

Q41. How to pass a parameter to a Java Thread?

It is possible to pass a parameter to a Java Thread and for doing so, you can pass the parameter in the constructor of the Runnable object. Here is the solution for you-

public class TheRunnable implements Runnable {

    public TheRunnable(Object theParameter) {       // Thread's Constructor with parameters...
           // Use the parameter...
    }

    public void run() {}
}

// and invoke it thus:

Runnable r1 = new TheRunnable(yourParameter);  // passed the parameter in thread 'r1'

new Thread(r).start();

 


Pattern-based Questions 

Q42. How to create Floyd Triangle Pattern in Java?

It’s a Star-Pattern based problem and mostly asked Core Java Interview Questions for Freshers. Floyd Triangle Pattern is one of the common Pattern problems, and here’s its simplest solution-

/*  Floyd Triangle Pattern:

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

*/

package com.shubhamklogic.java.interview.questions;

public class FloydTriangleSolution {

    public static void main(String[] arguments) {

        printFloyydTrianglePattern();

    }
    public static void printFloyydTrianglePattern() {

        int k = 1;
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= 9; j++) {

                if (j % 2 != 0 && j < i * 2)
                    System.out.print(k++);
                else
                    System.out.print(" ");
            }
            System.out.print("\n");                                         // Put a new line when required numbers are print in each row...
        }
    }
}

 

Q43. Write a program to print the below pattern?

Here is the solution of it-

/*     Pattern:

        ABCDEFG
        ABC EFG
        AB   FG
        A     G
*/
package com.shubhamklogic.java.interview.questions;

public class PatternSolution {

    public static void main(String[] arguments) {

        printPattern();

    }
    public static void printPattern() {

        char k;
        for (int i = 1; i <= 4; i++) {
            k = 'A';
            for (int j = 1; j <= 7; j++) {
                if (j >= 6 - i && j <= 2 + i) {
                    System.out.print(" ");
                } else
                    System.out.print(k);
                k++;
            }
            System.out.print("\n");
        }
    }
}

 

Q44. Write a program to print the below pattern?

Here is the solution-

/* Pattern:

   1
  A B
 1 2 3
A B C D

*/

package com.shubhamklogic.java.interview.questions;

public class PatternSolution {

    public static void main(String[] arguments) {

        printPattern();
        // char ch = 49;
        // System.out.print(ch);

    }
    public static void printPattern() {

        int k = 0;
        for (int i = 1; i <= 4; i++) {
            if (i % 2 == 0)
                k = 65; // 65 is the ASCII value of character 'A'
            else
                k = 49; // 49 is the ASCII value of character '1'

            for (int j = 1; j <= 7; j++) {
                if (i % 2 == 0) {
                    if (j >= 5 - i && j <= 3 + i && j % 2 != 0) {
                        System.out.print((char) k);
                        k++;
                    } else
                        System.out.print(" ");
                } else {
                    if (j >= 5 - i && j <= 3 + i && j % 2 == 0) {
                        System.out.print((char) k);
                        k++;
                    } else
                        System.out.print(" ");
                }
            }
            System.out.print("\n");
        }
    }
}

 

Q45. Write a program to print the below pattern?

Here is the solution-

/* Pattern:

    A
   CB
  FED
 JIHG
ONMLK

*/
package com.shubhamklogic.java.interview.questions;

public class PatternSolution {

    public static void main(String[] arguments) {

        printPattern();

    }
    public static void printPattern() {

        /*	Steps of Logical Implementation of this Pattern Program:

        		Pattern    Hint	Initial Value
        		     A	     1	        1			 (THEN Increment till the end of Columns to print...)
        		   CB	   23        2
        		  FED	  345	3
          		 JIHG    6789       6
        		ONMLK	 ...	       10
        */

        int k = 64, m = 0, p;                           // Initially...
        for (int i = 1; i <= 5; i++) {

            m++;
            k = k + m;
            p = k;                                                 // Get Initial Value to Print on Each Line...

            for (int j = 1; j <= 5; j++) {
                if (j >= 6 - i) {                              // Range of All Columns to print...
                    System.out.print((char) p--);
                } else
                    System.out.print(" ");
            }
            System.out.print("\n");
        }
    }
}

 

Q46. Write a program to print the below pattern?

Here is the solution of the pattern-

/* Pattern

*********
 *******
  *****
   ***
    *
*/
package com.shubhamklogic.java.interview.questions;

public class PatternSolution {

    public static void main(String[] arguments) {

        printPattern();

    }
    public static void printPattern() {
        /* Steps to Logically Implement this Pattern Program: 

                           Output
                i 	123456789	    j					j
        -------------------------------------------------------------------
        step 1	*********	1 to 9             	j >= i  &&  j <= 10-i
        step 2	 *******	       2 to 8   	        j >= i  &&  j <= 10-i
        step 3	  *****	       3 to 7	   	j >= i  &&  j <= 10-i
        step 4	   ***	      4 to 6		j >= i  &&  j <= 10-i
        step 5	     *	              5 to 5	   	j >= i  &&  j <= 10-i

        */
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= 9; j++) {

                if (j >= i && j <= 10 - i)         // Check, whether to print * or space ( )
                    System.out.print("*");
                else
                    System.out.print(" ");
            }
            System.out.print("\n");
        }
    }
}

 


Mostly Asked Java Interview Questions 

Q47. How to check Armstrong number using Java?

If you’re unaware of Armstrong numbers, Here’s what exactly Armstrong Number is-
An Armstrong number is a number that is equal to the sum of cubes of its digits.
For example: 153,
Explaination: 153 = [(1x1x1)+(5x5x5)+(3x3x3)],
Here is a Java program to check Armstrong number:

package com.shubhamklogic.java.interview.questions;

public class ArmstrongNumberSolution {

    public static void main(String[] args) {

        System.out.println(" Check: 153 is Armstrong number: " + checkArmStrongNumber(153));
        System.out.println(" Check: 200 is Armstrong number: " + checkArmStrongNumber(200));
        System.out.println(" Check: 407 is Armstrong number: " + checkArmStrongNumber(407));
    }
    public static boolean checkArmStrongNumber(int checkingNumber) {
        int sum = 0;
        int originalNumber = checkingNumber;
        while (checkingNumber != 0) {

            int remainder = checkingNumber % 10;
            sum = sum + remainder * remainder * remainder;
            checkingNumber = checkingNumber / 10;
        }
        if (originalNumber == sum) {
            return true;
        }
        return false;
    }
}
/*                      -: Output :-
 Check: 153 is Armstrong number: true
 Check: 200 is Armstrong number: false
 Check: 407 is Armstrong number: true
*/

 

Notes For You***
Few other ArmStrong Numbers are: 0, 1, 153, 370, 371, 407

Q48. Write Java program to check whether a String is a Palindrome?

If you’re unaware of Palindrome, A palindrome is a String that remains the same even after reverse.
For example: 545, 151, 34543, MADAM, POP etc. are the Palindromes.

package com.shubhamklogic.java.interview.questions;

public class PalindromeSolution {

    public static void main(String[] arguments) {

        String string1 = "MADAM";
        String string2 = "SIR";

        checkPalindrome(string1);
        checkPalindrome(string2);
    }

    public static void checkPalindrome(String string) {

        String reverse = "";
        for (int i = string.length() - 1; i >= 0; i--)
            reverse = reverse + string.charAt(i);

        if (string.equals(reverse))
            System.out.println(string + " ==> Palindrome");
        else
            System.out.println(string + " ==> Not palindrome");

    }
}
/*  =: OUTPUT :=
MADAM ==> Palindrome
SIR ==> Not palindrome
*/

 

Notes For You***
The above program is a Case-sensitive Palindrome checker ( for above solution : “Madam” is not a palindrome, while “MADAM” is a palindrome),
However, You can convert it into Case-insensitive Palindrome checker by using toLowerCase() method with charAt() method.

Q49. How to Generate a Fibonacci Series in Java?

Generating Fibonacci series is one of the mostly asked Core Java Interview Questions for Freshers. In this problem, you need to generate a list of numbers in which every next number is the calculated Number of previous two numbers.
Explaining Example:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc.
In Fibonacci series, the First two digits (0 and 1) are initiators. Next numbers will be calculated Number like this-
Num=Pre+Next
1  = 0 + 1
2  = 1 + 1
3  = 1 + 2
5  = 2 + 3

There are multiple ways to generate a Fibonacci Series, here I’m sharing an Iterative Method-

package com.shubhamklogic.java.interview.questions;

public class FibonacciSeriesSolution {

    public static void main(String[] arguments) {

        int prev = 0, next = 1;                                     // First two number of Fibonacci Series

        System.out.print(prev + " " + next);            // Print first two elements

        int range = 10;                                                 // Range of Numbers to be printed
        int calculatedNumber = 0;

        for (int i = 2; i < range; i++) {

            calculatedNumber = prev + next;
            System.out.print(" " + calculatedNumber);

            prev = next;                                                   // Update the numbers prev and next
            next = calculatedNumber;
        }
    }
}
/*
     -:OUTPUT:-
0 1 1 2 3 5 8 13 21 34
*/

 

Notes For You***
Explaining Steps of Iterative method:
Step 1– Initialise first two terms (prev and next) with 0 and 1,
Step 2– Find calculatedNumber of first two terms,
Step 3– Iterate upto the range,
Step 4– Print the calculatedNumber,
Step 5– Assign prev to next and next to calculatedNumber to go for next two terms,
Fibonacci Series generated successfully.

Q50. How to Sort an Array using Bubble Sort?

Sorting algorithms are favorite Interview Questions of Companies like- Amazon, Google, Uber, or others.
Bubble Sort is used to sort elements of an array. In this sorting algorithm, each element of the array is compared with its adjacent element. A list with N elements requires N-1 rounds or passes for complete sorting.

package com.shubhamklogic.java.interview.questions;

public class BubbleSortSolution {

    public static void main(String[] args) {

        // Un-Sorted Array...
        int[] arr = new int[] { 30, 20, 10, 70, 60, 80, 50, 40 };

        System.out.println("\n====== Before Sorting ======");
        for (int n: arr)
            System.out.print(" " + n);

        performBubbleSort(arr);                    // Bubble Sort called...

        System.out.print("\n======= After Sorting ======");
        for (int n: arr)
            System.out.print(" " + n);

        System.out.print("\n======= Already Sorted ======");
        performBubbleSort(arr);                                                     // Bubble Sort called...

    }
    public static void performBubbleSort(int[] arr) {

        int swaps = 0;
        for (int k = 1; k < arr.length; k++) {

            int flag = 0;                                                                     // Flag will check, if further sorting is necessary or not!
            for (int i = 0; i < arr.length - k; i++) {

                if (arr[i] > arr[i + 1]) {
                    int t = arr[i];                                                         // Swapping or Bubbling Up :: arr[i] with arr[i+1] ...
                    arr[i] = arr[i + 1];
                    arr[i + 1] = t;
                    flag = 1;                                                                  // Flag will tell, current run was necessary...
                    swaps++;
                }
            }
            if (flag == 0)
                break;
        }
        System.out.print("\nINFO: Swapping Done, Total swaps :: " + swaps);
        // Counter of Swappings...
    }
}

/*             -: OUTPUT :-
====== Before Sorting ======
 30 20 10 70 60 80 50 40

INFO: Swapping Done, Total swaps :: 11


======= After Sorting ======
 10 20 30 40 50 60 70 80

======= Already Sorted ======
INFO: Swapping Done, Total swaps :: 0

*/

 

Notes For You***
Let’s check the Time Complexity of Bubble Sort:
Worst case running time complexity= O(n2)
Best case running time complexity= O(n)
Average case running time complexituy= O(n2)

Q51. How to Sort an Array using Quick Sort?

It’s one of the top Core Java Interview Questions for Experienced candidates as well.
Quicksort is one of the fastest sorting algorithms that makes (n log n) comparisons in average case for sorting of an array of n elements. Quick Sort follows “Divide And Conquer” approach.
Almost all of the built-in Sorting functions provided by Programming Languages including (C++, Ruby, JavaScript, PHP etc.) internally use Quick Sort or its variant.
Here is the Complete implementation of Quick Sort:

package com.shubhamklogic.java.interview.questions;

public class QuickSortInJavaSolution {

    public static void main(String[] args) { // main() method

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

        System.out.print("\n===== Before Sorting =====");
        print(arr);

        Quicksort(arr, 0, arr.length - 1);                                              // Calling QuickSort()...

        System.out.print("\n===== After Sorting =====");
        print(arr);
    }
    public static void Quicksort(int[] arr, int start, int end) {    // QuickSort() body...

        if (start < end) {
            int pIndex = getPartitioningIndex(arr, start, end);     // Get the partitioning index
            Quicksort(arr, start, pIndex - 1);                                      // Sort the first half: from start to partition_index-1
            Quicksort(arr, pIndex + 1, end);                                      // Sort the other half: from partition_index+1 to end
        }
    }

    public static int getPartitioningIndex(int[] arr, int start, int end) {

        int pivot = arr[end];                                          // In the beginning, set the last element as pivot
        int pIndex = start;                                            // Set the first index as partitioning_index as it will adjust accordingly

        for (int i = start; i < end; i++) {
            if (arr[i] <= pivot)                                        // Checking if any element is lesser than the pivot
            {                                                                       // If true, swap the value at partitioning_index with that lesser_value
                int temp = arr[i];
                arr[i] = arr[pIndex];
                arr[pIndex] = temp;

                pIndex++;                                                // Increment... partitioning_index
            }
        }
        int temp = arr[end];                                     // At last - just swap partitioning_index value with pivot (or arr[end])
        arr[end] = arr[pIndex];
        arr[pIndex] = temp;
        return pIndex;                                             // Return partitionIndex...
    }
    public static void print(int[] arr) {
        for (int n: arr) {
            System.out.print(" " + n);
        }
    }
}

/*      -: OUTPUT :-
===== Before Sorting ===== 
30 20 40 10 80 50 60 70

===== After Sorting ======
10 20 30 40 50 60 70 80
*/

 

Notes For You***
Check out the comments in the above Quick Sort program for explanations.

What We Learned? 

Java has almost infinite number of Concepts, Features and Methods that can not be cover in just one interview Guide. Still, We understood Top 50+ core java interview questions on topics as based on Array, String, Collection API, Multi-Threading, Star-Patterns and a few tricky ones as well.

We’ll keep upgrading this ultimate list every week, so it’s recommended to bookmark this page and keep updating your Java skills with latest Java Interview Questions. Now, If you thinking to achieve Expertise in Java, you will have to enhance your skills, and here are a few Top resources on Udemy for Intermediate Java developers and Beginners to become a Master of Java –


 

 

Hope, this post helped you to enhance your Java Knowledge 1 level up. Don’t forget to share its link on social media to show what you know! Best of luck for all your future interviews. Believe in yourself, You will get success. Keep learning and Thanks for reading πŸ˜€
Do share because, Sharing is Caring …

Leave a Comment