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. |
Assume a thread has a lock on it, calling the sleep() method on that thread will release the lock? |
|
Answer» A THREAD that has a lock won't be released even after it calls sleep(). DESPITE the thread sleeping for a SPECIFIED period of time, the lock will not be released. |
|
| 2. |
What is a Memory Leak? Discuss some common causes of it. |
|
Answer» The Java Garbage Collector (GC) typically removes unused objects when they are no longer required, but when they are STILL referenced, the unused objects cannot be removed. So this causes the MEMORY leak problem. Example - Consider a linked list like the structure below - In the above image, there are unused objects that are not referenced. But then also Garbage collection will not free it. Because it is referencing some existing referenced OBJECT. So this can be the situation of memory leak. Some common causes of Memory leaks are -
|
|
| 3. |
What are the different categories of Java Design patterns? |
|
Answer» Java Design PATTERNS are categorized into the following DIFFERENT types. And those are also further categorized as Structural patterns:
Behavioral patterns:
J2EE patterns:
Creational patterns:
|
|
| 4. |
How we can set the spring bean scope. And what supported scopes does it have? |
|
Answer» A scope can be set by an annotation such as the @Scope annotation or the "scope" ATTRIBUTE in an XML configuration FILE. Spring Bean supports the FOLLOWING five SCOPES:
|
|
| 5. |
What is the best way to inject dependency? Also, state the reason. |
|
Answer» There is no boundation for using a particular dependency INJECTION. But the recommended approach is - Setters are mostly recommended for optional dependencies injection, and constructor arguments are recommended for mandatory ONES. This is because constructor injection ENABLES the injection of VALUES into immutable FIELDS and enables reading them more easily. |
|
| 6. |
In the below Java Program, how many objects are eligible for garbage collection? |
|
Answer» class Main{ public STATIC void main(String[] args){ int[][] num = new int[3][]; num[0] = new int[5]; num[1] = new int[2]; num[2] = new int[3]; num[2] = new int[5]; num[0] = new int[4]; num[1] = new int[3]; num = new int[2][]; }} In the above program, a total of 7 OBJECTS will be eligible for garbage collection. Let’s visually understand what's happening in the code. In the above figure on line 3, we can see that on each array index we are DECLARING a new array so the reference will be of that new array on all the 3 indexes. So the old array will be pointed to by none. So these three are eligible for garbage collection. And on line 4, we are creating a new array object on the older reference. So that will point to a new array and older multidimensional objects will become eligible for garbage collection. |
|
| 7. |
What are the possible ways of making object eligible for garbage collection (GC) in Java? |
|
Answer» FIRST Approach: Set the object references to null once the object creation purpose is served. PUBLIC class IBGarbageCollect { public static void main (String [] args){ String s1 = "Some String"; // s1 referencing String object - not yet eligible for GC s1 = null; // now s1 is eligible for GC } }Second Approach: Point the reference variable to another object. Doing this, the object which the reference variable was referencing before becomes eligible for GC. public class IBGarbageCollect { public static void main(String [] args){ String s1 = "To Garbage Collect"; String s2 = "Another Object"; System.out.println(s1); // s1 is not yet eligible for GC s1 = s2; // Point s1 to other object pointed by s2 /* Here, the string object having the content "To Garbage Collect" is not REFERRED by any reference variable. Therefore, it is eligible for GC */ }}Third Approach: Island of Isolation Approach: When 2 reference variables pointing to instances of the same class, and these variables refer to only each other and the objects pointed by these 2 variables don't have any other references, then it is said to have formed an “Island of Isolation” and these 2 objects are eligible for GC. public class IBGarbageCollect { IBGarbageCollect ib; public static void main(String [] STR){ IBGarbageCollect ibgc1 = new IBGarbageCollect(); IBGarbageCollect ibgc2 = new IBGarbageCollect(); ibgc1.ib = ibgc2; //ibgc1 points to ibgc2 ibgc2.ib = ibgc1; //ibgc2 points to ibgc1 ibgc1 = null; ibgc2 = null; /* * We see that ibgc1 and ibgc2 objects refer * to only each other and have no VALID * references- these 2 objects for island of isolcation - eligible for GC */ }} |
|
| 8. |
What is the output of the below code and why? |
|
Answer» public class InterviewBit{ public static void main(String[] args) { System.out.println('b' + 'i' + 't'); }} “bit” would have been the result PRINTED if the letters were USED in double-quotes (or the string literals). But the QUESTION has the CHARACTER literals (single quotes) being used which is why concatenation wouldn't OCCUR. The corresponding ASCII values of each character would be added and the result of that sum would be printed.
98 + 105 + 116 = 319 Hence 319 would be printed. |
|
| 9. |
Why is it said that the length() method of String class doesn't return accurate results? |
Answer»
Now if a string contained supplementary characters, the length function WOULD count that as 2 units and the result of the length() function would not be as per what is expected. In other words, if there is 1 supplementary character of 2 units, the length of that SINGLE character is considered to be TWO - Notice the inaccuracy here? As per the java documentation, it is expected, but as per the REAL logic, it is inaccurate. |
|
| 10. |
Explain the term “Double Brace Initialisation” in Java? |
|
Answer» This is a convenient means of initializing any collections in Java. Consider the below example. import java.util.HashSet;import java.util.SET; public class IBDoubleBraceDemo{ public static void main(String[] args){ Set<String> stringSets = NEW HashSet<String>() { { add("set1"); add("set2"); add("set3"); } }; doSomething(stringSets); } private static void doSomething(Set<String> stringSets){ System.out.println(stringSets); }}In the above example, we SEE that the stringSets were initialized by using double braces.
Care should be taken while initializing through this method as the method involves the creation of anonymous inner classes which can cause PROBLEMS during the garbage collection or serialization processes and may ALSO result in memory leaks. |
|
| 11. |
What do you understand by marker interfaces in Java? |
|
Answer» Marker interfaces, also KNOWN as tagging interfaces are those interfaces that have no methods and CONSTANTS defined in them. They are there for helping the COMPILER and JVM to get run time-related INFORMATION regarding the OBJECTS. |
|
| 12. |
Will the finally block be executed if the code System.exit(0) is written at the end of try block? |
|
Answer» NO. The control of the program post System.exit(0) is immediately gone and the program gets TERMINATED which is why the FINALLY BLOCK never gets EXECUTED. |
|
| 13. |
In case a package has sub packages, will it suffice to import only the main package? e.g. Does importing of com.myMainPackage.* also import com.myMainPackage.mySubPackage.*? |
|
Answer» This is a big NO. We need to understand that the importing of the sub-packages of a package needs to be done EXPLICITLY. Importing the PARENT package only results in the IMPORT of the classes WITHIN it and not the contents of its child/sub-packages. |
|
| 14. |
Is it possible to import the same class or package twice in Java and what happens to it during runtime? |
|
Answer» It is POSSIBLE to import a class or package more than once, HOWEVER, it is REDUNDANT because the JVM internally loads the package or class only once. |
|
| 15. |
What could be the tradeoff between the usage of an unordered array versus the usage of an ordered array? |
Answer»
|
|
| 16. |
Can you explain the Java thread lifecycle? |
|
Answer» Java thread life cycle is as follows:
The following flowchart clearly EXPLAINS the lifecycle of the thread in Java. |
|
| 17. |
Define System.out.println(). |
|
Answer» System.out.println() is used to print the message on the CONSOLE. System - It is a class PRESENT in java.lang package. Out is the static variable of type PrintStream class present in the System class. println() is the method present in the PrintStream class. So if we justify the statement, then we can SAY that if we want to print ANYTHING on the console then we need to call the println() method that was present in PrintStream class. And we can call this using the output OBJECT that is present in the System class. |
|
| 18. |
What will be the output of the below java program and define the steps of Execution of the java program with the help of the below code? |
|
Answer» class InterviewBit{ INT i; static int J; { System.out.println(" Instance Block 1. Value of i = "+i); } static{ System.out.println(" Static Block 1. Value of j = "+j); method_2(); } { i = 5; } static{ j = 10; } InterviewBit(){ System.out.println(" Welcome to InterviewBit "); } public static void main(String[] args){ InterviewBit ib = new InterviewBit(); } public void method_1(){ System.out.println(" Instance method. "); } static{ System.out.println(" Static Block 2. Value of j = "+j); } { System.out.println(" Instance Block 2. Value of i = "+i); method_1(); } public static void method_2(){ System.out.println(" Static method. "); }} The Output we get by executing this program will be Static Block 1. Value of j = 0 This is a java tricky interview question frequently asked in java interviews for the EXPERIENCED. The output will be like this because, when the java program is compiled and gets executed, then there are various steps followed for execution. And the steps are -
In above steps from 4 to 6, will be executed for EVERY object creation. If we create multiple objects then for every object these steps will be performed. Now from the above code, the execution will happen like this - 1. In the step of identification of static members. It is found that -
During identification, the JVM will assign the default value in the static int j variable. Then it is currently in the state of reading and indirectly writing. Because the original value is not assigned. 2. In the next step, it will execute the static block and assign the value in static variables.
3. Now it will execute the main method. In which it will create an object for the class InterviewBit. And then the execution of INSTANCES will happen. 4. Identify the instance variables and blocks from top to bottom.
Like a static variable, the instance variable also has been initialized with the default value 0 and will be in the state of reading and writing indirectly. 5. It will execute the instance methods and assign the original value to the instance variable.
6. And at the last step, the constructor will be invoked and the lines will be executed in the constructor. This is how the java program gets executed. |
|
| 19. |
In the given code below, what is the significance of ... ? |
|
Answer» public void fooBarMethod(String... variables){ // method CODE}
|
|
| 20. |
Why is synchronization necessary? Explain with the help of a relevant example. |
|
Answer» Concurrent execution of different processes is made possible by synchronization. When a particular resource is shared between many THREADS, situations may arise in which multiple threads require the same shared resource. Synchronization assists in resolving the issue and the resource is shared by a single thread at a time. Let’s take an example to understand it more clearly. For example, you have a URL and you have to find out the number of requests made to it. Two simultaneous requests can MAKE the count erratic. No synchronization: package anonymous;public class Counting { private int increase_counter; public int increase() { increase_counter = increase_counter + 1; return increase_counter; }}If a thread Thread1 views the count as 10, it will be INCREASED by 1 to 11. Simultaneously, if another thread Thread2 views the count as 10, it will be increased by 1 to 11. Thus, inconsistency in count values takes place because the EXPECTED final value is 12 but the actual final value we get will be 11. Now, the function increase() is made synchronized so that simultaneous accessing cannot take place. With synchronization: package anonymous;public class Counting { private int increase_counter; public synchronized int increase() { increase_counter = increase_counter + 1; return increase_counter; }}If a thread Thread1 views the count as 10, it will be increased by 1 to 11, then the thread Thread2 will VIEW the count as 11, it will be increased by 1 to 12. Thus, consistency in count values takes place. |
|
| 21. |
Is exceeding the memory limit possible in a program despite having a garbage collector? |
|
Answer» Yes, it is possible for the program to go out of MEMORY in spite of the presence of a garbage collector. Garbage collection assists in recognizing and eliminating those objects which are not required in the program anymore, in order to free up the resources used by them. In a program, if an object is unreachable, then the execution of garbage collection takes place with respect to that object. If the amount of memory required for creating a NEW object is not SUFFICIENT, then memory is RELEASED for those objects which are no longer in the scope with the HELP of a garbage collector. The memory limit is exceeded for the program when the memory released is not enough for creating new objects. Moreover, exhaustion of the heap memory takes place if objects are created in such a manner that they remain in the scope and consume memory. The developer should make sure to dereference the object after its work is accomplished. Although the garbage collector endeavors its level best to reclaim memory as much as possible, memory limits can still be exceeded. Let’s take a look at the following example: List<String> example = new LinkedList<String>();while(true){example.add(new String("Memory Limit Exceeded"));} |
|
| 22. |
How is the ‘new’ operator different from the ‘newInstance()’ operator in java? |
|
Answer» Both ‘new’ and ‘newInstance()’ operators are USED to creating objects. The difference is- that when we ALREADY know the class name for which we have to create the object then we use a new OPERATOR. But suppose we don’t know the class name for which we need to create the object, Or we get the class name from the command line argument, or the database, or the file. Then in that CASE we use the ‘newInstance()’ operator. The ‘newInstance()’ keyword throws an exception that we need to HANDLE. It is because there are chances that the class definition doesn’t exist, and we get the class name from runtime. So it will throw an exception. |
|
| 23. |
How is the creation of a String using new() different from that of a literal? |
|
Answer» When a String is formed as a literal with the assistance of an ASSIGNMENT operator, it makes its way into the String constant pool so that String Interning can take place. This same object in the HEAP will be referenced by a different String if the content is the same for both of them. public bool checking() {String first = "InterviewBit";String second = "InterviewBit";if (first == second) return TRUE;else return false;}The checking() function will return true as the same content is referenced by both the VARIABLES. Conversely, when a String formation takes place with the HELP of a new() operator, interning does not take place. The object gets created in the heap memory even if the same content object is present. public bool checking() {String first = new String("InterviewBit");String second = new String("InterviewBit");if (first == second) return true;else return false;}The checking() function will return false as the same content is not referenced by both the variables. |
|
| 24. |
What are Composition and Aggregation? State the difference. |
|
Answer» Composition, and Aggregation help to build (Has - A - Relationship) between classes and objects. But both are not the same in the END. Let’s understand with the help of an EXAMPLE.
|
|
| 25. |
What is the difference between ‘>>’ and ‘>>>’ operators in java? |
|
Answer» These 2 are the BITWISE right shift OPERATORS. Although both operators LOOK similar. But there is a minimal difference between these two right shift operators.
Example- Num1 = 8, Num2 = -8. So the binary form of these numbers are - Num1 = 00000000 00000000 00000000 00001000 ‘>>’ Operator : 8 >> 1 (Shift by one bit) : Num1 = 00000000 00000000 00000000 00000100 ‘>>>’ Operator : 8 >>> 1 (Shift by one bit) = Num1 = 00000000 00000000 00000000 00000100 |
|
| 26. |
Although inheritance is a popular OOPs concept, it is less advantageous than composition. Explain. |
|
Answer» Inheritance lags BEHIND composition in the following scenarios:
Let’s take an example: package comparison;PUBLIC class Top {public int start() { return 0;}}class Bottom extends Top { public int stop() { return 0; }}In the above example, inheritance is FOLLOWED. Now, some modifications are done to the Top class like this: public class Top { public int start() { return 0; } public void stop() { }}If the new implementation of the Top class is followed, a compile-time error is bound to occur in the Bottom class. Incompatible return type is there for the Top.stop() function. Changes have to be made to either the Top or the Bottom class to ensure compatibility. However, the composition technique can be utilized to solve the given problem: class Bottom { Top par = new Top(); public int stop() { par.start(); par.stop(); return 0; }} |
|