Core Java Interview Questions and Answers

Back End Interview Questions for Freshers

Java Interview Questions and Answers for Freshers

1. What is Java?

Java is a high-level, object-oriented programming language and platform that enables developers to create robust, scalable, and secure applications. It's designed to be platform-independent, allowing Java code to run on any device supporting a Java Virtual Machine (JVM).

Java key features include:

  • Platform independence
  • Object-oriented
  • Simple and familiar syntax
  • Robust security

2. What is JDK?

JDK (Java Development Kit) is a software development kit that provides a set of tools and libraries for developing, testing, and running Java applications

JDK allows developers to:

  1. Write Java code
  2. Compile Java code into bytecode
  3. Run and test Java applications
  4. Debug Java programs

3. What is JVM?

Java Virtual Machine (JVM) is a software program that runs Java bytecode on a computer. It's the runtime environment for Java, allowing Java code to execute on any device supporting JVM.

4. What are the Features of JVM?

  1. Platform independence: JVM enables Java code to run on any platform (Windows, macOS, Linux, etc.).
  2. Bytecode interpretation: JVM interprets Java bytecode (.class files) into machine-specific instructions.
  3. Memory management: JVM manages memory allocation and deallocation for Java applications.
  4. Security: JVM provides a sandboxed environment, ensuring Java code runs securely.
  5. Dynamic loading: JVM loads classes and libraries dynamically, as needed.

5. What is JRE?

Java Runtime Environment (JRE) is a software package that provides the libraries, frameworks, and tools necessary to run Java applications. It's the runtime environment for Java, allowing Java bytecode to execute on a computer.

6. Difference between String, String Builder, and String Buffer.

  • In Java, a String is immutable, meaning its value cannot be changed after creation. StringBuilder and StringBuffer, on the other hand, are mutable and allow for dynamic modification of the content.
  • StringBuilder being non-thread-safe and more efficient, while StringBuffer is thread-safe but relatively slower.

7. Difference between Default and Protected access specifiers.

  • Default: Methods and variables declared in a class without any access specifiers are called default.
  • Default members in Class A are visible to the other classes which are inside the package and invisible to the classes which are outside the package.
  • Protected: Protected is the same as Default but if a class extends then it is visible even if it is outside the package.

8. Difference between Abstract class and Interface.

  • An abstract class in Java can have both abstract and concrete methods, and it allows for the use of fields (variables).
  • On the other hand, an interface can only declare abstract methods, and all fields are implicitly public, static, and final.
  • Additionally, a class can implement multiple interfaces, but it can extend only one abstract class.
Java Interview Questions for Freshers

9. What is the meaning of Collections in Java?

  • "Collections" refers to a framework that provides a set of classes and interfaces for managing and manipulating groups of objects.
  • It includes interfaces like List, Set, and Map, along with their various implementing classes, offering a standardized way to work with collections of data, making it easier to handle, store, and process groups of objects.

10. Explain about Map and its types.

A Map is an interface that represents a collection of key-value pairs, where each key is associated with exactly one value.

  • HashMap
  • TreeMap
  • LinedHashMap

11. What are the types of Exceptions? Explain the hierarchy of Java Exception classes?

  • Checked Exception: The classes which directly inherit Throwable class except RuntimeException and Error are known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at compile-time.
  • Unchecked Exception:The classes which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

    Hierarchy of Java Exception classes:

    The root class for all exceptions in Java is java.lang.Throwable. It has two main subclasses:

  • Error: Represents serious, unrecoverable issues that are usually beyond the control of the application. Examples include OutOfMemoryError and StackOverflowError.

    Exception:

  • This is the superclass for all exceptions that represent exceptional conditions not related to errors.It further divides into two subclasses:
  • Checked Exceptions: Extend java.lang.Exception, excluding RuntimeException and its subclasses.
  • Unchecked Exceptions (Runtime Exceptions): Extend java.lang.RuntimeException.

12. What is difference between Heap and Stack Memory in java?

  • Java Heap Space: Java Heap space is used by java runtime to allocate memory to Objects and JRE classes. Whenever we create any object, it’s always created in the Heap space.
  • Java Stack Memory: Stack in java is a section of memory which contains methods, local variables and reference variables. Local variables are created in the stack.
  • Stack memory is always referenced in LIFO (Last-In-First-Out) order

