Skip to main content

Command Palette

Search for a command to run...

Java interview

Updated
12 min read

Core Java

What is Abstraction, and how many ways to achieve. ?

→ In Java, abstraction refers to the concept of hiding implementation details and showing only essential features of an object. This is typically achieved through abstract classes and interfaces, allowing for the creation of generalized types and behaviors without specifying all the implementation details.

What is an Interface?

→ An interface in Java defines a contract for classes to implement, specifying abstract methods, constants, and optionally default and static methods.

→ It allows for achieving abstraction, polymorphism, and multiple inheritance-like behavior by enabling classes to inherit from multiple interfaces.

Diff b/w Abstraction and Interface?

→ Abstraction in Java involves hiding complex implementation details and showing only the essential features of an object or system. It simplifies complexity by focusing on what an object does rather than how it does it.

→ Interface, on the other hand, is a blueprint of methods that a class must implement. It defines a contract for classes, specifying what methods a class should have without providing the implementation details. Interfaces allow for achieving abstraction and enabling multiple inheritance-like behavior in Java.

→ Java 8 introduced major enhancements like Lambda Expressions, Stream API, new Date/Time API, and default methods in interfaces. These features made Java more functional, concise, and powerful for modern application development

  1. Lambda Expressions

    • Enable functional programming in Java.

    • Provide a concise way to implement functional interfaces (interfaces with a single abstract method).

    • Example:

      java

      List<String> names = Arrays.asList("Mohan", "Krishna", "Java");
      names.forEach(n -> System.out.println(n));
      
  2. Stream API

    • Introduced for processing collections in a functional style.

    • Supports operations like map, filter, reduce, collect.

    • Example:

      java

      List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
      int sum = numbers.stream()
                       .filter(n -> n % 2 == 0)
                       .mapToInt(n -> n)
                       .sum();
      
  3. Optional Class

    • Helps avoid NullPointerException.

    • Represents a value that may or may not be present.

    • Example:

      java

      Optional<String> name = Optional.ofNullable(null);
      System.out.println(name.orElse("Default"));
      
  4. Method References

    • Shorthand for calling methods using ::.

    • Example:

      java

      names.forEach(System.out::println);
      
  5. Functional Interfaces:

    • Functional interfaces are interfaces that have exactly one abstract method (SAM - Single Abstract Method).

    • Java 8 introduced the @FunctionalInterface annotation to mark interfaces as functional interfaces, which allows them to be used with lambda expressions and method references.

    • Functional interfaces enable functional programming concepts in Java, such as passing behavior around as method arguments or return values.

  6. Default Methods:

    • Default methods allow interfaces to have methods with a default implementation.

    • These methods can be overridden by implementing classes but provide a default behavior if not overridden.

    • They were introduced to support backward compatibility with existing codebases while adding new functionality to interfaces.

  7. Static Methods:

    • Java 8 also introduced static methods in interfaces.

    • These methods are declared using the static keyword and can be called directly using the interface name without requiring an instance of the interface.

    • Static methods in interfaces provide utility methods that are associated with the interface itself rather than any specific instance of the implementing class.

Inheritance in Java and its types of inheritance?

→ In Java, inheritance is a mechanism where one class (subclass or derived class) inherits the properties and behaviors (methods and fields) of another class (superclass or base class). This promotes code reuse and establishes a hierarchical relationship between classes.

Types of Inheritance in Java:

  1. Single Inheritance.

  2. Multilevel Inheritance.

  3. Hierarchical Inheritance.

  4. Hybrid Inheritance.

  5. Multiple Inheritance (through Interfaces):

    • Java supports multiple inheritance of types, but not of implementation (i.e., a class can implement multiple interfaces).

    • Interfaces allow a class to inherit from multiple sources by specifying a contract that the class must implement.

What are Strings in Java, and how many ways to create a string?

→ In Java, a string is a sequence of characters used to represent text. Strings in Java are objects of the class java.lang.String, which is a built-in class in Java and is immutable, meaning once created, its value cannot be changed.

