25 Java Intermediate Level Interview Questions & Answers
Below is a list of our Java Intermediate Level interview questions. Click on any interview question to view our answer advice and answer examples. You may view 5 answer examples before our paywall loads. Afterwards, you'll be asked to upgrade to view the rest of our answers.
1. Design a Java class that demonstrates the usage of a queue in storing and displaying your data?
This question tests your understanding of Java data structure. The interviewer is trying to measure your comfort level with different data structures using Java programming. The shortest path to answer this question is to implement the use case of a queue. In this question, you will be better off if you can display all the elements you added to the queue. In other words, you are expected to give code examples using any object value of your choice.
The queue data structure can be called by importing the queue library found in java.util.Queue. In addition, to fully test our queue implementation we will use the for loop that will enable us to call the values in our queue. Our class will contain the main method to run our code. To start we will create a queue that will hold two booleans. The logic of our program is to have a queue that stores the Object boolean values and prints them thereafter. Once our queue is created we will add our elements to our data structure. This can be done using the add method. Next, we need to display our elements and a loop statement. The code used for this process is as follows:
package JavaQuestions;
import java.util.LinkedList;
import java.util.Queue;
public class QueueTest {
public static void main(String[] args) {
Queue<Boolean> myQueue= new LinkedList<>();
myQueue.add(Boolean.TRUE);
myQueue.add(Boolean.FALSE);
for(Boolean element: myQueue){
System.out.println(element);
}
}
Written by Mohamed Echout on May 7th, 2021
2. In terms of search complexity and CPU time what would be the main advantage of having your Java application data structures stored in a sorted format?
This question examines your understanding of Java CPU runtime and code optimization. Expect this question later on in the interview process. To explain, working with Java requires you to understand code optimization as the Java framework is resource-heavy. In other words, your code should be optimized in a way that your Java program will run fast and efficiently. The interviewers are testing your understanding of optimization in terms of data storage and data searching capabilities. No code will be required in this question but you can add a code example if you believe it will add value to your answer. However, answer the question in the most direct manner. To explain, use Java terms and try to give a good example of what would be the difference between a sorted vs unsorted data structure.
In computer science not only Java programming there is a high benefit of having a sorted data structure. To explain, Java provides a set of data structures that enables the programmer to create dynamically allocated data storage for your program. Having a list of choices in terms of data structure opens the door for a lot of optimization opportunities. In other words, picking the right data structure will be the difference between having a fast-running program or not. However, one of the variables that a Java programmer can control is the way a list or array is ordered. Having an order list will enable a fast search operation on your data structure. For example, if we have a Java ArrayList of numbers having an order list will enable us to find any number easily using a fast search algorithm. The main advantage of having a sorted list is the program loading time and search speed of your list.
Written by Mohamed Echout on May 7th, 2021
3. In terms of runtime performance which data structure would be better to use a LinkedList or an ArrayList?
This question examines your understanding of Java data structure implementation. Part of the Java technical interview process will be to fully comprehend your level of expertise in terms of data storage choices. To explain, developing a Java application is more than creating a set of classes and methods that perform certain tasks. This is demonstrated by the fact that having a clean fast running code is very important to the creation of a world-class application. I want to emphasize the speed of an application in my statement. To elaborate, the choice of your data structure will make the difference between a fast program and a slow underperforming one. In this question make sure to list the main difference between an ArrayList and a LinkedList in terms of performance. No code is a need in this question as the main idea is to examine your grasp of runtime performance and data structure implementation in terms of Java programming.
If we compare a LinkedList and an ArrayList we have to understand that the main variables used to compare these two data structures. Indeed, we can classify our comparison in terms of access speed, data manipulation, and implementation. First, when it comes to runtime speed ArrayLists outperform LinkedList as they are accessible using the index operators. Second, Linked Lists are better at storing data in an ordered manner as every element in the list is linked to the previous element. Finally, code implementation both an ArrayList and LinkedList are deployed using the List interface found in the Java util library. In other words, they are very simple in terms of internal code resume and algorithm implementation.
Written by Mohamed Echout on May 7th, 2021
4. Design a Java class that performs a linear search using a list of integer values?
This question examines your understanding of Java linear search which is a searching algorithm that can be implemented using the Java programming language. This will be a set of questions that will test your understanding of algorithm analysis using Java. Most of these algorithm analysis questions will be code-based questions where you will need to demonstrate your understanding of the basic searching and sorting algorithms using Java code. To implement a linear search you might use a for loop that will be used to traverse a list of integer values. Alternatively, you might be tempted to use a class implementation of linear search. However, the main takeaway from these questions is to limit your implementation to the basic building blocks of Java. Indeed, this will save you time and will limit your risk of Java compilation errors.
To perform the linear search algorithm we start by creating a search function under the main class. To explain, this search function will be declared as static with an integer return type. In addition, the logic of our method will simply be to traverse all the elements in our list to find out our value starting from the first elements to the last one in our array. Keep in mind that in some cases the value we are searching for will not be found in the list which will result in an error. In this case, we will return the value -404 as a representation of value not found. The code used to implement this logic is as follow:
package JavaQuestions;
public class LinearSearchClass {
public static void main(String[] args) {
int[] myData = { 40, 14, -1, 61, 0 };
int findNumber = 0;
int found = mySearch(myData, findNumber);
System.out.print("My number was found at location: " + found);
}
static int mySearch(int[] data, int number) {
int notFound = -404;
for (int i = 0; i < data.length; i++) {
if (data[i] == number)
return i;
}
return notFound;
}
}
Written by Mohamed Echout on May 7th, 2021
5. In terms of collection sorting algorithms, how does the implementation of a Comparable and a Comparator interface differ in terms of Java?
This question examines your understanding of Java collection methods and comparison tools. Indeed, Java offers a large set of tools, methods, and libraries that can help you compare your objects. One of the main questions that will be asked in the process of your Java technical interview is the difference between the comparable and comparator Java interfaces. To answer this question you might be tempted to create two code blocks. First, a class that uses the comparators algorithm and another one that will be using the comparable one. Second, a third-class will call both these interfaces to showcase the differences. I would advise against this strategy as it requires heavy code. If the question doesn’t specify the use of a code block then try always to keep your answer as far from code as possible. The way to answer this question is to compare both interfaces and showcase examples of their uses.
Initially, a comparable or comparator interface is used to compare objects belonging to a list class type. They are very useful if your Java program contains some sorting algorithm that will sort elements in your ArrayList for example. The main value of using a comparable interface over a comparator is the method call. To explain, the comparable interface will be used to compare two objects by using one object to call the other. For instance, object1 will call the compareTo method that takes as argument the second object we want to compare called object2. However, the comparator interface will take a different path. Indeed, both objects will be called independently of each other and they will be both given to the compare method as arguments.
Written by Mohamed Echout on May 7th, 2021
6. Explain a Java class that implements the process of serialization?
This question examines your understanding of the serialization implementation. Part of the Java technical interview process will be to fully comprehend your level of expertise in terms of file storage choices using the serialization process. To explain, having a clean efficient program is very important to the creation of a professional Java application. To elaborate, the choice of your storage operations will make the difference between an efficient program and a slow underperforming one. In this question make sure to explain the process of serialization. No code is a need in this question all you will need is an example showcasing the use of serialization.
To start we need to implement the basic class structure. To explain, a random class would be created with attributes, methods, a constructor, and a toString method. This method will be used for our testing purposes. To implement a serializable object we will have to add a simple input in the class signature. This input is by adding the keyword implements to the class name followed by the java.io.Serializable. This will enable fast storage and retrieval of our object in case the object is saved in our local storage. To explain, having a Serializable object converts all its elements to an array of bytes that can save processing time and improves program performance.
Written by Mohamed Echout on May 7th, 2021
7. In terms of File Input/Output operations, what is the difference between Serialization and Deserialization of a Java object?
This question examines your understanding of the file input and output operations. As part of the Java interview questions, you will be tested in terms of file input and output choices using the serialization and deserialization process. To explain, having a quick file storage program is very important to the creation of a seamless Java application. In this question make sure to explain the difference between serialization and deserialization. The goal is to make sure both terms are explained from a file storage perspective in terms of Java programming.
To explain the difference between Serialization and Deserialization of a Java object an example will be provided. Let’s assume we have a Java class that represents an employee. This class contains a name, id, and salary. During the Java programming process, one of the steps that we might be taking is to save our employee objects to a local file. This process is time-consuming and can cause our application to consume a lot of processing power. To save time and performance we will convert the class to a series of bytes using the Serialization process. Once done we will be able to instantly save the object to our local storage. However, to read the file again and use it in our program we need to convert it from a series of bytes to an employee object and that is the process of Deserialization.
Written by Mohamed Echout on May 7th, 2021
8. Design a Java class that demonstrates the use case of a HashMap in storing and displaying your data?
This question examines your understanding of Java data structure implementation. Part of the Java technical interview process will be to fully comprehend your level of expertise in terms of data structure choices. To explain, developing a Java application is more than creating a set of classes and methods that perform certain tasks. This is demonstrated by the fact that having a clean fast running code is very important to the creation of a world-class application. In this question make sure to implement a HashMap using the Map interface. A code block is needed in this question as the main idea is to perform the basic operation of adding and displaying elements in a HashMap.
The HashMap data structure can be called by importing the hashmap library found in java. util.HashMap. In addition, to fully test our hashmap implementation we will use the map library that will enable us to call the keys and value in our hashmap. Our class will contain the main method to run our code. To start we will create a hashmap that will hold two strings, a first name, and the last name. The logic of our program is to have a hashmap that stores full names in our program. Once our hashmap is created we will add some elements to our data structure. This can be done using the put method. Next, we need to display our elements and a for loop is the perfect candidate for this operation. The code used for this process is as follows:
package JavaQuestions;
import java.util.HashMap;
import java.util.Map;
public class HashMapClass{
public static void main(String[] args){
Map<String,String> fullNameMap = new HashMap<>();
fullNameMap.put("First","Last");
fullNameMap.put("FirstName","LastName");
for(Map.Entry name : fullNameMap.entrySet()){
System.out.println(name);
}
}
}
Written by Mohamed Echout on May 7th, 2021
9. In terms of data structure, what is the difference between a Binary Search Tree and a Binary Tree?
This question examines your understanding of Java tree classes and interfaces. Indeed, Java offers a large set of tree objects used to store, search, or retrieve your application’s data. One of the main questions that will be asked in the process of your Java technical interview is the difference between a Binary Search Tree and a Binary Tree. To answer this question you might be tempted to create two code blocks. First, a class that implements a Binary Search Tree and another one that will be implementing Binary Tree. I would advise against this strategy as it requires heavy code. If the question doesn’t specify the use of a code block then try always to keep your answer as far from code as possible. The way to answer this question is to explain where we can use a Binary Tree compared to the use case of a Binary Search Tree.
Comparing a Binary Tree and Binary Search Tree comes down to one main factor in Java called a data structure. To explain, a binary tree is a data structure used to store data in a tree format. However, a binary search tree is used to store data not only for storage purposes but also for ease of search capabilities. If you chose to store your data in a binary search tree you will be able to easily retrieve any one of your values or objects in a more efficient faster manner. The overall idea is that a binary tree is a way we store our values in Java and a binary search tree is a more advanced storage way that comes with searching capabilities.
Written by Mohamed Echout on May 7th, 2021
10. In terms of Java programming explain the main elements of the Insertion Sort algorithm?
This question examines your understanding of the major search algorithms in computer science. To explain, one of the key ingredients to ensure that your interview goes as great as possible is to make sure that your computer science understanding covers the major areas. One of these areas is search algorithms. Insertion search can be explained using code blocks, real-world examples, or the combination of the two. You will have to choose which strategy makes sense to you depending on the interview and the position of the question. If you think that creating a Java program that uses an Insertion search algorithm is the best way to explain this algorithm that would be a path to take.
The insertion sort in terms of Java can be implemented using a Java class that holds a list, a sort method, and a print method. To explain, the list will hold our values that we want to sort the method sort will implement the logic of our insertion sort and the print will output the final results. The insertion algorithm traverse over all elements or object in our list and compares the elements by finding out the correct order to sort all values. The unique input of the insertion sort is the fact we always need to keep track of the last element we are comparing to understand where this element should be inserted in our list.
Written by Mohamed Echout on May 7th, 2021
11. In terms of choosing a data structure, what is the difference between a LinkedList and a doubly-linked list?
This question examines your understanding of Java List interfaces. Indeed, Java offers a set of List interfaces that help you store your data. One of the main questions that will be asked in the process of your Java technical interview is the difference between a LinkedList and a doubly-linked list. To answer this question you can create two code classes. A First-class that implements a LinkedList and another one that will be implementing a doubly-linked List. This strategy requires heavy code but can be very effective. Another option is to try to compare both lists by showcasing examples of where they can be used in a Java program.
If we compare a linked list with a doubly-linked list we need to understand that these both belong to the list interface offered in the Java programming environment. In other words, they both serve the same goal of storing data in our program. However, one of the main differences between the two data structures is the memory these lists use. A LinkedList will use less memory than a doubly-linked list. To explain, a doubly-linked list contains an additional element that keeps track of the previous and next element in our list. This extra element is what causes the doubly-linked list to be quite heavy in terms of memory usage. There is another difference worth mentioning in terms of speed and efficiency. Linked Lists tend to underperform when put under the test against doubly-linked List. Indeed, this can be explained by the fact that a doubly-linked list can easily be manipulated to add more data and search for any value or object in our list.
Written by Mohamed Echout on May 7th, 2021
12. In terms of File input operations, what is the difference between a FileReader and a FileInputStream?
This question examines your understanding of Java file input operators. Indeed, Java offers a set of file interfaces that help you read your data. One of the main questions that will be asked in the process of your Java technical interview is the difference between a FileReader and a FileInputStream. To answer this question you can create two code classes. A First-class that implements a FileReader and another one that will be implementing a FileInputStream. This strategy requires heavy code but can be very effective. Another option is to try to compare both file operators by providing examples of where they can be implemented in your Java program.
Both FileReader and FileInputStream are used to read data from your local file directory. Indeed they have the same role and objective. The difference between the two operators is the way they process data. For example, the FileReader will read data from a local file in the form of characters that can be used in your program as input for your lists or output for another file. On the other hand, the FileInputStream read your data from your file directly in the form of an array of bytes that you can convert to any datatype in your Java program.
Written by Mohamed Echout on May 7th, 2021
13. Design a Java class that demonstrates the usage of a LinkedList in storing and displaying your data?
This question examines your understanding of Java data structure implementation. Part of the Java technical interview process will be to fully comprehend your level of expertise in terms of data structure choices. To explain, developing a Java application is more than creating a set of classes and methods that perform certain tasks. This is demonstrated by the fact that having a clean fast running code is very important to the creation of a world-class application. In this question make sure to implement a LinkedList using the List interface. A code block will be needed in this question as the main idea is to perform the basic operations of adding and displaying elements in a LinkedList.
The LinkedList data structure can be called by importing the LinkedList library found in java.util.LinkedList. Our class will contain the main method to run our code. To start we will create a LinkedList that will hold file strings representing numbers. The logic of our program is to have a LinkedList that stores these strings and displays them using the print statement. Once our LinkedList is created we will add some elements to our data structure. This can be done using the add method. Next, we need to display our elements and a for loop is the perfect candidate for this operation. The code used for this process is as follows:
package JavaQuestions;
import java.util.LinkedList;
import java.util.List;
public class LinkedListClass {
public static void main(String[] args) {
List<String> myLinkedList = new LinkedList<>();
myLinkedList.add("1");
myLinkedList.add("2");
myLinkedList.add("3");
myLinkedList.add("4");
for(String element : myLinkedList){
System.out.println(element);
}
}
}
Written by Mohamed Echout on May 7th, 2021
14. Design a Java class that removes spaces from a hard-coded String value?
This question examines your understanding of the string operators available in the Java programming environment. You will be required to showcase your coding skills in terms of Java class declaration, string methods, and print statements. You can answer this question in many ways. However, the best strategy is to create a Java class that will include a main method that will thereafter contain the logic of your program. Having a separate class that does the work, in this case, is not a very efficient strategy as the work can be done in the main method. If you need to import external libraries try to explain why you made these imports and keep your answer clear and code statements easy to follow and understand.
In the following code block, I will create a main class called RemoveSpacesClass. This class will hold my main method that will contain my test sentence in the form of a string. The logic of the program starts by calling the method removeSpaces that takes care of removing all spaces from my string input and returns a string with zero spaces. The following is the code bock used to demonstrate this logic:
package JavaQuestions;
public class RemoveSpacesClass {
public static void main(String args[]) {
String withSpaces = " My test sentence";
String noSpaces = removeSpaces(withSpaces);
System.out.println("Before: "+withSpaces);
System.out.println("After: "+noSpaces);
}
public static String removeSpaces(String sentence){
StringBuilder newSentence = new StringBuilder();
char[] sentenceArray = sentence.toCharArray();
for(char ch : sentenceArray) {
if (!Character.isWhitespace(ch))
newSentence.append(ch);
}
return newSentence.toString();
}
}
Written by Mohamed Echout on May 7th, 2021
15. Design a Java class that demonstrates the usage of a stack in storing and displaying your data?
This question tests your understanding of Java data structure. The interviewer is trying to measure your comfort level with different data structures using Java programming. The shortest path to answer this question is to implement the use case of a stack. In this question, you will be better off if you can print out all the elements you added to the stack. In other words, you are expected to give code examples stack using any data or object value of your choice. Try to implement the main class of a stack coupled with an example and you can be certain that you successfully answered the question.
The stack data structure can be called by importing the stack library found in java.util.Stack. In addition, to fully test our stack implementation we will use the for loop that will enable us to call the values in our stack. Our class will contain the static void main method to run our code. To start we will create a stack that will hold five booleans. The logic of our program is to have a stack that stores the Object boolean values and prints them thereafter. Once our stack is created we will add our elements to our data structure. This can be done using the push method. Next, we need to display our elements and a for loop is the perfect candidate for this operation. The code used for this process is as follows:
package JavaQuestions;
import java.util.Stack;
public class StackTestClass {
public static void main(String[] args) {
Stack<Boolean> myStack= new Stack<>();
myStack.push(Boolean.TRUE);
myStack.push(Boolean.TRUE);
myStack.push(Boolean.FALSE);
myStack.push(Boolean.FALSE);
myStack.push(Boolean.TRUE);
for(Boolean element: myStack){
System.out.println(element);
}
}
}
Written by Mohamed Echout on May 7th, 2021
16. What would be the difference between choosing a stack or a queue in terms of data structure while building a Java program?
This question tests your understanding of Java data structure. The interviewer is trying to measure your comfort level with different data structures using Java programming. The shortest path to answer this question is to compare the use case of a stack and a queue. In this question, you will be better off if you can explain each data structure with a real-world example. In other words, you are expected to give examples of applications you created using a queue or a stack. Try to presents the overall idea of a stack and a queue coupled with an example and you can be certain that you successfully answered the question.
To decide between choosing a stack or a queue in terms of Java data structure we need to understand our Java program. A stack is used to store values in the LIFO order. To explain, LIFO stands for Last In First Out which represents the way we save data while using a stack. For example, if we store data in a stack elements will be added to a list in a normal manner. However, during the removal of these elements, we start with the last elements we added. A java program that keeps track of the user click can use a stack to keep track of the last posting a user clicks in the program. Alternatively, a queue follows the FIFO order that stands for First In First Out. For example, a program that needs to keep track of users that are signing up to our application to process their data on a first come first serve basis. The main difference between choosing a stack or a queue is in the use case or the program we are tiring to develop.
Written by Mohamed Echout on May 7th, 2021
17. Design a Java class that demonstrates the usage of a Vector in storing and displaying your data?
This question examines your understanding of Java data structure implementation. Part of the Java technical interview process will be to fully comprehend your level of expertise in terms of data structure choices. To explain, developing a Java application is more than creating a set of classes and methods that perform certain tasks. This is demonstrated by the fact that having a clean fast running code is very important to the creation of a world-class application. In this question make sure to implement a Vector using the Vector interface. A code block will be needed in this question as the main idea is to perform the basic operations of adding and displaying elements in a Vector.
The Vector data structure can be called by importing the Vector library found in java.util.Vector import. In addition, to fully test our Vector implementation we will use the loop that will output our values after the storing operation. Our class will contain the main method to run our code statement. To start we will create a Vector that will hold two strings a V1 and V2. The logic of our program is to have a Vector that stores smartphone versions. Once our Vector is created we will add some elements to our data structure. This can be done using the addElement method. Next, we need to display our elements and a for loop is the perfect candidate for this operation. The code used for this process is as follows:
package JavaQuestions;
import java.util.Vector;
public class VectorClass {
public static void main(String[] args) {
Vector<String> myVectors = new Vector<>();
myVectors.addElement("V1");
myVectors.addElement("V2");
for(String vectors : myVectors){
System.out.println(vectors);
}
}
}
Written by Mohamed Echout on May 7th, 2021
18. Design a Java class called Student with your getters, setters, constructor, and toString method?
This is a highly expected question in the Java interview process. Understanding how to create a Java class with all its values, methods, and elements is very important in learning this programming language. The goal here is for you to code the class using the best programming practices followed in the Java documentation. Keep your code limited to the question requirements as they are very important to demonstrate your ability to understand the client’s needs while developing a Java application. The easiest strategy to follow in this question is to explain every part of your code with good documentation and comments to showcase your code’s professionalism.
The program will start by creating a Java class called Student. This class will hold our main elements. First, the attributes full name and id both will take the value of strings. Second, we will implement setters and getters that will be used to either get the value of your attribute or set them in later stages of the program. Next, a constructor will be also coded to instantiate our student objects, normally it will take the full names and id attributes as input. The last puzzle piece of our program will wilt the toString method that is used to display all the elements of our student object. The code used for this example is as follows:
package JavaQuestions;
public class MyStudent {
private String fullNames;
private int studentID;
public MyStudent(String fullNames, int studentID) {
this.fullNames = fullNames;
this.studentID = studentID;
}
public String getFullNames() {
return fullNames;
}
public void setFullNames(String fullNames) {
this.fullNames = fullNames;
}
public int getStudentID() {
return studentID;
}
public void setStudentID(int studentID) {
this.studentID = studentID;
}
@Override
public String toString() {
return "Student{" +
"fullNames='" + fullNames + '\'' +
", studentID=" + studentID +
'}';
}
}
Written by Mohamed Echout on May 7th, 2021
19. Design a Java class that will use a built-in Java method to sort an ArrayList of floating-point numbers?
This question tests your understanding of Java sorting algorithms and data structure. The interviewer is trying to measure your comfort level with sorting data using Java programming. The shortest path to answer this question to call a Collection sort algorithm that will sort a list of floating numbers. In this question, you will be better off if you can create multiple numbers that will each serve as a puzzle piece for your sorting algorithm. In other words, try to import some of the Java util libraries used to test your program. You are not expected to have a perfect flawless implementation of the collection sort algorithm. If your program presents the overall idea of the collection sort you can be certain that you successfully answered the question.
The Collections Sort method can be called by importing the Collections library found in java.util.Collections. In addition, to fully test our program we will use the ArrayList library that will enable us to store a list of floating numbers. Our class will contain the main method to run our code. To start we will create an ArrayList that will hold four numbers. The logic of our program is to have an ArrayList that stores unordered floating numbers and then sorted them with the collection sort method. Once our ArrayList is created we will add the numbers to our data structure. This can be done using the add method. Next, sort our numbers using the Collection sort method that takes as argument the ArrayList of flowing numbers. The code used for this process is as follows:
package JavaQuestions;
import java.util.ArrayList;
import java.util.Collections;
public class ArrayListSorted {
public static void main(String[] args){
ArrayList<Float> myNumbers = new ArrayList<>();
myNumbers.add((float) 12.11);
myNumbers.add((float) 16.11);
myNumbers.add((float) 15.11);
myNumbers.add((float) 10.11);
Collections.sort(myNumbers);
for(Float numbers: myNumbers){
System.out.println(numbers);
}
}
}
Written by Mohamed Echout on May 7th, 2021
20. Design a Java class that reverses the order of a String array?
This question examines your understanding of Java arrays and string data types. Your answer can take many forms. For example, a strategy is to create a Java class called StringArray that will contain a method that will reverse a string array. In addition, the method can contain a toString method to display the final results. Avoid using any external libraries to implement your answer. In other words, the question doesn’t require importing any external libraries and it opens us the opportunity for you to use a combination of loops and print statements.
To implement the code block for this question we first start with creating 3 variables. First, a variable that will hold our string in the form of a sentence. Second, an empty string variable will be used to store our string array after we reverse the string order. Next, an array variable will be used to store our string sentence in an array format. To split the sentence into an array string we will use a regex expression that is defined within the Java environment. This will be done using the split method that takes as an argument the character that will be used to split the sentence. To reverse the order of our string array we will use a for loop that will store the variable front the last elements to the first one. The code used to cover this answer is as follows:
package JavaQuestions;
public class ReverseMySentence {
public static void main(String[] args) {
String sentence = "This is a test";
StringBuilder myReverse = new StringBuilder();
String[] mySentence = sentence.split(" ");
int sentenceSize = mySentence.length - 1;
for (int i = sentenceSize; i >= 0; i--) {
myReverse.append(mySentence[i]).append(" ");
}
System.out.println("My old sentence: " + sentence);
System.out.println("My new sentence: " + myReverse);
}
}
Written by Mohamed Echout on May 7th, 2021
21. Design a Java class that reads data from a text file and inserts the data into an ArrayList for processing?
This question examines your understanding of Java File Input Output operators. Indeed, this question will be used to examine your ability not only to take input from a local file. In addition, it will test your understanding of how to store the data after reading. The code in this section can be implemented in different ways and methods. One way is to use the FileReader class that will enable you to read the data from the file locally and then use a buffer to process it. However, I would advise you to use a simple Scanner object to conduct this task. To explain, less code means less likelihood of errors and exceptions. Make sure that during any coding question to go with the easy way out. In other words, the code should be simple and easy to follow.
The first step in creating the Text File Reader will create a Main class that will contain the main method containing our programming logic. Next, a File object will be created using the File constructor that takes the absolute path of the text file we wish to read. Following this step is the definition of a Scanner object that will be used to read the data from our file object. Last but not least an array list will be created to hold the data extracted from the file. To read the data from the file we will use a while loop that will keep reading every line from the file until we arrive at an empty line. The code used for this question can be demonstrated as follows:
package JavaQuestions;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class ReadDataFileClass {
public static void main(String[]args) throws FileNotFoundException{
String filePath = "data.txt";
File dataFile = new File(filePath);
Scanner fileReader = new Scanner(dataFile);
ArrayList<String> myData = new ArrayList<>();
while (fileReader.hasNextLine()) {
myData.add(fileReader.nextLine());
}
fileReader.close();
System.out.println(myData);
}
}
Written by Mohamed Echout on May 7th, 2021
22. In terms of Java programming explain the main elements of a Binary Search algorithm?
This question examines your understanding of the major search algorithms in computer science. To explain, one of the key ingredients to ensure that your interview goes as great as possible is to make sure that your computer science understanding covers the major areas. One of these areas is search algorithms. Binary search can be explained using code blocks, real-world examples, or the combination of the two. You will have to choose which strategy makes sense to you depending on the interview and the position of the question. However, no matter what you do try to go with the strategy that you feel more comfortable with. If you think that creating a Java program that uses a binary search algorithm is the best way to explain this algorithm that would be a path to take. Overall keep your answer within the Java programming framework and give real examples in both cases.
A binary search can be implemented in A Java programming during the creation of an application that searches elements of a list of objects. For example, during the creation of a Java program that stores a list of students in a learning management system one of the features we might need to implement is to have a search function in this system. Doing a linear search is time-consuming that is why a more cost-effective option is to implement a binary search. This algorithm starts by sorting the elements in an ordered manner. Next, the algorithm then searches for our element or student in the middle of the list. Then, if the element is bigger than the middle index value we search the right-hand side of our list. In case, the element is smaller we search the left-hand side of our list. This process will be repeated until we finally find our student object in the learning management system.
Written by Mohamed Echout on May 7th, 2021
23. Design a Java class to check if two string values are identical?
String operators provided in the Java language. The interviewer is trying to measure your comfort level in some of the more intermediate Java string methods. In this question, you will simply create a Java class that will hold your main function. To elaborate, your class will contain the code that covers the question implementation. No need to create getters or setters for your class or a constructor, make sure everything is covered in the main class under the main method code block.
The code will contain a simple string comparison algorithm that will test if strings 01 and 02 are identical. One of the methods that is perfectly suited for this task is the contains method. This method will return two values. First, the value true is strings 01 and 02 contain the same characters. Second, false in case they are different in any shape or form. Once strings 01 are 02 are compared the second step is to print out the results using the println method. The following is the code that covers the implementation of this question:
package JavaQuestions;
public class StringClass {
public static void main(String[] args) {
String firstString = "Mike";
String secondString = "Mikey";
boolean identical = firstString.contains(secondString);
System.out.println(identical);
firstString = "Sarah";
secondString = "Sarah";
identical = firstString.contains(secondString);
System.out.println(identical);
}
}
Written by Mohamed Echout on May 7th, 2021
24. In terms of Java programming explain the main elements of the merge sort algorithm?
This question tests your understanding of Java search algorithms and data structure. The interviewer is trying to measure your comfort level with searching, sorting, and merging data using Java programming. The shortest path to answer this question to explain a merge sort algorithm that sorts a list of numbers. To explain, the goal is to ensure the logic of your algorithm is identical to the merge sort implementation known in the Java programming language. In this question, you will be better off if you can explain multiple methods that will each serve as a puzzle piece for your merge sorting algorithm. In other words, try to explain your answer by using some of the Java concepts such as modularity to showcase your understanding of Java at a more sophisticated level.
In terms of Java programming using the merge sort is a great option if the program goal is to sort a list of numbers or values. To start the merge sort use the concept of divide and conquer. In other words, the program starts by defining the list of numbers using the ArrayList collection. Next, this list will be processed by a method that will try to find the middle of the list. Indeed, this method will take the total number of elements in our list and divide them by two. Following, the next step is to process the first half of our list by sorting the element in that half. Next, the same will be done on the second half of our list. The logic is to work recursively in every half of our list until all elements or objects are totally sorted.
Written by Mohamed Echout on May 7th, 2021
25. Design a Java class that builds an Array List of Strings and adds various values of this data structure?
This question examines your understanding of the various data structures offered in the Java programming language. Your job is to create an ArrayList that holds string values and then adding different elements to this collection. You can create a collection class to answer this question or keep your code only limited to the working of the main method. One of the more efficient strategies is to create a Java class that will serve as your main class. In addition, add to this class a method called add elements that will enable you to add values or elements to your ArrayList. The most important point in this scenario is to make sure that your program can create an array list and add various elements to that list using a method call or a loop.
In the following code block, I will create a main class that will be used to call two methods. First, the main method will be used as a starting point for my program. Second, the addString method will be used to add elements to my ArrayList collection. The main method will also be used to create an ArrayList called names and a list of names called myNames. Once all variables are initialized the next step is to call the method addString to add every element in the list names to the ArrayCollection names. To make sure we are not adding any empty strings the method addString will check for empty strings. The following is the code block used to demonstrate this solution:
package JavaQuestions;
import java.util.ArrayList;
public class ArrayListClass {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
String[] myNames = {"Mike", "John", "Sarah"};
System.out.println("Before: "+names);
for(int i = 0; i<3 ;i++){
addString(myNames[i], names);
}
System.out.println("After: "+names);
}
public static void addString(String element, ArrayList<String> names){
if (element.isEmpty() != true){
names.add(element);
}
}
}
Written by Mohamed Echout on May 7th, 2021