13. What is JVM and is it platform independent?

  • The Java Virtual Machine (JVM) is an integral part of the Java Runtime Environment (JRE) and is responsible for executing Java bytecode.
  • It abstracts the underlying hardware and operating system details, providing a consistent environment for Java programs to run.
  • JVM allows Java programs to run on any device or platform that has a compatible JVM installed, ensuring "Write Once, Run Anywhere" capability.

14. What is JIT compiler in Java?

  • The JIT (Just-In-Time) compiler in Java is a component of the Java Virtual Machine (JVM) that dynamically translates Java byte code into native machine code during runtime.
  • This adaptive compilation process enhances the performance of Java programs by optimizing frequently executed code, contributing to improved execution speed while maintaining the platform independence provided by Java's byte code.

15. Can we import same package/class two times? Will the JVM load the package twice at runtime?

  • We can import the same package or same class multiple times. The JVM will internally load the class only once no matter how many times import the same class.
  • Nested inner classes are employed for improved code organization, encapsulation, and logical grouping of related classes.

16. Distinguish between static loading and dynamic class loading?

  • Static loading involves loading classes at compile-time, as seen in static nested classes.
  • Dynamic class loading occurs at runtime, allowing for flexibility in loading classes during program execution, exemplified by instances of non-static inner classes.
  • class TestClass {
    public static void main(String args[]) {
    TestClass tc = new TestClass();
    }
    }
  • Dynamic Class Loading: Loading classes use Class.forName() method. Dynamic class loading is done when the name of the class is not known at compile time.
  • Class.forName (String className);

17. Can you declare the main method as final?

  • The main method can be declared as final without causing a compilation error.
  • However, marking the main method as final is not necessary and doesn't affect the program's execution or behavior, as the JVM (Java Virtual Machine) still recognizes and executes the public static void main(String[] args) method irrespective of the final keyword.

18. What is the difference between the final method and abstract method?

  • The key distinction between a final method and an abstract method lies in their purpose and implementation.
  • On the other hand, an abstract method, marked with the abstract keyword, lacks an implementation in the declaring class.

19. The syntax of Java is based on which programming language?

  • The syntax of Java is primarily based on the syntax of the C and C++ programming languages. Java was designed to be familiar to C and C++ programmers, making it easier for developers with experience in those languages to transition to Java.
  • Java shares some syntax elements with other languages, such as Simula and Smalltalk.

20. What does ‘write once run anywhere’ mean in Java?

  • "Write once, run anywhere" in Java signifies that once a program is written and compiled into bytecode.
  • It can be executed on any device or platform with a compatible Java Virtual Machine, emphasizing Java's platform independence.
  • This is facilitated by the bytecode's interpretation by the JVM, abstracting the underlying system details.

21. What is Java programming used for? Explain its primary applications?

  • Java programming is widely used for developing versatile applications, including web applications, mobile applications (Android)
  • Enterprise-level server-side applications, and embedded systems, owing to its platform independence and extensive libraries.
  • It is also prevalent in building large-scale systems, such as banking applications and e-commerce platforms.

22. Is it possible for a class to extend itself?

  • No, it is not possible for a class to extend itself in Java.
  • Inheritance involves creating a new class that is a specialized version of an existing class, but a class cannot be its own superclass or subclass.

23. Is it possible to assign a superclass to a subclass in Java?

  • No, direct assignment of a superclass to a subclass in Java is not allowed.
  • While a subclass can be treated as its superclass through polymorphism, explicit casting is required for such assignments.

24. What is garbage collection in Java?

  • Garbage collection in Java is an automatic memory management process where the Java Virtual Machine (JVM) identifies and removes unreferenced objects from the heap memory.
  • It helps free up memory occupied by objects that are no longer accessible, preventing memory leaks and improving overall program efficiency.

25. What is inheritance in Java?

  • Inheritance is a mechanism that allows a class (subclass or derived class) to inherit the properties and behaviors (fields and methods) of another class (superclass or base class).
  • This promotes code reuse and establishes an "is-a" relationship between the subclass and superclass, enabling the subclass to access and extend the functionalities of the superclass.

26. What is polymorphism in Java?

  • Polymorphism in Java allows a method or class to take on multiple forms.
  • It includes compile-time polymorphism (method overloading) and runtime polymorphism (method overriding), enhancing code flexibility and readability.

27. What is encapsulation in Java?

  • Java encapsulation is a process that allows you to integrate the data variables and code and store them as a single thing.
  • It is like two different capsules of medicine are mixed together to create a new single capsule. This is the logic behind calling it encapsulation.

