Java Interview Questions
1. Why is Java a platform independent language?
Java was designed to be an independent language on any software or hardware due to the fact that the compiler then gathers the code and then converts it into a platform-independent bytecode which can be run on multiple sites.
2. Why is Java not a pure object oriented language?
Java supports old data types like char, byte, float, int, short, double and long and thus it is not a fully object-oriented language.
3. Why does Java not make use of pointers, though they are used in C/ C++ ?
Pointers are quite difficult and not very safe to use by beginner programmers. Java focuses on the simplicity of the code, but usage of pointers can make it complicated. Pointer utilization may cause errors leading to compromised security.
Moreover, a certain level of abstraction is equipped by not including pointers. The usage of pointers can make the procedure of garbage collection quite slow.
4. Explain data encapsulation?
- It helps developers to follow standard procedure while developing a software by ensuring that each object is not dependent on any other objects by having its own methods and attributes.
- It is a concept of hiding the data attributes and their behaviors in a single unit.
- It is used for securing the private properties of an object and thus serves the aim of hiding the data.
5. Tell us something about the JIT compiler.
- JIT stands for Just-In-Time, which is used for enhancing the performance during run time. It does the crucial task of compiling the parts of byte code having similar functionality at the same time
- The compiler is particularly a convertor of source code to machine-executable code
- Working :
- The Java source code converted to byte occurs with the help of the javac compiler.
- The class files are loaded at run time by JVM, then these are converted to machine understandable code.
- When the JIT compiler is enabled, the JVM analyzes the method calls in the class files and compiles them to get more efficient and native code.
- JVM executes the optimized code directly. This increases the performance and speed of the execution.
6. What are infinite loops?
Infinite loops are those loops that run infinitely without any breaking conditions.
7. Briefly explain the concept of constructor overloading?
It is the process of creating multiple constructors in the class consisting of different constructor parameters but the same name. Depending upon the number of parameters and their similar types, separation of different types of constructors is done by the compiler.
8. Comment on method overloading and overriding?
When discussing Java, method overloading is made possible by introducing different methods in the same class consisting of the same name, but all the functions are different in number or type of parameters. It takes place inside a class and improves program readability.
Method overriding is the concept in which two methods having the same method signature are present in two different classes.
9. A single try block and multiple catch blocks can co-exist in a Java Program?
Absolutely, multiple catch blocks can exist but specific approaches should come before the general approach because only the first catch block satisfying the catch condition is executed.
10. Do final, finally and finalize keywords have the same function?
All three keywords have their own differences.
Finally: It is the block present in a program where all the codes written inside it get executed irrespective of any exceptions.
Final: The final keyword comes in handy If any restriction is required for classes, variables, or methods. Overriding of a final method is blocked by the use of the final keyword. The variable value becomes fixed.
Finalize: The finalize method is called so that the clean-up activity is implemented.
11. Can the static methods be overloaded?
Yes, There can be two or more static methods in a class with the same name but different parameters.
12. Can the static methods be overridden?
- No, static methods having the same signature are possible in the subclass but run time polymorphism can not take place in these cases.
- Overriding polymorphism takes place during the runtime, but the static methods are loaded and searched up at the compile time statically. Hence, these methods can’t be overridden
13. What is the main objective of garbage collection?
The main objective of this process is to free up the memory space occupied by the unnecessary objects during the Java program execution by deleting those unreachable objects.
- This ensures that the memory resource is used efficiently.
14. What part of memory – Stack or Heap – is cleaned in garbage collection process?
Heap
15. In Java, static as well as private method overriding is possible. Comment on the statement.
No, 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 procedure explained here is popularly known as method hiding, and overriding is certainly not possible. Only hiding can be facilitated and not overriding.
16. Explain the differences between interfaces and abstract classes?
- Variables can only be declared in the case of interfaces, whereas abstract classes can also have non-static and non-variables.
- Inheritance: Multiple inheritances are accepted by interfaces, but abstract classes do not promote it.
- Availability of methods: Only abstract methods are available in interfaces, however non-abstract methods can be presented along with abstract methods.
- Implementation: With the help of an abstract class, the implementation of an interface is easily possible. However, the converse is not true.
17. How would you differentiate between a String, StringBuffer, and a StringBuilder?
- Efficiency: working with a String is quite low. Though, StringBuilder is the fastest of all in performing operations. Speed of a StringBuffer is more than a String but less than a StringBuilder.
- Mutability: A String is immutable, however both the StringBuilder and StringBuffer are mutable.
- Thread-safe: In the case of a threaded environment, StringBuilder and StringBuffer are used whereas a String is not used
18. What are the reasons behind making strings immutable in Java?
A String is made immutable due to the following reasons:
- String Pool: Developers of Java were aware of the fact that String data type is going to be majorly used by the programmers and developers. Thus, They came up with the notion of using the String pool to store the String literals. They intended to decrease the temporary String object with the help of sharing. The sharing of the mutable structures between two distinct parties is not possible. So, immutable Java String helps in executing the concept of String Pool.
- Collections: In cases such as Hashtables and HashMaps, keys are String objects. If the String objects are not immutable, then it can get advanced during the period when it resides in the HashMaps.
19. What makes a HashSet different from a TreeSet?
HashSet and TreeSet are not synchronized and ensure that duplicates are not present..
- Complexity/ Performance: Adding, retrieving, and deleting elements, the time amortized complexity is O(1) for a HashSet but a bit higher for TreeSet and is equal to O(log n). Overall, HashSet is faster in comparison to TreeSet.
- Objects type: Heterogeneous objects can be stored with the help of HashSet. Runtime exception occurs while inserting heterogeneous objects or null objects in cases such as tree set.
- Implementation: The hash table is utilized for storing the elements in an unordered manner in cases such as Hashset, but TreeSet makes use of the red-black tree to store the material in a particular manner.
20. Why is the character array preferred over string for storing confidential information?
In Java, a string is basically immutable i.e. it cannot be further advanced. After its declaration, it continues to stay in the string pool until it is not removed in the form of garbage. To be brief, 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, risks of vital information being stolen for pursuing harmful activities by hackers or a memory dump being illegally accessed by them. Such risks can be eliminated by using mutable objects or structures like character arrays for storing any variable.
21. Why is the character array preferred over string for storing confidential information?
HashMap | HashTable |
---|---|
HashMap is not connected thereby making it better for non-threaded applications | HashTable is connected, leading to it being suitable for threaded applications. |
Only one null key is allowed but any number of null values. | This does not allow null in both keys or values |
Supports order of insertion by making use of its subclass LinkedHashMap. | Order of insertion is not guaranteed in HashTable |
22. What is the importance of reflection in Java?
- Reflection is best used for describing the inspection capability of a code on other code either of itself or of its system and modify it during runtime.
- The static typing system of Java doesn’t allow this method invocation unless the type of the object is known from before. This can be achieved using reflection which allows the code to scan the object and identify it.
Dis-advantages of using reflection:
- Slows the speed by three times than the direct method calls.
- Type safety — When a method is invoked via its reference wrongly using reflection, invocation fails at runtime as it is not detected at compile time.
- Traceability — Failing of reflective method is complex, because to find the root cause is very difficult due to a huge stack trace.
- Advisable to follow steps that don’t involve reflection and use this method as a last resort.
23. State the differences between constructor and method of a class in Java
Constructor | Method |
---|---|
Constructor is used for initializing the object state. | Method is used for exposing the object’s behavior |
It has no return type. | Method should always have a return type. Even if it does not return anything, the return type is void |
Constructor gets invoked implicitly. | Method has to be invoked on the object explicitly |
If the constructor is not defined, then a default constructor is provided by the java compiler | If a method is not defined, then the compiler does not provide it. |
The constructor name should be equal to the class name | The name of the method can have any name or have a class name too. |
A constructor cannot be marked as final because whenever a class is inherited. | A method can be defined as final but it cannot be overridden in its subclasses. |
Final variable instantiations are possible inside a constructor and the scope of this applies to the whole class and its objects. | A final variable if initialised inside a method ensures that the variable cant be changed only within the scope of that method. |
24. Java works as “pass by value” or “pass by reference” phenomenon?
Java always works as a “pass by value”. There is no term such as “pass by reference” in the language. But, 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.
25. Which among String or String Buffer should be preferred when there are lot of updates required to be done in the data?
StringBuffer is mutable and quite dynamic in nature whereas String is immutable. Every update of String creates a new String thereby putting excess pressure on the string pool with unnecessary objects. Thus, in cases where there are a lot of updates, it is always advised to use StringBuffer as it will reduce the overhead of the creation of multiple String objects in the string pool.
26. How to not allow serialization of attributes of a class in Java?
In order to achieve this, the attribute can be declared along with the usage of transient keyword as shown below:
publicclass
privatetransient String someInfo;
private String name;
privateint id;
// :
// Getters setters
// :
}
27. What happens if the static modifier is not included in the main method signature in Java?
There wouldn’t be any type of compilation error. But then the program is run, since the JVM can’t map the main method signature, the code throws “NoSuchMethodError” error at the runtime.
28. If there are multiple main methods inside one class in Java, what happens?
The program possibly cannot be compiled as the compiler says that the method has been already defined inside the class.
29. Briefly explain object cloning and how do you achieve it in Java?
It is best defined as the process of creating an exact copy of any object. In order to support this, a java class has to implement the Cloneable interface of java language package and override the clone() method provided by the Object class the syntax of which is:
protected Object clone() throws CloneNotSupportedException{
return (Object)super.clone();
}
30. Is it mandatory for a catch block to be followed after a try block?
No, it is not mandatory 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 there are more chances of being an exception, then they should be declared using the throws clause of the method.
31. Will the finally block get executed when the return statement is written at the end of try block and catch block as shown below?
publicintsomeMethod(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. The only case where the finally block is not executed is when it encounters the ‘System.exit()’ method anywhere in the try/catch block.
32. Can you call a constructor of a class inside another constructor?
Yes we can call a constructor of a class inside another constructor, the concept can be termed as constructor chaining and can be achieved.
33. Contiguous memory locations are usually used for storing actual values in an array but not in ArrayList. Why so?
In the case of ArrayList, data storing in the form of old data types is not possible. The data objects present in the ArrayList have references to the objects which are located at various sites in the memory. Thus, storing of actual objects data types takes place in various locations of memory.
However, the same does not apply to the arrays.
Advanced
34. Although inheritance is a popular OOPs concept, it is less advantageous than composition. Explain.
Inheritance lags behind composition in the following scenarios:
- Multiple-inheritance is not possible in Java. Classes can only extend from one superclass. In cases where multiple functionalities are required, for example – to read and write information into the file, the pattern of composition is preferred. The writer, as well as reader functionalities, can be made use of by considering them as the private members
- Composition assists in attaining high flexibility and prevents breaking of encapsulation
- Unit testing is possible with composition and not inheritance. When a developer wants to test a class composing a different class, then Mock Object can be created for signifying the composed class to facilitate testing. This technique is not possible with the help of inheritance as the derived class cannot be tested without the help of the superclass in inheritance.
- The loosely coupled nature of composition is preferable over the tightly coupled nature of inheritance
35. How is the creation of a String using new() different from that of a literal?
When a String is formed as a literal with the assistance of an operator, it makes its way into the String constant pool so that String Interning can take place. This same object in the pile will be referenced by a distant String if the content is the same.
public bool checking() {
String first = “ThinkNext”;
String second = “ThinkNext”;
if (first == second)
return true;
else
return false;
}
The checking() function will return true as the same content is referenced by both the variables.
36. Why is synchronization necessary? Explain
Concurrent execution of different procedures is made possible by synchronization. When a specific resource is shared between many threads, situations may rise in which multiple threads require the same resource.
Synchronization in resolving the matter and the resource is shared by a single thread at a time. Let’s take an example to understand it more clearly.
37. Can you explain the Java thread lifecycle?
Java thread life cycle is as follows:
- New – When the instance of the thread is created and the method has not been invoked, the thread is considered to be alive.
- Runnable – Once the method is invoked, before the method is called by JVM, the thread is said to be in RUNNABLE state.
- Running – When the run method has been invoked and the thread starts its execution, the thread is said to be in a RUNNING state.
- Non-Runnable – When the thread is not able to run despite the fact of its aliveness, the thread is said to be in a NON-RUNNABLE state. Ideally, after some time of its aliveness, the thread should go to a runnable state.
- Terminated – Once the run method execution is completed, the thread is said to enter the TERMINATED step is executed.
38. Is it possible to import the same class or package twice in Java and what happens to it during runtime?
It is possible to import a class or package more than once, however, it is unnecessary because the JVM internally loads the class only once.
39. In case a package has sub packages, will it suffice to import only the main package?
This is a big NO. We need to understand that the importing of the sub-packages of a package needs to be done uniquely. Importing the parent package only results in the import of the classes within it and not the contents.
40. Will the finally block be executed if the code things.exit is written at the end of try block?
NO. The control of the program post things.exit is immediately gone and the program gets executed which is why the finally block never gets executed.
41. What do you understand by marker interfaces in Java?
Marker interfaces, also known as tagging interfaces are those interfaces that have no methods and constants explained in them. They are there for helping the compiler and JVM to get run time-related information regarding the objects.
42. What tools are used for analyzing Garbage Collection logs?
Tools used for analyzing Garbage collection logs are IBM Pattern Modeling and Analysis Tool.
43. What are different regions in JVM memory?
Different regions in JVM memory are
- Survivor 1
- Survivor 2
- Old Generation
- Eden
- Perm Generation