InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
How does the size of ArrayList grow dynamically? And also state how it is implemented internally. |
|
Answer» ArrayList is IMPLEMENTED in such a way that it can grow dynamically. We don't need to specify the size of ArrayList. For adding the values in it, the methodology it uses is - 1. Consider initially that there are 2 elements in the ArrayList. [2, 3]. 2. If we need to add the element into this. Then internally what will happen is-
3. This process continues and the time taken to perform all of these is considered as the amortized constant time. This is how the ArrayList grows dynamically. And when we DELETE any entry from the ArrayList then the FOLLOWING steps are PERFORMED - 1. It searches for the element index in the array. Searching takes some time. Typically it’s O(n) because it needs to search for the element in the entire array. 2. After searching the element, it needs to shift the element from the right side to fill the index. So this is how the elements are deleted from the ArrayList internally. Similarly, the search operations are also implemented internally as defined in removing elements from the list (searching for elements to delete). |
|
| 2. |
How many overloaded add() and addAll() methods are available in the List interface? Describe the need and uses. |
||||||||||
|
Answer» There are a total of 4 overloaded methods for add() and addAll() methods available in List Interface. The below table states the DESCRIPTION of all.
|
|||||||||||
| 3. |
Why is the remove method faster in the linked list than in an array? |
|
Answer» In the linked list, we only need to adjust the references when we want to delete the element from either end or the front of the linked list. But in the array, INDEXES are used. So to manage proper indexing, we need to adjust the values from the array So this adjustment of value is COSTLIER than the adjustment of references. Example - To Delete from the front of the linked list, internally the references adjustments happened LIKE this. The only THING that will change is that the head pointer will point to the head’s next node. And delete the previous node. That is the constant time operation. Whereas in the ArrayList, internally it should work like this- For DELETION of the first element, all the next element has to move to one place ahead. So this copying value takes time. So that is the reason why removing in ArrayList is slower than LinkedList. |
|
| 4. |
Why does the java array index start with 0? |
|
Answer» It is because the 0 index array avoids the extra arithmetic operation to calculate the MEMORY ADDRESS. Example - Consider the array and assume each element takes 4-byte memory SPACE. Then the address will be like this - Now if we want to access index 4. Then internally java calculates the address using the formula- [Base Address + (index * no_of_bytes)]. So ACCORDING to this. The starting address of the index 4 will be - [100 + (4*4)] = 116. And exactly that's what the address is calculated. Now if we apply the same formula here. Then we get - 116 as the starting address of the 4th index. Which is wrong. Then we need to apply formula - [Base Address + ((index-1) * no_of_bytes)]. And for calculating this, an extra arithmetic operation has to be performed. And consider the case where millions of ADDRESSES need to be calculated, this causes complexity. So to avoid this, ) the index array is supported by java. |
|
| 5. |
Contiguous memory locations are usually used for storing actual values in an array but not in ArrayList. Explain. |
|
Answer» In the case of ARRAYLIST, data storing in the form of primitive data types (like int, float, etc.) is not possible. The data members/objects present in the ArrayList have REFERENCES to the objects which are LOCATED at various sites in the memory. Thus, storing of actual objects or non-primitive data types (like Integer, Double, etc.) takes place in various memory locations. However, the same does not apply to the arrays. Object or primitive type values can be stored in arrays in contiguous memory locations, HENCE EVERY element does not require any reference to the next element. |
|
| 6. |
Can you call a constructor of a class inside the another constructor? |
|
Answer» YES, the concept can be TERMED as constructor chaining and can be achieved USING this(). |
|
| 7. |
Will the finally block get executed when the return statement is written at the end of try block and catch block as shown below? |
|
Answer» PUBLIC int someMethod(int i){ try{ //some statement return 1; }CATCH(EXCEPTION e){ //some statement return 999; }FINALLY{ //finally block statements }} finally block will be executed irrespective of the exception or not. The only case where finally block is not executed is when it ENCOUNTERS ‘System.exit()’ method anywhere in try/catch block. |
|
| 8. |
Is it mandatory for a catch block to be followed after a try block? |
|
Answer» No, it is not NECESSARY for a catch block to be present after a try block. - A try block should be followed EITHER by a catch block or by a finally block. If the exceptions likelihood is more, then they should be declared using the THROWS CLAUSE of the method. |
|
| 9. |
How do exceptions affect the program if it doesn't handle them? |
|
Answer» EXCEPTIONS are runtime errors. Suppose we are making an android application with java. And it all works fine but there is an exceptional case when the application TRIES to get the file from storage and the file doesn’t EXIST (This is the case of exception in java). And if this case is not handled properly then the application will crash. This will be a bad experience for users. This is the type of error that cannot be CONTROLLED by the programmer. But programmers can TAKE some steps to avoid this so that the application won’t crash. The proper action can be taken at this step. |
|
| 10. |
How does an exception propagate in the code? |
|
Answer» When an exception occurs, first it searches to locate the matching CATCH BLOCK. In case, the matching catch block is located, then that block would be executed. Else, the exception propagates through the METHOD call stack and goes into the caller method where the PROCESS of matching the catch block is performed. This propagation happens until the matching catch block is found. If the match is not found, then the program gets terminated in the main method. |
|
| 11. |
What do you understand by Object Cloning and how do you achieve it in Java? |
Answer»
|
|
| 12. |
What happens if there are multiple main methods inside one class in Java? |
|
Answer» The PROGRAM can't compile as the compiler says that the METHOD has been already defined inside the class. |
|
| 13. |
Can we make the main() thread a daemon thread? |
|
Answer» In java multithreading, the MAIN() THREADS are ALWAYS non-DAEMON threads. And there is no way we can change the NATURE of the non-daemon thread to the daemon thread. |
|
| 14. |
Consider the below program, identify the output, and also state the reason for that. |
|
Answer» public class MAIN{public static void main(String[] args) { System.out.println(" Hello. Main METHOD. ");}public static void main(INT[] args) { System.out.println(" Hello. Main Method2. ");}} The output of the above program will be Hello. Main Method. This is because JVM will always CALL the main method based on the definition it already has. Doesn't matter how many main methods we overload it will only EXECUTE one main method based on its declaration in JVM. |
|
| 15. |
What happens if the static modifier is not included in the main method signature in Java? |
|
Answer» There wouldn't be any COMPILATION error. But then the program is run, since the JVM CANT map the main METHOD SIGNATURE, the code throws “NoSuchMethodError” error at the RUNTIME. |
|
| 16. |
How to not allow serialization of attributes of a class in Java? |
Answer»
|
|
| 17. |
Which among String or String Buffer should be preferred when there are lot of updates required to be done in the data? |
|
Answer» StringBuffer is MUTABLE and dynamic in nature whereas String is immutable. EVERY updation / modification of String creates a new String thereby overloading the string pool with unnecessary objects. Hence, in the CASES of a lot of UPDATES, it is always preferred to use StringBuffer as it will reduce the overhead of the creation of multiple String objects in the string pool. |
|
| 18. |
What is the ‘IS-A ‘ relationship in OOPs java? |
|
Answer» ‘IS-A’ relationship is another name for inheritance. When we inherit the base CLASS from the DERIVED class, then it forms a relationship between the classes. So that relationship is termed an ‘IS-A’ Relationship. Example - Consider a TELEVISION (Typical CRT TV). Now another Smart TV that is INHERITED from television class. So we can say that the Smart iv is also a TV. Because CRT TV THINGS can also be done in the Smart TV. So here ‘IS-A’ Relationship formed. [ SmartTV ‘IS-A’ TV ]. |
|
| 19. |
Java works as “pass by value” or “pass by reference” phenomenon? |
|
Answer» Java always WORKS as a “pass by value”. There is nothing called a “pass by reference” in Java. HOWEVER, when the object is passed in any method, the address of the value is passed due to the nature of object handling in Java. When an object is passed, a copy of the reference is created by Java and that is passed to the method. The objects point to the same memory location. 2 cases might happen inside the method:
For example: class InterviewBitTest{ int num; InterviewBitTest(int x){ num = x; } InterviewBitTest(){ num = 0; }}class DRIVER { public static void main(String[] args) { //create a reference InterviewBitTest ibTestObj = new InterviewBitTest(20); //Pass the reference to updateObject Method updateObject(ibTestObj); //After the updateObject is EXECUTED, check for the value of num in the object. System.out.println(ibTestObj.num); } public static void updateObject(InterviewBitTest ibObj) { // Point the object to new reference ibObj = new InterviewBitTest(); // Update the value ibObj.num = 50; }}Output:20
For example: class InterviewBitTest{ int num; InterviewBitTest(int x){ num = x; } InterviewBitTest(){ num = 0; }}class Driver{ public static void main(String[] args) { //create a reference InterviewBitTest ibTestObj = new InterviewBitTest(20); //Pass the reference to updateObject Method updateObject(ibTestObj); //After the updateObject is executed, check for the value of num in the object. System.out.println(ibTestObj.num); } public static void updateObject(InterviewBitTest ibObj) { // no changes are made to point the ibObj to new location // Update the value of num ibObj.num = 50; }}Output:50 |
|
| 20. |
Identify the output of the below java program and Justify your answer. |
|
Answer» class Main { public static void main(String args[]) { SCALER s = new Scaler(5); }}class InterviewBit{ InterviewBit(){ System.out.println(" Welcome to InterviewBit "); }}class Scaler extends InterviewBit{ Scaler(){ System.out.println(" Welcome to Scaler ACADEMY "); } Scaler(int X){ this(); super(); System.out.println(" Welcome to Scaler Academy 2"); }} The above code will throw the compilation error. It is because the super() is used to call the parent class constructor. But there is the condition that super() must be the first statement in the block. Now in this case, if we replace this() with super() then also it will throw the compilation error. Because this() also has to be the first statement in the block. So in conclusion, we can say that we cannot USE this() and super() keywords in the same block. |
|
| 21. |
What are the differences between constructor and method of a class in Java? |
||||||||||||||||
Answer»
|
|||||||||||||||||
| 22. |
What is the difference between the ‘throw’ and ‘throws’ keyword in java? |
Answer»
Example - class Main { public static int testExceptionDivide(int a, int b) throws ArithmeticException{ if(a == 0 || b == 0) throw new ArithmeticException(); return a/b; } public static void main(String args[]) { try{ testExceptionDivide(10, 0); } CATCH(ArithmeticException e){ //Handle the exception } }}Here in the above snippet, the method testExceptionDivide throws an exception. So if the main method is calling it then it MUST have handled the exception. Otherwise, the main method can ALSO throw the exception to JVM. And the method testExceptionDivide 'throws’ the exception based on the condition. |
|
| 23. |
What is the difference between the program and the process? |
Answer»
|
|
| 24. |
What are the different types of Thread Priorities in Java? And what is the default priority of a thread assigned by JVM? |
|
Answer» There are a total of 3 different types of priority AVAILABLE in JAVA. MIN_PRIORITY: It has an integer value assigned with 1. In Java, THREAD with MAX_PRIORITY gets the first chance to EXECUTE. But the default priority for any thread is NORM_PRIORITY assigned by JVM. |
|
| 25. |
What are the different ways of threads usage? |
Answer»
|
|
| 26. |
What is the importance of reflection in Java? |
Answer»
|
|
| 27. |
What are the differences between HashMap and HashTable in Java? |
||||||||
Answer»
|
|||||||||
| 28. |
What are the differences between JVM, JRE and JDK in Java? |
||||||||||||||||||||||||
Answer»
|
|||||||||||||||||||||||||
| 29. |
What do we get in the JDK file? |
Answer»
|
|
| 30. |
Why is the character array preferred over string for storing confidential information? |
|
Answer» In Java, a string is basically immutable i.e. it cannot be modified. After its declaration, it continues to stay in the string pool as long as it is not removed in the form of GARBAGE. In other words, a string resides in the heap section of the memory for an unregulated and unspecified time interval after string value processing is executed. As a result, vital information can be stolen for pursuing harmful activities by hackers if a memory dump is ILLEGALLY accessed by them. Such risks can be eliminated by using mutable objects or structures like CHARACTER arrays for storing any VARIABLE. After the work of the character ARRAY variable is done, the variable can be configured to blank at the same instant. Consequently, it helps in saving heap memory and also gives no chance to the hackers to extract vital data. |
|
| 31. |
What makes a HashSet different from a TreeSet? |
|
Answer» Although both HashSet and TREESET are not SYNCHRONIZED and ensure that duplicates are not present, there are certain properties that distinguish a HashSet from a TreeSet.
|
|
| 32. |
In Java, static as well as private method overriding is possible. Comment on the statement. |
|
Answer» The statement in the context is completely False. The static methods have no relevance with the objects, and these methods are of the CLASS level. In the case of a CHILD class, a static METHOD with a method signature exactly like that of the parent class can exist without even throwing any compilation error. The phenomenon mentioned here is popularly KNOWN as method hiding, and overriding is CERTAINLY not possible. Private method overriding is unimaginable because the visibility of the private method is restricted to the parent class only. As a result, only hiding can be facilitated and not overriding. |
|
| 33. |
What is a Comparator in java? |
|
Answer» Consider the example where we have an ArrayList of employees LIKE( EId, Ename, Salary), etc. Now if we want to sort this list of employees based on the NAMES of employees. Then that is not possible to sort USING the Collections.sort() METHOD. We need to PROVIDE something to the sort() function depending on what values we have to perform sorting. Then in that case a comparator is used. Comparator is the interface in java that contains the compare method. And by overloading the compare method, we can define that on what basis we need to compare the values. |
|
| 34. |
Is this program giving a compile-time error? If Yes then state the reason and number of errors it will give. If not then state the reason. |
|
Answer» abstract final class InterviewBit{2. public abstract void printMessage();3. }4. class ScalarAcademy extends InterviewBit{5. public void printMessage(){6. System.out.println("Welcome to Scalar Academy By InterviewBit");7. }8. }9. class ScalarTopics extends ScalarAcademy{10. public void printMessage(){11. System.out.println("Welcome to Scalar TOPICS By Scalar Academy");12. }13. }public class Main{ public static void main(String[] args) { InterviewBit ib = new ScalarTopics(); ib.printMessage(); }} The above PROGRAM will give a compile-time error. The compiler will THROW 2 errors in this.
It is because abstract classes are INCOMPLETE classes that need to be inherited for making their concrete classes. And on the other hand, the final keywords in class are used for avoiding inheritance. So these combinations are not ALLOWED in java. |
|
| 35. |
Using relevant properties highlight the differences between interfaces and abstract classes. |
Answer»
Abstract class example: public abstract class Athlete {public abstract void walk();}Interface example: public interface Walkable {void walk();} |
|
| 36. |
How would you differentiate between a String, StringBuffer, and a StringBuilder? |
Answer»
|
|
| 37. |
Which of the below generates a compile-time error? State the reason. |
Answer»
We get a compile-time error in line 3. The error we will get in Line 3 is - integer number too large. It is because the array requires size as an integer. And Integer takes 4 Bytes in the memory. And the number (2241423798) is beyond the CAPACITY of the integer. The maximum array size we can declare is - (2147483647). Because the array requires the size in integer, none of the lines (1, 2, and 4) will give a compile-time error. The PROGRAM will compile fine. But we get the RUNTIME exception in line 2. The exception is - NegativeArraySizeException. Here what will happen is - At the time when JVM will allocate the required memory during runtime then it will find that the size is negative. And the array size can’t be negative. So the JVM will throw the exception. |
|
| 38. |
What is a singleton class in Java? And How to implement a singleton class? |
|
Answer» Singleton classes are those classes, whose objects are created only once. And with only that object the class members can be accessed. Understand this with the help of an example-: Consider the water jug in the office and if every employee wants that water then they will not create a NEW water jug for drinking water. They will use the existing one with their own reference as a glass. So programmatically it should be implemented as - class WaterJug{ PRIVATE int waterQuantity = 500; private WaterJug(){} private WaterJug object = null; // Method to provide the service of Giving Water. PUBLIC int getWater(int quantity){ waterQuantity -= quantity; return quantity; } // Method to return the object to the user. public static Waterjug getInstance(){ // Will Create a new object if the object is not ALREADY created and return the object. if(object == null){ object = new WaterJug(); } return object; }}In the above class, the Constructor is private so we cannot create the object of the class. But we can get the object by CALLING the method getInstance(). And the getInstance is static so it can be called without creating the object. And it returns the object. Now with that object, we can call getWater() to get the water. Waterjug glass1 = WaterJug.getInstance();glass1.getWater(1);We can get the single object using this getInstance(). And it is static, so it is a thread-safe singleton class. Although there are many ways to create a thread-safe singleton class. So thread-safe classes can also be:
|
|
| 39. |
Apart from the security aspect, what are the reasons behind making strings immutable in Java? |
|
Answer» A String is made immutable due to the following reasons:
|
|