Ways to Create a String in Java:

  1. Using String Literal:

    • String literals are created by enclosing the text within double quotes (").
  1. Using thenew Keyword (String Object):
  • Strings can also be created using the new keyword, which explicitly creates a new String object

    1. Using String Constructor:
  • Strings can be created using the String class constructors, which provide various ways to initialize strings from arrays of characters, bytes, or other strings

    1. Using String Concatenation:

    2. UsingStringBuilder or StringBuffer:

    3. UsingString.valueOf():

What is immutable?

→ In Java, "immutable" refers to an object whose state cannot be changed after it is created. Once an immutable object is instantiated with a certain value, that value cannot be modified. This property ensures that the object's state remains consistent and predictable throughout its lifetime, making immutable objects thread-safe and simplifying concurrent programming. Examples include the String class and wrapper classes for primitive types (Integer, Double, etc.)

Collections?

→ In Java, collections are containers that hold multiple elements in a structured way. They include lists, sets, maps, and queues, providing ways to store, manipulate, and retrieve data efficiently. These collections are essential for managing and organizing data in Java applications.

Diff b/w ArrayList & Linked List?

→ ArrayList:

  • Implemented as a resizable array, providing fast access to elements by index (O(1) complexity).

  • Slower for inserting and deleting elements in the middle (O(n) complexity) due to shifting elements.

  • Requires less memory overhead per element compared to LinkedList.

  • Suitable for scenarios where random access and iteration are frequent and the list size is known or stable.

  • Example usage includes storing and accessing data where indexed access is important, like database query results.

→ LinkedList:

  • Implemented as a doubly linked list, offering fast insertion and deletion operations (O(1) complexity) at the beginning or middle of the list.

  • Slower for random access to elements (O(n) complexity) because it requires traversing from the head or tail.

  • Requires more memory overhead per element due to storing next and previous references.

  • Ideal for scenarios where frequent insertion or deletion operations are performed, especially in large data sets.

  • Example usage includes implementing queues, stacks, or managing data with frequent changes in order.

Multithreading and thread life cycle?

  1. Multithreading:

    • Multithreading refers to the concurrent execution of multiple threads within a single process.

    • Threads are lightweight processes that enable applications to perform multiple tasks simultaneously, leveraging the CPU efficiently.

  2. Thread Lifecycle:

    • New: A thread is in this state when an instance of Thread class is created but start() method is not invoked yet.

    • Runnable: After invoking start() method, the thread becomes runnable and can be scheduled to run by the operating system.

    • Running: The thread is executing its task.

    • Blocked: A thread can enter this state while waiting for a resource (e.g., I/O operation, synchronization lock).

    • Waiting: A thread can enter this state by invoking wait() method, awaiting notification from another thread.

    • Timed Waiting: A thread enters this state by invoking sleep() method or join() method with a timeout.

    • Terminated: A thread exits its execution when its run() method completes or stop() method is invoked (which is deprecated).

Comparable and Comparator interface?

→ Comparable is used to define the natural ordering of objects within a class, while Comparator is used to define custom sorting logic externally. Both interfaces are essential when sorting user-defined objects in Java.

Serialization?

→ Serialization is the process of converting an object into a byte stream so it can be stored or transmitted. Classes must implement Serializable, and deserialization reconstructs the object. It’s widely used in persistence and distributed systems.

Serial version, which is usually used in serialization?

serialVersionUID It is a unique identifier used in serialization to ensure class compatibility during deserialization

How to monitor Spring-boot application?

→ To monitor a Spring Boot application, use Spring Boot Actuator for built-in metrics and health checks. Configure Micrometer to export metrics to a monitoring system like Prometheus. Set up logging and alerting for critical metrics, and consider tools like Zipkin for distributed tracing in microservices architectures. Regularly review metrics and logs to ensure application health and performance.

How to we check the logs?

→ To check logs in a Spring Boot application:

  1. Locate Log Files: Find log files in the logs directory of your application or as configured.

  2. View Logs: Use a text editor, terminal commands (tail, cat), or IDE log viewers to read logs.

  3. Logging Configuration: Configure log file path and levels (INFO, DEBUG, WARN, ERROR) in application.properties or application.yml.

  4. Monitor: Regularly review logs for application health, errors, and troubleshooting.

Vertical scaling and horizontal scaling?

→ Vertical Scaling (Scaling Up):

  • Definition: Increasing the capacity of a single server by adding more resources like CPU, RAM, or storage.

  • Advantages: Simplifies management, good for applications with predictable growth.

  • Disadvantages: Limited by hardware constraints, potential downtime during upgrades.

→ Horizontal Scaling (Scaling Out):

  • Definition: Adding more servers to distribute the load across multiple machines.

  • Advantages: Improves fault tolerance, handles increased traffic well, cost-effective for large-scale applications.

  • Disadvantages: Adds complexity in management and data consistency across servers.

Explain when should go for application.properties, when should go for application.yml?

  • application.properties: Use .properties format for straightforward key-value pairs and when you prefer simplicity and familiarity with Java properties files.

  • application.yml: Use .yml format for more complex configurations, hierarchical structures, or when you prefer a more human-readable and expressive syntax with YAML. It's especially useful for configurations involving nested data or lists.

Explain what is api-gateway in micro-services?

→ An API gateway in microservices is a server that acts as an entry point into a microservices architecture. It acts as a single point of entry for all client requests, handling tasks such as routing, authentication, load balancing, and caching. The API gateway helps to simplify the client-side experience by providing a unified interface to interact with various microservices behind the scenes. This approach enhances security, scalability, and manageability of microservices-based applications.

  • How servcies are communicate each other? (Eureka)

    → In a microservices architecture using Eureka (a service registry), services communicate with each other through a process known as service discovery:

    1. Registration: Each microservice registers itself with Eureka when it starts up. It tells Eureka its network location (IP address and port) and any other metadata.

    2. Discovery: When one microservice needs to communicate with another, it asks Eureka for the network location of the target microservice.

    3. Communication: Armed with the network location obtained from Eureka, the calling microservice can then directly communicate with the target microservice.

How do achieve loose coupling b/w application or two services?

→ By using interfaces and dependency injection, communicating via APIs or message queues, externalizing configurations, and defining clear contracts with versioning. This ensures services can evolve independently without breaking each other.

What do JRE, JDK, and JVM imply?

→ JVM (Java Virtual Machine) provides a runtime environment for codes needed to be executed, while JRE (Java Runtime Environment) can be referred to as a collection of whiles required during runtime by JVM. JDK (Java Development Kit is ultimately used for writing and executing a program. It features JRE alongside certain development tools.

What shall be the use of composition?

→ The composition can be used for holding the reference of one class within another class. In this situation, the contained object is not able to exist without the class that contains it, and it subsequently is a type of aggregation.

Are there any differences between Stack and Heap memory?

→ There are fundamental differences between Stack and Heap memory. Stack Memory is typically used for storing local variables and the method execution order. Meanwhile, Heap memory stores objects securely. Once both these types of memories store information, dynamic memory reallocation and allocation are used.

What is a Copy Constructor in Java?

→ In Java, a Copy Constructor is the constructor responsible for initialising one object through a second object belonging to the same class.

What is a marker interface?

→ In Java, any empty interface is known as a Marker interface. Well-known examples of a Marker Interface are Cloneable and Serializable.

What does the final keyword mean in Java?

→ Variable: Value can't be changed.

→ Method: Can't be overridden.

→ Class: Can't be subclassed

What is the difference between Stack and Heap memory?

→ Stack: Stores method calls and local variables. Memory is automatically managed.

→ Heap: Stores objects and class instances. Managed by Garbage Collector.

What is the purpose of the finalize() method?

→ It's called by the Garbage Collector before destroying an object. Rarely used now due to unpredictability.

What are Lambda Expressions?

→ A concise way to represent anonymous functions. Syntax: (parameters) -> expression

What is the Stream API?

→ A powerful tool for processing collections in a functional style. Supports operations like filter, map, reduce.

What is the difference between wait() and sleep()?

→ wait(): Releases the lock and waits for notify()

→ sleep(): Pauses thread but retains the lock.

How can we consume the application.properties values in class?

→ Use @Value for single values.

→ Use @ConfigurationProperties for structured groups of values.

→ Use Environment when you need dynamic lookups.