28. What is Java enum?

  • Enum in Java stands for enumeration. It is a data type that comes with a set of pre-defined constant values. These values are separated by a comma.
  • Enums enhance code readability and maintainability by providing a clear way to represent distinct values.
Java Interview Questions and Answers

29. Can you restrict an object from inheriting its subclass? If yes, how?

  • Yes, you can restrict a class from being inherited by using the final keyword in Java.
  • Declaring a class as final prevents the creation of subclasses.

30. What is the difference between heap memory and stack memory in Java?

  • The key difference between heap and stack memory lies in their purposes and lifetimes.
  • Heap memory is used for dynamic memory allocation, storing objects with a longer lifespan, while stack memory manages method execution and local variables with a limited scope, reclaimed when the method completes.

31. What is the difference between equals() method and equality (==) operator in Java?

  • The equals() method compares the content of objects, while the == operator checks for reference equality.
  • equals() is typically overridden for meaningful content comparison, whereas == checks if references point to the same object.

32. What are the roles of final, finally, and finalize keywords in Java?

Final

  • Its role is to execute
  • limitations or restrictions on classes, methods, or variables.

Finally

  • Its role is in exception handling.
  • Finally keyword runs the crucial code no matter whether the exception occurs or not.

Finalize

  • Used for processing clean up during garbage collection.

33. What is a ClassLoader in Java?

  • A ClassLoader is a subsystem responsible for dynamically loading Java classes into the Java Virtual Machine (JVM) at runtime
  • It locates and loads class files from the file system, network, or other sources, enabling the dynamic extension of a Java application.
  • ClassLoaders follow a hierarchical structure, with the Bootstrap ClassLoader at the top, followed by Extension and Application ClassLoaders.

34. What is the difference between ArrayList and LinkedList?

  • ArrayList uses a dynamic array, while LinkedList uses a doubly-linked list.
  • ArrayList is better for random access, while LinkedList is more efficient for frequent insertions and deletions.

35. Explain the difference between Set and List.

A Set is an unordered collection of unique elements, while a List is an ordered collection that allows duplicate elements.

36. What is the significance of the hashCode() and equals() methods in Java?

These methods are crucial for proper functioning in collections. hashCode() returns a hash code value for the object, and equals() checks if two objects are equal based on their content.

37. What is the Map interface, and name its primary implementing classes.

Map represents a collection of key-value pairs. Implementing classes include HashMap, TreeMap, and LinkedHashMap.

38. What is the difference between HashMap and HashTable?

HashMap is not synchronized, making it more efficient but not thread-safe. HashTable is synchronized, ensuring thread safety but with slightly lower performance.

39. Explain the Iterator interface in Java Collections.

Iterator is an interface that provides methods for iterating over a collection. It allows traversing elements in a collection one at a time.

40. What is the Collections class in Java?

The Collections class provides utility methods to perform operations on collections, such as sorting, searching, and shuffling.

41. What is the difference between Comparable and Comparator interfaces?

Comparable is used for natural ordering, and the object's class implements it. Comparator is a separate class that provides multiple sorting sequences.

42. How does the foreach loop work with collections in Java?

The foreach loop simplifies iteration through collections, allowing concise syntax for traversing elements without the need for explicit indices.

43. Can a method be overridden with a different return type?

Tricky part: No, it's not allowed. The return type in the overriding method must be the same or a subtype of the return type in the overridden method.

44. Explain the "diamond problem" in the context of multiple inheritance in Java.

Tricky part: Discuss how Java avoids the diamond problem by allowing interfaces to have default methods and how conflicts are resolved.

45. Why is the main method in Java declared as public static void?

Tricky part: Emphasize that the main method needs to be accessible from outside the class (public), can be called without creating an instance (static), and does not return any value (void).

Core Java Backend Interview Questions

46. How does the NullPointerException differ from the ArrayIndexOutOfBoundsException?

Tricky part: Highlight that a NullPointerException occurs when trying to access or invoke a method on an object that is null, while ArrayIndexOutOfBoundsException occurs when attempting to access an invalid index in an array.

47. Can you have a try block without a catch block in Java?

Tricky part: Yes, it's allowed to have a try block without a catch block, but it must be followed by either a finally block or both catch and finally blocks.

48. Can a static method be overridden in Java

Tricky part: No, static methods cannot be overridden in Java. They are associated with the class rather than an instance and are resolved at compile-time.