Sun. Dec 22nd, 2024
Java-Training-in-Chandigarh-Mohali

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?

5. Tell us something about the JIT compiler.

  1. 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
  2. The compiler is particularly a convertor of source code to machine-executable code
  3. Working :

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?

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.

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?

17. How would you differentiate between a String, StringBuffer, and a StringBuilder?

18. What are the reasons behind making strings immutable in Java?

A String is made immutable due to the following reasons:

19. What makes a HashSet different from a TreeSet?

HashSet and TreeSet are not synchronized and ensure that duplicates are not present..

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?

Dis-advantages of using reflection:

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:

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:

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

Leave a Reply

Your email address will not be published. Required fields are marked *