Tuesday, May 20, 2025

Core Java Interview Questions

 Q1. Can the 'this' keyword be equal to null?

Ans. No, the 'this' keyword cannot be equal to null.

The 'this' keyword refers to the current instance of a class.

It is used to access the members of the current object.

Since 'this' refers to an object, it cannot be null. 

Q2. What is C code in Java?

Ans. C code in Java refers to the use of the Java Native Interface (JNI) to incorporate C code into Java programs.

C code in Java is typically used when performance optimization or low-level system access is required.

JNI allows Java programs to call C functions and use C libraries.

C code can be written separately and compiled into a shared library, which is then loaded and used by Java code.

JNI provides a way to pass data between Java and C, handle exceptions, and manage memory.

Example: Using JNI to access a C library for image processing in a Java application

Q3. What are the different Spring bean scopes?

Ans. Spring bean scope defines the lifecycle and visibility of a bean in the Spring container.

Singleton scope: Only one instance of the bean is created and shared across the application.

Prototype scope: A new instance of the bean is created every time it is requested.

Request scope: A new instance of the bean is created for each HTTP request.

Session scope: A new instance of the bean is created for each HTTP session.

Global session scope: Similar to session scope, but for global HTTP sessions in a Portlet context.

Q4. What is the difference between Spring IOC and Dependency Injection?

Ans. Spring IOC is a container that manages the lifecycle of Java objects. Dependency Injection is a design pattern that allows objects to be loosely coupled.

Spring IOC is a container that manages the creation and destruction of objects.

Dependency Injection is a design pattern that allows objects to be loosely coupled.

Spring IOC uses Dependency Injection to inject dependencies into objects.

Dependency Injection can be implemented without using Spring IOC.

Q6. What is the difference between the Runnable and Callable interfaces?

Ans. Runnable interface is used for running a task, while Callable interface is used for returning a result after running a task.

Runnable interface has a run() method that does not return any value. 

Callable interface has a call() method that returns a value. 

Callable interface can throw an exception while Runnable interface cannot. 

Callable interface can be used with ExecutorService to submit tasks and get results.

Example of Runnable: Thread t = new Thread(new Runnable() { public void run() { //code here } });

Example of Callable: ExecutorService executor = Executors.newSingleThreadExecutor(); Future<String> future = executor.submit(new Callable<String>() { public String call() { //code here return result; } });

Q7. What does the @SpringBootApplication annotation do?

Ans. @SpringBootApplication is a Spring Boot annotation that enables auto-configuration and component scanning.

Enables auto-configuration of the Spring application context.

Enables component scanning for beans.

Provides a convenient shortcut for @Configuration, @EnableAutoConfiguration, and @ComponentScan annotations.

Can be used as a single entry point for the Spring Boot application.

Q8. How can you print even and odd numbers in increasing order using two threads in Java?

Ans. Use two threads to print even and odd numbers in increasing order.

Create two threads, one for printing even numbers and one for printing odd numbers.

Use a shared variable to keep track of the current number to be printed.

Synchronize access to the shared variable to ensure correct ordering of numbers.

Use a loop in each thread to print the next number and update the shared variable.

Q9. What is a constructor?

Ans. A constructor is a special method in a class that is automatically called when an instance of the class is created.

Constructors have the same name as the class they belong to.

They can be used to initialize the object's state or perform any necessary setup.

Constructors do not have a return type.

Example: public class Person { public Person() { // constructor code here } }

Q10. Explain Dependency Injection in Spring Boot.

Ans. Dependency Injection in Spring Boot is a design pattern that allows for better code management and testing by injecting dependencies.

Promotes loose coupling between components.

Facilitates easier unit testing by allowing mock dependencies.

Implemented using annotations like @Autowired, @Component, @Service.

Example: A service class can be injected into a controller using @Autowired.

Spring manages the lifecycle of the injected beans.

Q11. List the features of Java 8 and their use cases.

Ans. Java 8 introduced several new features including lambda expressions, streams, and functional interfaces.

Lambda expressions: Allow for more concise and readable code by enabling functional programming.

Streams: Provide a way to work with collections of objects in a more functional style.

Functional interfaces: Interfaces with a single abstract method, used to enable lambda expressions.

Optional class: Helps to avoid null pointer exceptions by wrapping a value that may or may not be present.

Default methods: Allow interfaces to have method implementations, reducing the need for abstract classes.

Q12. What is the purpose of using default methods in Java 8?

Ans. Default methods in Java 8 allow interfaces to have method implementations, enhancing flexibility and backward compatibility.

Enable adding new methods to interfaces without breaking existing implementations.

Facilitate multiple inheritance of behavior by allowing classes to inherit default methods from multiple interfaces.

Example: 'default void myMethod() { System.out.println("Default Method"); }' in an interface.

Support for functional programming by allowing interfaces to have behavior.

Help in maintaining legacy code while introducing new features.

Q13. What is CompletableFuture?

Ans. completableFuture is a class in Java that represents a future result of an asynchronous computation.

It is used for asynchronous programming in Java.

It can be used to chain multiple asynchronous operations.

It supports callbacks and combinators.

It can handle exceptions and timeouts.

Example: CompletableFuture.supplyAsync(() -> "Hello").thenApply(s -> s + " World").thenAccept(System.out::println);

Q14. Explain what Spring Sleuth is.

Ans. Spring Sleuth is a distributed tracing solution for Spring applications, enabling monitoring and debugging of microservices.

Integrates with Spring Cloud to provide tracing capabilities.

Automatically adds trace and span IDs to logs for better correlation.

Supports various backends like Zipkin and Brave for visualization.

Helps in identifying performance bottlenecks in microservices.

Example: If a request takes too long, Sleuth can trace the path through services to find the delay.

Q15. What is the difference between @Controller and @RestController annotations?

Ans. The @Controller annotation is used to create a controller class in Spring MVC, while @RestController is used to create RESTful web services.

The @Controller annotation is used to create a controller class in Spring MVC, which is used to handle traditional web requests.

The @RestController annotation is used to create RESTful web services, which return data in JSON or XML format.

The @RestController annotation is a specialized version of the @Controller annotation that includes the @ResponseBody annotation by default.

Q16. What is Component Scan?

Ans. Component Scan is a Spring framework feature that automatically detects and registers beans in the application context.

It uses annotations like @Component, @Service, @Repository, and @Controller to identify beans.

Configured via @ComponentScan annotation in a configuration class.

Can specify base packages to limit the scan, e.g., @ComponentScan(basePackages = "com.example")

Supports filtering to include or exclude certain classes using @Filter.

Helps in reducing boilerplate code by eliminating manual bean registration.

Q17. Why do we have @functionalInterface if we can make any interface a functional interface if it already has one abstract method?

Ans. Functional interfaces provide clarity and enforce single abstract method constraint.

Functional interfaces provide clarity to developers by explicitly indicating that the interface is intended to be used as a functional interface.

Using @FunctionalInterface annotation helps enforce the single abstract method constraint, preventing accidental addition of more abstract methods.

It also allows the compiler to perform additional checks to ensure that the interface meets the requirements of a functional interface. 

Examples of functional interfaces in Java include Runnable, Callable, and ActionListener.

Q18. How do you monitor Java applications using New Relic?

Ans. Monitoring Java applications with New Relic involves setting up agents and configuring alerts.

Install New Relic Java agent in the application server. 

Configure New Relic settings in the newrelic.yml file

Set up custom dashboards and alerts in New Relic Insights.

Monitor application performance metrics like response time, throughput, and error rate.

Q19. What is the Front Controller in Spring MVC?

Ans. Front Controller in Spring MVC is a design pattern that handles all requests and acts as a central point of control.

Front Controller is a servlet in Spring MVC that receives all requests and then dispatches them to the appropriate handlers.

It helps in centralizing request handling logic, improving code organization and reducing duplication.

Front Controller can perform tasks like authentication, logging, exception handling, and more before passing the request 

to the actual handler.

Example: DispatcherServlet in Spring MVC acts as the Front Controller

Q20. What is the difference between intermediate and terminal operations in streams?

Ans. Intermediate operations return a stream and do not produce a result, while terminal operations produce a result.

Intermediate operations are lazy and do not execute until a terminal operation is called.

Examples of intermediate operations include filter(), map(), and sorted()

Examples of terminal operations include forEach(), reduce(), and collect()

Terminal operations are eager and execute immediately.

Q21. Define Functional interfaces.

Ans. Functional interfaces are interfaces with a single abstract method, enabling lambda expressions in Java.

A functional interface can have multiple default or static methods.

It is annotated with @FunctionalInterface for clarity.

Example: Runnable (void run()) and Comparator (int compare(T o1, T o2)). 

They enable functional programming features in Java, like passing behavior as parameters.

Q22. What are Spring Actuators?

Ans. Spring actuators are devices that use the force generated by a spring to move or control a mechanism.

Spring actuators convert the potential energy stored in a spring into mechanical motion. 

They are commonly used in various applications such as valves, switches, and automotive systems.

Examples include spring return pneumatic actuators and spring-loaded safety valves.

Q23. Which Java framework are you most familiar with?

Ans. I am most familiar with the Spring framework, known for its comprehensive features for building Java applications.

Dependency Injection: Spring's core feature that promotes loose coupling. Example: Using @Autowired to inject beans.

Aspect-Oriented Programming: Allows separation of cross-cutting concerns. Example: Using @Aspect for logging.

Spring Boot: Simplifies the setup of new applications with embedded servers. Example: Creating a REST API with minimal configuration.

Spring MVC: A framework for building web applications. Example: Using @Controller and @RequestMapping for handling requests.

Integration with databases: Spring Data simplifies database access. Example: Using Spring Data JPA for ORM.

Q24. Tell me about Spring annotations.

Ans. Spring annotations are used to provide metadata to Spring framework classes and components.

Annotations are used to configure Spring beans, dependency injection, AOP, and more

Examples include @Component, @Autowired, @RequestMapping, @Service, @Repository

Annotations help in reducing XML configuration and make code more readable and maintainable.

Q25. What are the differences between Views and ViewGroups in Android?

Ans. Groups and View Groups are components of Android UI that help in organizing and displaying UI elements.

View Groups are containers that hold other UI elements, such as LinearLayout, RelativeLayout, etc. 

Groups are a type of View Group that allow for the creation of complex layouts by grouping multiple UI elements together, such as RadioGroup, TableLayout, etc. 

Both Groups and View Groups are used to organize and display UI elements in a structured manner.

Q26. How do you find Java elements using Selenium?

Ans. Java elements in Selenium can be found using various methods like findElement, findElements, etc.

Use findElement method to locate a single element in the DOM.

Use findElements method to locate multiple elements in the DOM.

Locate elements by ID, class name, name, tag name, xpath, css selector, etc.

Q27. Are you more proficient in SQL than in Java?

Ans. I have a good understanding of both SQL and Java.

I have experience working with both SQL and Java in various projects. 

I have a strong understanding of SQL syntax and can write complex queries.

I am proficient in Java and have worked with various frameworks and libraries.

I believe that having a good understanding of both SQL and Java is important for a Java Developer.

Q28. What are Java design patterns?

Ans. Java design patterns are reusable solutions to common problems encountered in software design.

Java design patterns help in creating flexible, reusable, and maintainable code. 

Examples of Java design patterns include Singleton, Factory, Observer, and Strategy.

Design patterns can be categorized into three groups: creational, structural, and behavioral.

Q29. Write a Dockerfile for a Java application.

Ans. A Dockerfile is a text file that contains instructions for building a Docker image for a Java application.

Use a base image that includes Java, such as 'openjdk:8'

Copy the application JAR file to the image using the 'COPY' instruction 

Set the working directory using the 'WORKDIR' instruction

Specify the command to run the Java application using the 'CMD' instruction.

Q30. How do you call an OSGi service from a model?

Ans. To call an OSGi service from a model, use the service tracker and obtain the service reference.

Create a service tracker object.

Set the context and filter for the service tracker .Open the service tracker

Get the service reference from the tracker

Use the service reference to call the OSGi service.

Q31. What is the difference between findFirst and findAny?

Ans. findFirst returns the first element in a stream, while findAny returns any element in a stream.

findFirst is deterministic and will always return the first element in a stream, while findAny is non-deterministic and can return any element.

findAny is useful for parallel processing as it can return any available element without the need to search for the first one.

findFirst is typically used when the order of elements matters, while findAny is used when any element can satisfy the condition.

Q32. Where is the Observer pattern used in Spring Boot?

Ans. The Observer pattern is used in SpringBoot for implementing event handling and notification mechanisms.

The Observer pattern is commonly used in SpringBoot for implementing event listeners and publishers. 

It allows objects to subscribe to and receive notifications about changes or events in other objects.

Spring's ApplicationEvent and ApplicationListener interfaces are examples of the Observer pattern in action.

Listeners can be registered with the ApplicationEventPublisher to receive notifications when specific events occur.

Q33. What is Metaspace in Java 8?

Ans. Meta space is a memory space in Java 8 used to store class metadata.

Meta space replaces the permanent generation (PermGen) space in Java 8. 

It stores class metadata such as class name, access modifiers, and constant pool.

Meta space is dynamically sized and can expand or shrink based on the application's needs.

It can be configured using the -XX:MetaspaceSize and -XX:MaxMetaspaceSize JVM options.

Q34. What is concurrency in Java?

Ans. Concurrency in Java refers to the ability of multiple tasks to run simultaneously within a program.

Concurrency allows for better utilization of resources by executing multiple tasks at the same time. 

Java provides built-in support for concurrency through features like threads and thread pools.

Concurrency can lead to issues like race conditions and deadlocks, which need to be carefully managed.

Example: Running multiple threads to perform different tasks concurrently in a web server application.

Q35. How do you handle lazy loading in Hibernate?

Ans. Lazy loading in Hibernate is a technique used to load data only when it is needed, improving performance.

Lazy loading is achieved by setting the fetch type to LAZY in the mapping of the entity relationship. 

When an entity is loaded, associated entities marked as LAZY are not loaded until accessed. 

Lazy loading helps in reducing unnecessary database calls and improves performance.

Example: @OneToMany(fetch = FetchType.LAZY)

Q36. What is an abstract method?

Ans. An abstract method is a method that is declared without an implementation in an abstract class or interface.

Abstract methods do not have a body and must be implemented by subclasses. 

Abstract classes can have both abstract and non-abstract methods.

Interfaces can only have abstract methods by default.

Q37. Tell me about the Executor framework.

Ans. Executor framework is a Java framework that provides a way to execute tasks asynchronously using a thread pool.

It provides a way to manage threads and execute tasks in a thread pool.

It allows for better resource management and improved performance.

It supports different types of thread pools such as fixed, cached, and scheduled.

Example: Executors.newFixedThreadPool(10) creates a thread pool with 10 threads.

Q38. what is java and new features of java ?

Ans. Java is a popular programming language known for its platform independence and object-oriented approach. New features include modules, var keyword, and more.

Java is a high-level, class-based, object-oriented programming language. 

New features in Java include modules for better code organization, the var keyword for type inference, and enhancements in the Java Platform Module System (JPMS).

Java 14 introduced switch expressions, records, and text blocks as new features.

Java 15 added sealed classes and interfaces, hidden classes, and pattern matching for instanceof.

Java 16 brought in features like JEP 338: Vector API (Incubator), JEP 376: ZGC: Concurrent Thread-Stack Processing, and JEP 387: Elastic Metaspace.

Java 17 introduced features like JEP 356: Enhanced Pseudo-Random Number Generators, JEP 382: New macOS Rendering Pipeline, and JEP 391: macOS/AArch64 Port.

Q39. How do you set the default value of a date field to the current date and time?

Ans. To set the default value of a date field to the current date time value, use a script to assign the value.

Create a client script or business rule to set the default value.

Use the GlideDateTime API to get the current date time value.

Assign the current date time value to the date field.

Q40. What is the difference between super and super()?

Ans. super is a keyword used to access methods and properties of a superclass, while super() is used to call the constructor of a superclass.

super is used to access methods and properties of a superclass in a subclass. 

super() is used to call the constructor of a superclass from a subclass constructor.

super can be used to access overridden methods or properties in the superclass.

super() must be the first statement in a subclass constructor.

Q41. What is the use of the super keyword?

Ans. The super keyword is used in Java to refer to the immediate parent class object.

Used to access methods and variables of the parent class.

Helps in achieving method overriding in inheritance.

Can be used to call the constructor of the parent class.

Example: super.methodName();

Q42. Explain Wrapper Class in Java 8.

Ans. Wrapper class in Java 8 is used to convert primitive data types into objects.

Wrapper classes provide a way to use primitive data types as objects.

They are used for converting primitive data types into objects and vice versa.

Examples include Integer, Double, Boolean, etc.

Q43. What is a parallel stream?

Ans. Parallel stream is a feature in Java that allows processing elements of a stream concurrently.

Parallel stream can be created from a regular stream using parallel() method.

It utilizes multiple threads to process elements in parallel, improving performance for large datasets.

However, parallel stream may not always be faster than sequential stream due to overhead of managing multiple threads.

Example: List<String> list = Arrays.asList("apple", "banana", "cherry"); 

list.parallelStream().forEach(System.out::println);

Q44. What is a Spring Actuator?

Ans. Spring Actuator is a feature in Spring Boot that allows monitoring and managing the application.

Spring Actuator provides endpoints to monitor application health, metrics, info, etc. 

It helps in understanding the internal state of the application and its performance.

Actuator endpoints can be accessed over HTTP, providing useful information for monitoring tools.

Example: /actuator/health, /actuator/metrics, /actuator/info

Q45. What are Spring bean scopes?

Ans. Spring bean scopes define the lifecycle and visibility of beans in a Spring application context.

Singleton: One instance per Spring IoC container. Example: @Bean(name = 'myBean') in a configuration class.

Prototype: A new instance is created each time the bean is requested. Example: @Scope('prototype') on a bean.

Request: A new instance is created for each HTTP request. Example: @Scope(value = 'request', proxyMode = ScopedProxyMode.TARGET_CLASS).

Session: A new instance is created for each HTTP session. Example: @Scope(value = 'session').

Global Session: Used in portlet applications, a new instance for each global HTTP session.

Q46. MVC layers for Java web service?

Ans. MVC layers in Java web service help separate concerns for better organization and maintainability.

Model layer: Represents the data and business logic.

View layer: Handles the presentation of data to the user.

Controller layer: Manages user input and updates the model accordingly.

Q47. How would you implement a database connection pool in Java?

Ans. Database connection pool in Java helps manage multiple database connections efficiently.

Use a connection pool library like HikariCP or Apache DBCP. 

Set up the pool with a maximum number of connections, timeout settings, etc.

Acquire and release connections from the pool as needed in your Java code.

Q48. Explain the internal workings of a Java HashMap.

Ans. Java HashMap is a data structure that stores key-value pairs and uses hashing to efficiently retrieve values.

HashMap uses an array of buckets to store key-value pairs.

The key is hashed to find the index of the bucket where the value is stored.

If multiple keys hash to the same index, a linked list or balanced tree is used to handle collisions.

HashMap allows one null key and multiple null values.

Example: HashMap<String, Integer> map = new HashMap<>();

Q49. What are the advantages of using Spring Boot Starters?

Ans. Spring Boot starters are dependency descriptors that simplify the dependency management process in Spring Boot applications.

Spring Boot starters provide a set of pre-configured dependencies that can be easily included in your project. 

They help in reducing the amount of boilerplate code needed to set up a Spring Boot application.

Starters are typically named with the format 'spring-boot-starter-*', where * represents the specific functionality or technology being included.

For example, 'spring-boot-starter-web' includes dependencies for building web applications using Spring MVC.

Q50. Java 8 in depth ?

Ans. Java 8 introduced several new features including lambda expressions, streams, and functional interfaces.

Lambda expressions allow for more concise code by enabling functional programming.

Streams provide a way to process collections of objects in a functional style.

Functional interfaces are interfaces with a single abstract method, which can be implemented using lambda expressions.

Java 8 also introduced the Optional class to handle null values more effectively.

Q51. Design principles in Java?

Ans. Design principles in Java focus on creating modular, reusable, and maintainable code.

Single Responsibility Principle - Each class should have only one responsibility. 

Open/Closed Principle - Classes should be open for extension but closed for modification.

Liskov Substitution Principle - Subtypes should be substitutable for their base types.

Interface Segregation Principle - Clients should not be forced to depend on interfaces they do not use.

Dependency Inversion Principle - High-level modules should not depend on low-level modules; both should depend on abstractions.

Q52. Java 8 advantages ?

Ans. Java 8 introduced several new features and improvements, including lambda expressions, functional interfaces, streams, and default methods.

Lambda expressions allow for more concise and readable code. 

Functional interfaces enable the use of lambda expressions.

Streams provide a way to work with collections in a more functional style.

Default methods allow interfaces to have method implementations.

Q53. How have you leveraged Spring Java in your projects?

Ans. I leverage Spring Java for dependency injection, MVC framework, and transaction management in my projects.

Utilize Spring's dependency injection to manage object dependencies and improve code maintainability.

Leverage Spring MVC framework for building web applications with clean separation of concerns.

Use Spring's transaction management to ensure data integrity and consistency in database operations.

Q54. Different technologies available in java

Ans. Some technologies available in Java include Java EE, Spring Framework, Hibernate, Apache Struts, and JavaFX.

Java EE (Enterprise Edition) for building enterprise applications.

Spring Framework for dependency injection and aspect-oriented programming.

Hibernate for object-relational mapping.

Apache Struts for developing web applications.

JavaFX for creating rich internet applications.

Q55. How to deploy Java apps?

Ans. Java applications can be deployed using various methods such as manual deployment, using build tools like Maven or Gradle, or using containerization platforms like Docker.

Use build tools like Maven or Gradle to package the application into a JAR or WAR file.

Deploy the packaged application to a server or cloud platform.

Utilize containerization platforms like Docker to create a container image of the application and deploy it.

Automate deployment process using CI/CD tools like Jenkins or GitLab.

Q56. What is the return type for getWindowHandles?

Ans. The return type for get window handles is an array of strings.

Return type should be an array of strings.

Each string in the array represents a window handle.

Example: ['handle1', 'handle2', 'handle3']

Q57. JPA vs Hibernate ?

Ans. JPA is a specification while Hibernate is an implementation of JPA.

JPA is a Java specification for managing relational data in applications. 

Hibernate is an ORM framework that implements the JPA specification.

Hibernate provides additional features beyond JPA, such as caching and lazy loading.

JPA is vendor-neutral, allowing developers to switch between different JPA implementations.

Hibernate is a popular choice for JPA implementation due to its extensive features and community support.

Q58. All Java 8 new features ? 

Ans. Java 8 introduced several new features including lambda expressions, functional interfaces, streams, and default methods.

Lambda expressions allow you to pass functionality as an argument to a method. 

Functional interfaces have a single abstract method and can be used with lambda expressions.

Streams provide a way to work with sequences of elements efficiently.

Default methods allow interfaces to have method implementations.

Some other features include the new Date and Time API, Nashorn JavaScript Engine, and the CompletableFuture API.

Q59. How does AWT Token work?

Ans. AWT Token is a security token used for authentication and authorization in Java applications.

AWT stands for Abstract Window Toolkit .

AWT Token is used for managing user authentication and authorization in Java applications.

It provides a secure way to control access to resources based on user credentials.

Q60. Spring JPA vs Hibernate?

Ans. Spring JPA is a part of the Spring Data project that makes it easier to work with JPA. Hibernate is a popular ORM framework.

Spring JPA is a higher level abstraction on top of JPA, providing more features and simplifying development.

Hibernate is a powerful ORM framework that provides mapping between Java objects and database tables.

Spring JPA can be used with Hibernate as the underlying ORM provider.

Hibernate offers more flexibility and control over the database interactions compared to Spring JPA.

Q61. Classloaders in java ?

Ans. Classloaders are responsible for loading classes into the JVM at runtime.

Java has three built-in classloaders: bootstrap, extension, and system. 

Custom classloaders can be created to load classes from non-standard sources. 

Classloaders follow a delegation model, where they first delegate to their parent classloader before attempting to load the class themselves.

Classloaders can be used for dynamic class loading and hot-swapping of code at runtime.

Q62. Stream and collection api usage ?

Ans. Stream and collection api usage involves manipulating data using streams and collections in Java.

Stream API provides a way to process collections of objects in a functional way. 

Collection API provides data structures to store and manipulate groups of objects.

Stream API can be used to filter, map, reduce, and collect data from collections.

Collection API includes interfaces like List, Set, and Map for different data structures.

Q63. Objects in java 8 ?

Ans. Java 8 introduced the concept of functional programming with the addition of lambda expressions and streams.

Lambda expressions allow for concise code and easier parallel programming. 

Streams provide a way to work with collections of objects in a functional style. 

Functional interfaces like Predicate, Function, and Consumer are commonly used with lambda expressions.

Q64. java 8 improvements ?

Ans. Java 8 introduced several improvements including lambda expressions, functional interfaces, streams, and default methods.

Lambda expressions allow for more concise code and easier parallel programming. 

Functional interfaces enable the use of lambda expressions.

Streams provide a way to work with sequences of elements efficiently.

Default methods allow interfaces to have concrete methods.

Optional class helps to handle null values more effectively.

Q65. Is Java platform-independent, and if so, why?

Ans. Yes, Java is platform-independent because of its 'write once, run anywhere' principle.

Java programs are compiled into bytecode, which can be executed on any platform with a Java Virtual Machine (JVM).

The JVM acts as an interpreter, translating the bytecode into machine code specific to the underlying platform.

This allows Java programs to run on different operating systems and hardware architectures without modification.

For example, a Java program developed on a Windows machine can run on a Linux or macOS machine without recompilation.

Q66. Can we use a controller annotation instead of a service annotation?

Ans. No, controller and service annotations serve different purposes in a software application.

Controller annotations are used to define the entry points for incoming requests and map them to specific methods in a controller class.

Service annotations are used to mark a class as a service component that can be injected into other classes for business logic implementation.

Mixing up controller and service annotations can lead to confusion in the application structure and functionality.

Q67. What are the different techniques to inject a bean into an application context?

Ans. Different techniques for injecting beans in application context

Constructor Injection 

Setter Injection

Field Injection

Method Injection

Q68. Do you have any knowledge of software such as Java or Python?

Ans. Yes, I have knowledge of both Java and Python.

I have experience in developing robotics applications using Java and Python. 

I am familiar with object-oriented programming concepts in both languages. 

I have worked on projects involving robotics simulation and control using Java and Python. 

I have used Java for Android app development in robotics applications.

I have utilized Python for machine learning algorithms in robotics projects.

Q69. What are some methods in the Executor framework?

Ans. The Executor framework in Java provides a high-level API for managing and controlling thread execution.

Executor: The simplest interface for executing tasks asynchronously. 

ExecutorService: Extends Executor, provides methods for managing termination and tracking progress.

ScheduledExecutorService: Allows scheduling of tasks to run after a given delay or periodically.

invokeAll(): Executes a collection of tasks and returns a list of Future objects.

invokeAny(): Executes a collection of tasks and returns the result of the first successfully completed task.

Q70. Important Spring boot Annotations

Ans. Some important Spring Boot annotations include @SpringBootApplication, @RestController, @Autowired, @RequestMapping, @ComponentScan.

@SpringBootApplication - Used to mark the main class of a Spring Boot application. 

@RestController - Used to define RESTful web services.

@Autowired - Used for automatic dependency injection.

@RequestMapping - Used to map web requests to specific handler methods.

@ComponentScan - Used to specify the base packages to scan for Spring components.

Q71. What is C++ Java

Ans. C++ and Java are programming languages used for software development.

C++ is a high-performance language used for system programming, game development, and other performance-critical applications.

Java is an object-oriented language used for developing web applications, mobile apps, and enterprise software.

C++ is compiled, while Java is both compiled and interpreted.

C++ allows for direct memory manipulation, while Java has automatic memory management.

C++ is known for its speed and efficiency, while Java is known for its portability and ease of use.

Q72. Explain all the features of Java 8.

Ans. Java 8 introduced several new features including lambda expressions, streams, functional interfaces, and more.

Lambda expressions: Allow you to pass functionality as an argument to a method. 

Streams: Provide a way to work with sequences of elements.

Functional interfaces: Interfaces with a single abstract method, used for lambda expressions.

Default methods: Allow interfaces to have methods with implementation.

Method references: Provide a way to refer to methods without invoking them. 

Optional class: Helps to avoid null pointer exceptions. 

Date and Time API: Improved API for handling date and time.

Parallel array sorting: Arrays can now be sorted in parallel.

CompletableFuture: Asynchronous programming with future-like capabilities.

Q73. Tell me about CompletableFuture?

Ans. CompletableFuture is a class introduced in Java 8 to represent a future result of an asynchronous computation.

CompletableFuture can be used to perform tasks asynchronously and then combine their results. 

It supports chaining of multiple asynchronous operations.

It provides methods like thenApply, thenCompose, thenCombine, etc. for combining results.

Example: CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 10);

Q74. What is the difference between @RequestBody and @ResponseBody?

Ans. Difference between @requestbody and @responsebody annotations in Spring MVC

The @RequestBody annotation is used to bind the HTTP request body to a method parameter in Spring MVC controller.

The @ResponseBody annotation is used to bind the return value of a method to the HTTP response body in Spring MVC.

Example: @RequestBody User user - binds the request body to a User object parameter.

Example: @ResponseBody String hello() - binds the return value of hello() method to the response body as a String.

Q75. What is the use of a functional interface?

Ans. Functional interfaces are interfaces with a single abstract method, used in Java to enable lambda expressions.

Functional interfaces allow lambda expressions to be used as instances of the interface.

They provide a way to implement functional programming concepts in Java.

Examples include java.lang.Runnable, java.util.Comparator, and java.util.function.Predicate

Q76. How do you find characters using the Stream API?

Ans. Using Java Stream API to find characters in a string efficiently and concisely.

Streams can be created from a string using `chars()` method: `String str = "hello"; str.chars()`.

To filter specific characters, use `filter()`: `str.chars().filter(c -> c == 'e')`.

Convert the IntStream back to characters using `mapToObj()`: `mapToObj(c -> (char) c)`.

Collect results into a list with `collect(Collectors.toList())`: `collect(Collectors.toList())`.

Q77. What are the commonly used functional interfaces in your application?

Ans. Commonly used functional interfaces include Predicate, Consumer, Supplier, and Function.

Predicate: used for boolean-valued functions of one argument.

Consumer: used for operations that take in one argument and return no result.

Supplier: used for operations that take no arguments and return a result.

Function: used for operations that take in one argument and return a result.

Q78. Frame works in Java?

Ans. Frameworks in Java provide pre-written code to help developers build applications more efficiently.

Frameworks like Spring, Hibernate, and Struts provide structure and functionality to Java applications.

Frameworks help developers follow best practices and reduce the amount of code they need to write.

Frameworks often include features like dependency injection, ORM mapping, and MVC architecture.

Using frameworks can speed up development time and make applications more maintainable.

Popular Java frameworks include Spring Boot, JavaServer Faces, and Apache Wicket.

Q79. Can you briefly explain Spring annotations?

Ans. Spring annotations are used to provide metadata to Spring framework classes and methods.

Annotations like @Component, @Controller, @Service, and @Repository are used for component scanning and auto-wiring. 

@Autowired is used for dependency injection.

@RequestMapping is used to map web requests to specific handler methods.

@Transactional is used for managing transactions.

Annotations like @Value, @Qualifier, and @Scope are used for configuring beans.

Q80. Features of SringBoot ?

Ans. Spring Boot is a framework that simplifies the development of Java applications by providing pre-configured settings and tools.

Spring Boot eliminates the need for manual configuration by providing defaults for most settings.

It includes embedded servers like Tomcat, Jetty, or Undertow, making it easy to deploy standalone applications.

Spring Boot offers production-ready features like metrics, health checks, and externalized configuration.

It supports Spring's programming model and is designed to work with Spring frameworks like Spring Data, Spring Security, etc.

Q81. What are the differences between @RequestParam and @PathVariable, and what is the syntax for each?

Ans. Requestparam vs pathvariable and syntax

RequestParam is used to extract query parameters from the URL, while PathVariable is used to extract values from the URI template

RequestParam syntax: @RequestParam("paramName") String paramValue 

PathVariable syntax: @PathVariable("varName") String varValue

Example: @RequestParam("id") String id

Example: @PathVariable("name") String name

Q82. What databases are used by the Java front-end developer?

Ans. The database used by Java front end developers varies depending on the project requirements.

Common databases used by Java front end developers include MySQL, PostgreSQL, Oracle, and MongoDB. 

The choice of database depends on factors such as scalability, performance, and data structure requirements.

For example, a Java front end developer working on a financial application may use Oracle for its robust transaction capabilities.

Q83. How can you send values without using the sendKeys method?

Ans. Values can be sent without using sendkeys method by directly manipulating the DOM or using JavaScriptExecutor.

Use JavaScriptExecutor to execute JavaScript code to set values of input fields. 

Find the element using appropriate locators and then use JavaScriptExecutor to set the value.

Example: driver.executeScript("document.getElementById('elementId').value='text'");

Q84. What are Spring beans?

Ans. Spring beans are objects managed by the Spring IoC container, providing configuration and lifecycle management.

Spring beans are instantiated, configured, and managed by the Spring IoC container. 

They can be defined in XML, Java annotations, or Java configuration classes.

Example: @Component annotation can be used to define a bean in a class.

Beans can have different scopes: singleton, prototype, request, session, etc.

Dependency injection allows beans to collaborate with other beans.

Q85. What is a bean factory?

Ans. Bean factory is a container for managing beans in Spring framework.

Bean factory is responsible for creating, managing, and configuring beans in a Spring application. 

It uses inversion of control (IoC) to manage the beans.

Beans are defined in a configuration file (XML or Java) and the bean factory instantiates them.

Example: ApplicationContext is a type of bean factory in Spring framework.

Q86. What is the get method?

Ans. The get method is a function used to retrieve the value of a specified property from an object.

Used in JavaScript to access the value of a property in an object .

Syntax: objectName.propertyName

Example: var person = {name: 'John', age: 30}; console.log(person.name); // Output: John

Q87. multithreading in spring boot ?

Ans. Multithreading in Spring Boot allows for concurrent execution of tasks, improving performance and responsiveness.

Spring Boot provides support for multithreading through the use of @Async annotation.

By annotating a method with @Async, it will be executed in a separate thread. 

ThreadPoolTaskExecutor can be configured to control the number of threads used for executing async methods.

Example: @Async public void asyncMethod() { // method logic }

Q88. What features were introduced in Java 8?

Ans. Java 8 introduced features like lambda expressions, functional interfaces, streams, and default methods.

Lambda expressions allow you to pass functionality as an argument to a method. 

Functional interfaces have a single abstract method and can be used with lambda expressions.

Streams provide a way to work with sequences of elements and perform aggregate operations.

Default methods allow interfaces to have method implementations.

Q89. What is the difference between @Mock and @InjectMock?

Ans. Difference between @Mock and @InjectMock annotations in Java testing

Use @Mock to create a mock object of a class or interface.

Use @InjectMock to inject the mock object into the class being tested.

Example: @Mock UserService userService; @InjectMock UserController userController;

Example: Mockito.when(userService.getUserById(1)).thenReturn(new User());

Q90. Regarding functional interfaces, what are the real-time use cases for static and default methods?

Ans. Static and default methods in functional interfaces provide utility methods and default implementations for interface methods in real-time applications.

Static methods in functional interfaces can be used for utility methods that are not tied to a specific instance of the interface.

Default methods in functional interfaces provide default implementations for interface methods, allowing for backward compatibility when new methods are added to the interface.

In real-time applications, static and default methods can be used to provide common functionality across multiple implementations of the functional interface.

Q91. What are some web development frameworks for Java?

Ans. Java web development frameworks include Spring, Hibernate, Struts, and Play.

Popular Java web development frameworks include Spring, Hibernate, Struts, and Play

Spring is a widely used framework for building enterprise Java applications

Hibernate is an ORM framework for mapping Java objects to database tables

Struts is a framework for building web applications using the MVC design pattern.

Play is a lightweight web framework for building scalable web applications.

Q92. What is the final keyword in Java?

Ans. The final keyword in Java is used to restrict the user from modifying the value of a variable, the definition of a method, or the inheritance of a class.

When a variable is declared as final, its value cannot be changed.

When a method is declared as final, it cannot be overridden by subclasses.

When a class is declared as final, it cannot be inherited by other classes.

Final variables must be initialized before use.

Final methods can be used to prevent method overriding.

Final classes are often used for utility classes or to prevent subclassing.

Q93. What is @ComponentScan?

Ans. Annotation used in Spring framework to enable component scanning for Spring-managed beans.

Used to automatically detect and register Spring-managed beans within the specified package(s). 

Can be used at class level or configuration classes to specify base package(s) to scan

Can be customized with additional attributes like basePackageClasses, includeFilters, excludeFilters

Example: @ComponentScan(basePackages = {"com.example.package1", "com.example.package2"})

Q94. What is the basic role of JAVA in software development?

Ans. JAVA is a versatile programming language used for developing various software applications.

JAVA is platform-independent and can run on any operating system,

It is object-oriented and supports multithreading

JAVA is widely used for developing web applications, mobile applications, and enterprise software

It provides a vast library of pre-built classes and APIs for developers to use

JAVA is also used for developing games, scientific applications, and financial applications

Q95. Why did you choose Python over Java?

Ans. Python offers simplicity, readability, and a rich ecosystem, making it a preferred choice over Java for many developers.

Simplicity: Python's syntax is cleaner and more intuitive, allowing for faster development. For example, list comprehensions in Python are concise. 

Readability: Python emphasizes code readability, which makes it easier to maintain and collaborate on projects. Indentation is used to define code blocks.

Rich Libraries: Python has a vast collection of libraries and frameworks (like Django for web development and NumPy for data science) that speed up development. 

Dynamic Typing: Python's dynamic typing allows for more flexibility in coding, reducing boilerplate code compared to Java's static typing. 

Community Support: Python has a large and active community, providing extensive resources, tutorials, and third-party modules.

Q96. New features of java 8 ?

Ans. Java 8 introduced new features like lambda expressions, functional interfaces, streams, and default methods.

Lambda expressions allow you to pass functions as arguments to methods. 

Functional interfaces have a single abstract method and can be used with lambda expressions.

Streams provide a way to work with sequences of elements efficiently.

Default methods allow interfaces to have method implementations.

Example: Lambda expression - (a, b) -> a + b

Example: Stream - List<String> names = Arrays.asList("Alice", "Bob"); names.stream().filter(name -> name.startsWith("A")).forEach(System.out::println);

Q97. What are the use cases for functional interfaces?

Ans. Functional interfaces enable the use of lambda expressions and method references in Java, promoting cleaner and more concise code.

A functional interface has exactly one abstract method. 

Examples include Runnable, Callable, and Comparator.

They can be implemented using lambda expressions for brevity.

Functional interfaces are used extensively in the Stream API.

Custom functional interfaces can be created using the @FunctionalInterface annotation.

Q98. Why do we have a wait method in the Object class?

Ans. The wait method in the Object class is used for inter-thread communication and synchronization.

wait() is used to make a thread wait until another thread notifies it.

It is used in multi-threaded applications to coordinate the execution of threads.

wait() releases the lock held by the current thread, allowing other threads to acquire it.

It is typically used in conjunction with notify() and notifyAll() methods.

Example: wait() can be used to implement the producer-consumer pattern.

Q99. What is the difference between @Inject and @Autowire?

Ans. Difference between @Inject and @Autowire in Java Spring

Both are used for dependency injection in Spring framework.

@Inject is a standard annotation defined in Java EE, while @Autowired is a Spring-specific annotation.

@Inject is more powerful and flexible as it supports optional dependencies and custom qualifiers.

@Autowired is more commonly used in Spring applications and is more concise

Q100. What is dependency injection in Spring?

Ans. Dependency injection in Spring is a design pattern where objects are provided with their dependencies rather than creating them internally.

In Spring, dependency injection is achieved through either constructor injection or setter injection. 

It helps in achieving loose coupling between classes and promotes easier testing and maintenance.

Example: In Spring framework, you can define dependencies in a configuration file and let the framework inject them into the classes at runtime.

Q101. Explain what a package is?

Ans. A package is a way to organize related classes and interfaces in Java.

Packages help in organizing code and avoiding naming conflicts.

Packages can be nested within each other

Packages are declared using the 'package' keyword at the beginning of a Java file.

Q102. New features of java 8 ?

Ans. Java 8 introduced new features like lambda expressions, functional interfaces, streams, and default methods.

Lambda expressions allow you to pass functions as arguments to methods.

Functional interfaces have a single abstract method and can be used with lambda expressions.

Streams provide a way to work with sequences of elements efficiently.

Default methods allow interfaces to have method implementations.

Example: Lambda expression - (a, b) -> a + b

Example: Stream - List<String> names = Arrays.asList("Alice", "Bob"); names.stream().filter(name -> name.startsWith("A")).forEach(System.out::println);

Q103. Describe a time you processed a file, selected the first three lines, identified the longest line, and counted the words in that line. What approach did you take, and what Java methods did you use?

Ans. The program reads a file and selects the first 3 lines. It then identifies the longest line and counts the number of words in that line.

Read the file using appropriate file handling methods.

Store the first 3 lines in an array of strings.

Iterate through the array to find the longest line.

Count the number of words in the longest line using string manipulation methods.

Q104. What is the purpose of the @SpringBootApplication annotation?

Ans. Annotation used to mark a class as a Spring Boot application

Combines @Configuration, @EnableAutoConfiguration, and @ComponentScan annotations.

Used to bootstrap and launch a Spring application

Automatically scans for Spring components in the package and sub-packages.

Q105. What archive is present in EAR?

Ans. EAR file contains a JAR file which is an archive of Java classes, resources, and metadata.

EAR file stands for Enterprise Archive.

Contains one or more Java EE modules (WAR, JAR, etc.)

Used for packaging and deploying enterprise applications.

Q107. Can we use the 'this' keyword inside a static method?

Ans. No, this keyword cannot be used inside a static method.

The 'this' keyword refers to the current instance of the class, but static methods do not have an instance. 

Static methods can only access static variables and methods.

To access non-static variables or methods, an object of the class must be created first.

Q108. What are the different scopes of Spring beans?

Ans. Spring beans can have different scopes like singleton, prototype, request, session, and application.

Singleton scope: Bean is created only once per Spring IoC container.

Prototype scope: Bean is created each time it is requested.

Request scope: Bean is created once per HTTP request.

Session scope: Bean is created once per HTTP session.

Application scope: Bean is created once per ServletContext.

Q109. What types of Class Loaders are available in Java?

Ans. Java has three types of class loaders: Bootstrap Class Loader, Extension Class Loader, and System Class Loader.

Bootstrap Class Loader loads core Java classes located in the bootstrap classpath. 

Extension Class Loader loads classes from the extensions directory.

System Class Loader loads classes from the classpath specified by the CLASSPATH environment variable.

Q110. What is StringBuffer and where is it used?

Ans. StringBuffer is a mutable sequence of characters. It is used to efficiently manipulate strings.

StringBuffer is a class in Java that allows you to modify strings without creating a new object. 

It is used when you need to concatenate a large number of strings efficiently.

StringBuffer is synchronized, so it is safe to use in multi-threaded environments.

It provides methods like append(), insert(), delete(), and reverse() to modify the string.

Example: StringBuffer sb = new StringBuffer(); sb.append("Hello"); sb.append(" World!");

Q111. What all topics I know about Java?

Ans. I have knowledge about various topics in Java programming language.

Object-oriented programming.

Java syntax and data types.

Exception handling.

Multithreading.

Collections framework.

File handling.

Networking.

Java GUI (Swing, JavaFX).

Database connectivity (JDBC).

Java frameworks (Spring, Hibernate).

Q112. What is a static initializer?

Ans. A static initializer is a block of code that is used to initialize the static variables of a class.

Static initializers are executed only once when the class is loaded into memory. 

They are useful for initializing static variables that require complex calculations or external resources.

Static initializers are defined using the 'static' keyword followed by a block of code enclosed in curly braces.

Q113. What is the difference between finally, finalize, and final?

Ans. finally is a keyword used in try-catch block, finalize is a method in Object class, and final is a keyword used for declaring constants.

finally is used to execute a block of code after try-catch block.

finalize is called by garbage collector before destroying an object.

final is used to declare a constant variable or to make a class uninheritable.


Q114. How many classes can be present in a Java file?

Ans. A Java file can have multiple classes, but only one public class.

A Java file can have multiple non-public classes. 

The name of the public class must match the name of the file. 

Only the public class can be accessed from outside the file.

Q115. Why is Java considered secure?

Ans. Java is most secured due to its strong memory management, bytecode verification, and security manager.

Java's strong memory management prevents buffer overflow and other memory-related vulnerabilities. 

Bytecode verification ensures that the code is safe to execute and prevents malicious code from running.

Security manager allows fine-grained control over access to system resources.

Java also has a robust set of security APIs and tools for encryption, authentication,and authorization.

Examples of Java's security features include SSL/TLS support, JCA/JCE for cryptography, and JAAS for authentication and authorization.

Q116. Can we use super and this in a single constructor?

Ans. Yes, we can use super and this in a single constructor.

Using 'super' in a constructor calls the parent class constructor. 

Using 'this' in a constructor calls another constructor in the same class.

We can use both 'super' and 'this' in the same constructor to call both parent and same class constructors.

Example: public MyClass(int x) { this(x, 0); super(); }

Q117. Why do we use SerialVersionUID, and what happens if the IDs do not match?

Ans. SerialVersionUID is used to ensure version compatibility of serialized objects.

SerialVersionUID is a unique identifier assigned to a serializable class. 

It is used to ensure that the serialized object can be deserialized correctly even if the class definition has changed. 

If the SerialVersionUID of the serialized object does not match the one in the class definition, an InvalidClassException is thrown.

To avoid this, it is recommended to declare a static final long SerialVersionUID in the class definition.

Q118. What is the superclass of Exception?

Ans. The super class of Exception is Throwable.

Throwable is the root class of all exceptions in Java. 

It has two direct subclasses: Exception and Error.

Exceptions are used for recoverable errors while Errors are used for unrecoverable errors.

All exceptions and errors inherit from Throwable.

Throwable provides methods like getMessage() and printStackTrace() to handle exceptions.

Q119. Can we use @repository as @service?

Ans. Yes, we can make @repository as @service.

Both @repository and @service are stereotypes in Spring framework. 

@repository is used to indicate that a class is a repository, which is responsible for data access. 

@service is used to indicate that a class is a service, which is responsible for business logic.

If a class annotated with @repository also performs business logic, it can be annotated with @service as well.

This allows the class to be autowired as both a repository and a service.

Q120. Under what conditions can we skip the GC test?

Ans. GC test can be skipped in certain medical conditions.

If the patient has a medical condition that can interfere with the accuracy of the test, such as liver disease or kidney failure.

If the patient is taking medication that can affect the test results, such as antibiotics or antifungal drugs.

If the patient has recently received a vaccine that contains live viruses, such as the MMR vaccine.

If the patient has a low risk of infection or if the test is not necessary for diagnosis or treatment.


Q121. Can we pass arguments in place of args in String[] args?

Ans. Yes, we can pass arguments in place of args in string[] args.

Arguments can be passed directly as an array of strings. 

The number of arguments passed must match the size of the array. 

Example: public static void main(String[] args) can be called as main(new String[] {"arg1", "arg2"});

Q122. Can you describe the role of a Java Developer?

Ans. A Java developer is responsible for designing, implementing, and maintaining Java applications.

Java developers write, test, and debug code. 

They collaborate with cross-functional teams to define, design, and ship new features.

They are proficient in Java programming language and frameworks like Spring and Hibernate.

Java developers have knowledge of database technologies like SQL and NoSQL.

They have experience with version control systems like Git.

They possess problem-solving and analytical skills.

They stay updated with the latest trends and advancements in Java development.

Q123. What is the access modifier of the default constructor?

Ans. The access modifier of the default constructor is usually public.

The default constructor is a special constructor that is automatically generated by the compiler if no constructor is defined in the class. 

The access modifier determines the visibility of the constructor. 

By default, the access modifier of the default constructor is public, allowing it to be accessed from anywhere. 

However, it can also be explicitly defined with other access modifiers like private or protected.

Q124. What annotation tools are you familiar with?

Ans. Annotations tools are used to highlight, mark, or add notes to a document or image.

Annotations can be made using software tools such as Adobe Acrobat, Microsoft Word, or Google Docs. 

They can be used to add comments, highlight text, draw shapes, or add sticky notes.

Annotations are commonly used in academic research, legal documents, and graphic design.

They can also be used in medical imaging to mark areas of interest or abnormalities.

Annotations can improve collaboration and communication by providing clear feedback and context.

Q125. How can you check if a string is not null without using string != null?

Ans. Checking if a string is not null without using string != null.

Use string.IsNullOrEmpty() method.

Use string.IsNullOrWhiteSpace() method.

Use string.Compare() method to compare with an empty string.

Use string.Length property to check if length is greater than 0.

Q126. What are some common Java commands?

Ans. Java commands are instructions used to execute Java programs and perform various tasks.

Java commands are used to compile and run Java programs.

Some commonly used Java commands include javac, java, jar, and jdb.

Javac is used to compile Java source code into bytecode.

Java is used to execute Java bytecode.

Jar is used to create and manage Java archive files.

Jdb is used to debug Java programs.

Java commands can be executed from the command line or from an IDE.

Q127. What is the difference between an abstract method and an interface?

Ans. Abstract methods are methods without implementation in abstract classes, while interfaces are contracts that define methods.

Abstract classes can have both abstract and non-abstract methods, while interfaces can only have abstract methods. 

A class can implement multiple interfaces, but can only inherit from one abstract class.

Abstract classes can have constructors, while interfaces cannot.

Interfaces can have properties, while abstract classes can have fields.

Q128. What is the difference between extend and implement?

Ans. Extend is used to inherit properties and methods from a class, while implement is used to implement interfaces.

Extend is used to create a subclass that inherits properties and methods from a superclass. 

Implement is used to define a class that implements the methods declared in an interface.

A class can extend only one superclass, but it can implement multiple interfaces.

Extend is used for inheritance, while implement is used for interface implementation.

Q129. Who calls the main method in Java?

Ans. The Java Virtual Machine (JVM) calls the main method in Java.

The main method is the entry point of a Java program.

It is declared as public static void main(String[] args)

The JVM searches for the main method in the class specified in the command line arguments.

If the main method is not found, the JVM throws a NoSuchMethodError.

Q130. What are the final, super, and extends keywords?

Ans. final, super, and extends are keywords in Java used for inheritance and method overriding.

final keyword is used to make a variable constant or a method unchangeable. 

super keyword is used to refer to the immediate parent class.

extends keyword is used to create a subclass that inherits properties and methods from a superclass.

Q131. How can you reduce the time complexity of a for each loop?

Ans. Use indexed for loop instead of for each loop to reduce time complexity.

Indexed for loop has a constant time complexity of O(1) whereas for each loop has a time complexity of O(n).

Indexed for loop is faster when accessing elements in an array.

Example: for (int i = 0; i < array.length; i++) { //access array[i] }

Example: for (String str : stringArray) { //access str }

Q132. Can we overload the main method or constructor?

Ans. Yes, we can overload the main method and constructor in Java.

Overloading means having multiple methods or constructors with the same name but different parameters.

In the case of the main method, we can have multiple main methods with different parameter lists.

For example, we can have a main method with the signature 'public static void main(String[] args)' and another with 'public static void main(String arg)'Similarly, constructors can also be overloaded by having different parameter lists. 

For example, a class can have multiple constructors with different parameter combinations.

Q133. Write a program to extract and print all alphabets from the string "selenium 123java456". The expected output is "seleniumjava".

Ans. Write a program to print all the alphabets from a given string.

Loop through each character in the string.

Check if the character is an alphabet using isalpha() function.

If it is an alphabet, add it to a new string.

Print the new string.

Q134. What does a finally block do?

Ans. Finally block is used in exception handling to execute code regardless of whether an exception is thrown or not.

Finally block is always executed after try and catch blocks.

It is used to release resources like file handles, database connections, etc.

It is also used to perform cleanup operations like closing streams, deleting temporary files, etc.

Finally block can be used without catch block but not vice versa.

Example: try { //code that may throw exception } catch(Exception e) { //handle exception } finally { //code that always executes }

Q135. How is it implemented in Java?

Ans. The question is asking about how a specific implementation is done in Java.

Explain the implementation details of the specific feature or functionality in Java.

Provide code examples if applicable.

Discuss any relevant libraries or frameworks used in the implementation.

Q136. What are static, super, and final keywords?

Ans. Static, super, and final are Java keywords used for different purposes.

Static keyword is used to create class-level variables and methods. 

Super keyword is used to call the parent class constructor or method.

Final keyword is used to create constants or prevent method or class overriding.

Q137. Does Java have pointers?

Ans. Yes, Java has pointers.

Java has pointers but they are not explicitly exposed to the programmer. 

Java uses references instead of pointers.

Java pointers are used for memory management and garbage collection.

Q138. What is the difference between an interface and a functional interface?

Ans. An interface is a blueprint for a class while a functional interface is an interface with only one abstract method.

An interface can have multiple abstract methods while a functional interface has only one. 

Functional interfaces can be used with lambda expressions and method references.

Examples of functional interfaces include Runnable, Comparator, and Callable.

Interfaces can have default and static methods while functional interfaces cannot.

Functional interfaces are used extensively in Java 8's Stream API.

Q139. What is Java? Explain in detail.

Ans. Java is a high-level, object-oriented programming language used to develop applications for various platforms.

Java is platform-independent, meaning it can run on any platform with a Java Virtual Machine (JVM).

It is known for its security features, such as the ability to run code in a sandbox environment

Java is used for developing a wide range of applications, from web applications to mobile apps and games.

It is also used for developing enterprise-level applications, such as banking systems and e-commerce websites.

Java has a vast library of pre-built classes and APIs, making it easier for developers to write code.

Q140. Why is static used in "public static void main"?

Ans. Static is used in public static void main to allow the method to be called without creating an instance of the class.

Static methods belong to the class and not to any instance of the class. 

The main method is the entry point of a Java program and needs to be called without creating an object of the class.

The static keyword allows the main method to be called directly from the class, without creating an instance of the class.

The main method signature is public static void main(String[] args), where the static keyword is used to make the method accessible without creating an object of the class.

If the main method was not static, it would require an instance of the class to be created before it could be called.

Q141. What is the difference between synchronized and concurrent?

Ans. Synchronized ensures only one thread can access a resource at a time, while concurrent allows multiple threads to access it simultaneously.

Synchronized is used for thread safety and mutual exclusion.

Concurrent is used for improving performance and scalability.

Synchronized can cause performance issues due to locking. 

Concurrent can cause race conditions and requires careful synchronization.

Examples of synchronized: synchronized methods, synchronized blocks.

Examples of concurrent: ConcurrentHashMap, CopyOnWriteArrayList.

Q142. What is a precondition?

Ans. A precondition is a condition that must be true before a function or method can be executed.

Preconditions are used to ensure that the inputs to a function or method are valid. 

They help prevent errors and unexpected behavior by checking if certain conditions are met.

If a precondition is not satisfied, an exception or error may be thrown. 

For example, a precondition for a function that calculates the square root of a number could be that the number must be positive.

Q143. Why is Dagger required?

Ans. Dagger is required for dependency injection in Android development.

Dagger helps in managing dependencies and reduces boilerplate code. 

It provides compile-time safety and improves code readability. 

Dagger also helps in testing and modularizing the codebase.

It is widely used in Android development for building scalable and maintainable apps.

Q144. How do you define user-defined exceptions?

Ans. User defined exceptions can be defined by creating a new class that extends the Exception class.

Create a new class that extends the Exception class. 

Add constructors to the class to initialize the exception. 

Throw the exception using the 'throw' keyword.

Q145. Can you write code for printing a star pattern in Java?

Ans. Yes, I can write code for printing a star in Java.

Create an array of strings to represent the star

Use a loop to iterate through each row of the array.

Use another loop to iterate through each column of the array.

Print the value at each row and column position

Example: String[] star = {" * ", " *** ", "*****", " *** ", " * "};

Example: for (String row : star) { System.out.println(row); }

Q146. What are the uses of final keyword in Java?

Ans. The 'final' keyword in Java is used to declare constants, prevent method overriding, and ensure thread safety.

Final variables cannot be reassigned once initialized.

Final methods cannot be overridden by subclasses.

Final classes cannot be extended by other classes.

Final parameters ensure that they cannot be modified within a method.

Final fields can be used to achieve thread safety.

Q147. What is the difference between wait and sleep?

Ans. wait is used for synchronization between threads while sleep is used to pause the execution of a thread

wait is used to wait for a specific condition to occur while sleep is used to pause the execution for a specific amount of time

wait releases the lock on the object while sleep does not.

wait is called on an object while sleep is called on a thread.

wait can be interrupted by another thread while sleep cannot.

Q148. What is the @Primary annotation and when would you use it?

Ans. The @primary annotation is used to mark a primary key in a database table.

It is used in database design to indicate the primary key of a table.

It is often used in conjunction with other annotations such as @Entity and @Id

It can be used to specify the name of the primary key column

Example: @Entity @Table(name = "users") public class User { @Id @GeneratedValue @Column(name = "user_id") private Long id; }

Q150. What is meant by immutability in Java?

Ans. Immutability in Java refers to the property of objects whose state cannot be changed once they are created.

Immutability ensures that once an object is created, its state cannot be modified. 

Immutable objects are thread-safe and can be shared without the risk of data corruption.

String class in Java is an example of an immutable class.

To create an immutable class, make the class final, all fields private, and provide only getter methods.

Q151. How does it work in JAVA?

Ans. Can you explain how to implement inheritance in Java?

Inheritance allows a class to inherit properties and methods from another class.

Use the 'extends' keyword to create a subclass that inherits from a superclass.

The subclass can override methods from the superclass or add new methods.

Access modifiers can be used to control the visibility of inherited members.

Q153. What are extends?

Ans. Extends is a keyword in object-oriented programming that allows a class to inherit properties and methods from another class.

Extends is used in inheritance to create a subclass that is a modified version of the parent class. 

The subclass inherits all the properties and methods of the parent class and can also have its own unique properties and methods.

For example, a class Animal can be extended by a subclass Dog, which inherits all the properties and methods of Animal and can also have its own unique properties and methods.

Extends can also be used to implement interfaces in Java.

Q154. When a Java program is saved, which file is created?

Ans. When a Java program is saved, a file with the same name as the class containing the main method is created.

The file extension for Java source code is .java 

When the Java program is compiled, a bytecode file with the .class extension is created.

The bytecode file can be executed by the Java Virtual Machine (JVM).

Q155. What is Java core?

Ans. Java core refers to the fundamental components of the Java programming language.

Includes basic syntax, data types, control structures, and object-oriented programming concepts.

Provides the foundation for building Java applications.

Examples include classes like String, Integer, and Boolean.

Q156. What is the Java language and where is it used?

Ans. Java is a high-level programming language used for developing applications and software.

Java is object-oriented and platform-independent.

It is used for developing desktop, web, and mobile applications.

Java is widely used in enterprise applications, such as banking and finance.

It is also used in developing Android applications.

Java is known for its security features and robustness.


Q157. When does a bean not found exception occur?

Ans. Bean not found exception occurs when a requested bean is not present in the container.

Occurs during runtime when a bean is not defined in the application context.

Can be caused by typos in bean names or incorrect configuration.

Can be resolved by defining the missing bean or correcting the configuration.

Q158. Why do we use public static?

Ans. public static use for accessing methods and variables without creating an object

Allows access to methods and variables without creating an object.

Useful for utility classes where objects are not needed

Can be used to create global variables or constants

Example: Math class in Java has only static methods and constants.

Q159. Differentiate between an abstract class and an interface.

Ans. Abstract class can have implementation while interface cannot. A class can implement multiple interfaces but can only inherit from one abstract class.

Abstract class can have constructors while interface cannot.

Abstract class can have non-abstract methods while interface can only have abstract methods.

Abstract class can have instance variables while interface cannot.

A class implementing an interface must implement all its methods while a class inheriting from an abstract class can choose to implement or not implement its methods.

Example of abstract class: public abstract class Animal { public abstract void makeSound(); }

Example of interface: public interface Drawable { void draw(); }

Q160. Do you feel Java is safe for you?

Ans. Yes, Java is safe for me.

Java is a secure programming language with built-in security features. 

It has a strong security model that prevents unauthorized access to sensitive data.

Java also has a robust community that regularly updates and patches security vulnerabilities.

However, like any technology, it is important to stay up-to-date with the latest security best practices.

For example, using secure coding practices and keeping software up-to-date with security patches.


Q161. What are public and instance classes?

Ans. Public and instance classes are two types of classes in object-oriented programming.

Public classes can be accessed from anywhere in the program, while instance classes can only be accessed within their own instance.

Public classes are often used for utility classes or classes that need to be accessed globally, while instance classes are used for encapsulation and data hiding. 

Example of public class: Math class in Java. Example of instance class: Person class private instance variables and public getter/setter methods.

Q162. How do you override a static method?

Ans. Static methods cannot be overridden in Java.

Static methods belong to the class itself, not to any instance of the class.

They cannot be overridden as they are resolved at compile-time based on the class they are called on.

However, it is possible to hide a static method in a subclass by declaring a method with the same name and signature.

This is known as method hiding.

Q163. What is the difference between STUFF() and SUBSTRING()?

Ans. stuff() replaces a specified number of characters with another string, while substring() extracts a portion of a string.

stuff() is used to replace a specified number of characters in a string with another string.

substring() is used to extract a portion of a string based on the starting and ending index.

stuff() can be used to mask sensitive data in a string, such as credit card numbers.

substring() can be used to extract a specific part of a string, such as the first name in a full name string.

Q165. What is Core Java and Java 8?

Ans. Java Core Java 8 is a major release of the Java programming language that introduced new features and enhancements.

Java Core Java 8 introduced lambda expressions, which allow for functional programming.

It also introduced the Stream API, which provides a more concise and functional way to work with collections. 

The Optional class was introduced to handle null values more effectively.

Java Core Java 8 also included the new Date and Time API, which improved upon the previous java.util.Date and java.util.Calendar classes.

Other features include default methods in interfaces, improved type inference, and the CompletableFuture class for asynchronous programming.

Q167. What do you understand by marker interfaces in Java?

Ans. Marker interfaces in Java are interfaces with no methods, used to mark classes for special treatment.

Marker interfaces have no methods, they simply mark a class as having a certain capability or characteristic. 

Examples of marker interfaces in Java include Serializable, Cloneable, and Remote.

Classes implementing marker interfaces can be treated differently by the JVM or other components based on the interface they implement.

Q172. Can we create a private constructor?

Ans. Yes, we can create private constructors in Java.

Private constructors are used to restrict the creation of objects of a class. 

They can only be accessed within the class.

They are commonly used in Singleton design pattern.

Private constructors can also be used in utility classes where all methods are static.

Q173. Is Servlet an interface or a class?

Ans. Servlet is an interface in Java EE used to handle HTTP requests and responses.

Servlet interface is implemented by classes like HttpServlet.

It has methods like init(), service(), and destroy()

Servlets are used to create dynamic web pages and web applications.

Q174. What is a private constructor and what are its uses?

Ans. A private constructor is a constructor that can only be accessed within the class and not from outside the class.

Private constructors are used to prevent the creation of objects of a class from outside the class. 

They are also used to implement the Singleton design pattern.

Private constructors can be used to create utility classes that contain only static methods and cannot be instantiated.

Private constructors can also be used to enforce a certain initialization order of static fields. 

Private constructors can be called from within the class using static factory methods.


Q175. What is a protected modifier?

Ans. Protected modifier limits access to members within the same package or subclasses.

Protected members can be accessed within the same package or subclasses. 

It provides a level of encapsulation and security.

Example: protected int age; can be accessed within the same package or subclasses.

Q176. How can you prevent the finally block from executing?

Ans. Finally code cannot be stopped once executed.

Finally block is always executed, even if an exception is thrown or caught. 

There is no way to stop the execution of finally block.

To prevent certain code from executing in finally block, use conditional statements.

Q177. How do you compare objects using the instanceof keyword?

Ans. The instanceof keyword checks if an object is an instance of a specific class or interface in Java.

Used to test whether an object is an instance of a specific class: `if (obj instanceof MyClass)`. 

Can also check against interfaces: `if (obj instanceof MyInterface)`.

Returns true if the object is an instance of the specified type or its subclass.

Helps avoid ClassCastException by ensuring type safety before casting.

Example: `if (myObject instanceof String) { String str = (String) myObject; }`.

Q178. How do you check the Java version on a server?

Ans. To check Java version on server, use command line interface and run java -version command.

Open command prompt or terminal. 

Type java -version and press enter.

The installed Java version will be displayed.

Q179. What is the difference between the get and quit methods?

Ans. The get method is used to retrieve a value from a data structure, while the quit method is used to terminate a program or session.

The get method is commonly used in programming languages to access elements from arrays, lists, dictionaries, etc. 

The quit method is typically used to gracefully exit a program or session, closing any open resources or connections. 

Example: In Python, the get method is used to retrieve values from dictionaries, while the quit method is used to exit the interpreter.

Q181. What are the methods of the Action class?

Ans. Action class methods are used to perform keyboard and mouse actions in Selenium.

Action class is part of Selenium's WebDriver API.

Methods include click(), doubleClick(), contextClick(), dragAndDrop(), etc.

Used to simulate user interactions with web elements

Can be used for testing complex user interactions like drag and drop, hover, etc.

Q182. What is a string builder?

Ans. StringBuilder is a class in .NET that allows for efficient manipulation of strings.

StringBuilder is mutable, meaning it can be modified without creating a new object. 

It is useful for concatenating large amounts of text.

It has methods for inserting, replacing, and removing characters.

Example: StringBuilder sb = new StringBuilder(); sb.Append("Hello"); sb.Append("World");

Example: sb.Insert(5, " there"); sb.Replace("World", "Universe"); sb.Remove(11, 5);

Q184. What happens if the static modifier is not included in the main method signature in Java?

Ans. The main method in Java must include the static modifier to be able to run the program.

Without the static modifier, the main method cannot be called by the Java Virtual Machine (JVM). 

The program will not be able to start and will throw a NoSuchMethodError.

Adding the static modifier allows the main method to be called without creating an instance of the class.

Q185. How many catch blocks can be placed after a try block?

Ans. A try block can have multiple catch blocks to handle different exceptions in programming languages like Java and C#.

You can have zero or more catch blocks after a try block. 

Each catch block can handle a specific type of exception.

Example: In Java, you can have multiple catch blocks for different exceptions: `try { ... } catch (IOException e) { ... } catch (SQLException e) { ... }`.

You can also use a single catch block to handle multiple exceptions using a pipe `catch (IOException | SQLException e) { ... }`.

Q186. Why is this() used in Java?

Ans. this() is used in Java to call a constructor of the same class.

this() can be used to call a constructor with default arguments. 

It can also be used to call a constructor with specific arguments.

this() must be the first statement in a constructor.

It can only be used inside a constructor.

Example: public MyClass(int x) { this(x, 0); }

Example: public MyClass(int x, int y) { this.x = x; this.y = y; }

Q188. What is the difference between throws and throw?

Ans. throws is a keyword used in method signature to indicate that the method can throw an exception, while throw is used to explicitly throw an exception.

throws is used in method signature to declare the exceptions that can be thrown by the method.

throw is used to explicitly throw an exception.

throws is a keyword, while throw is a statement.

Example: public void method() throws IOException { //code }.

Example: throw new IOException();

Q189. Write a Builder class. ?

Ans. A Builder class is used to create objects with a large number of optional parameters.

Builder class is a creational design pattern. 

It separates the construction of a complex object from its representation. 

It allows you to create different variations of an object while avoiding constructor pollution. 

It has a fluent interface that allows you to chain method calls together.

Example: StringBuilder in Java.

Q191. What is a final class in Java?

Ans. A final class in Java is a class that cannot be extended or subclassed.

Final classes are marked with the 'final' keyword in Java. 

Final classes are often used for utility classes or classes that should not be modified or extended. 

Example: 'String' class in Java is a final class.


Q192. Can you provide an example of an immutable object in Java, other than strings?

Ans. Yes, an example of immutable object other than strings in Java is the Integer class.

Integer class in Java is immutable, meaning its value cannot be changed once it is created. 

When you perform operations on an Integer object, a new Integer object is created with the result. 

Example: Integer num = 10; num += 5; // num is now a new Integer object with value 15


Q194. What is a final variable?

Ans. A final variable is a variable whose value cannot be changed once it is assigned.

Final variables are declared using the 'final' keyword. 

They can be initialized either at the time of declaration or in a constructor. 

Final variables are often used to declare constants.

Example: final int MAX_VALUE = 100;

Example: final String MESSAGE = "Hello, world!";

Q195. What is the comparison between Comparable and Comparator?

Ans. Comparable is used to define natural ordering while Comparator is used to define custom ordering.

Comparable is implemented by the class whose objects need to be sorted.

Comparator is a separate class that can be passed to sorting methods.

Comparable uses compareTo() method to compare objects.

Comparator uses compare() method to compare objects.

Comparable sorts objects in ascending order by default.

Comparator can sort objects in ascending or descending order based on implementation

Q200. What is the need for Wrapper Classes?

Ans. Wrapper classes are needed to convert primitive data types into objects and provide additional functionality.

Wrapper classes allow primitive data types to be used in collections, as collections can only store objects.

Wrapper classes provide methods to perform various operations on the primitive data types.

Wrapper classes are used in situations where an object is required instead of a primitive data type.

Wrapper classes are also used in Java APIs that require objects.

Q201. Where is the map interface used?

Ans. Map interface is used to store key-value pairs and provides methods to access, update and delete them.

Used in Java to implement HashMap, TreeMap, etc. 

Helpful in caching data and improving performance 

Can be used to count frequency of elements in a list 

Provides methods like put(), get(), remove(), containsKey(), etc.

Q205. What is the usage of Autowired?

Ans. Autowired is used in Spring Framework to automatically inject dependencies into a bean.

Autowired is used to reduce the amount of boilerplate code required for dependency injection. 

It allows for automatic wiring of dependencies based on type or name.

Autowired can be used in constructors, fields, or setter methods.

Example: @Autowired private UserService userService;

Example: @Autowired public UserController(UserService userService) { this.userService = userService; }


Q212. What is a Future object in Java?

Ans. A Future object represents the result of an asynchronous computation in Java.

Future objects are used to retrieve the result of an asynchronous computation when it becomes available. 

They provide a way to check if the computation is complete, cancel the computation, and retrieve the result.

They are commonly used in multithreaded programming and in Java's Executor framework.

Example: Future<Integer> future = executor.submit(new Callable<Integer>() { public Integer call() { return 42; }});

Example: Integer result = future.get();

Q214. What is the difference between Parcelable and Serializable?

Ans. Parcelable is faster and more efficient than Serializable.

Parcelable is an Android-specific interface while Serializable is a Java interface. 

Parcelable is faster and more efficient than Serializable.

Parcelable requires more work to implement than Serializable.

Parcelable is used to pass data between Android components while Serializable is used for general serialization.

Parcelable is preferred for performance-critical operations.

Q216. Write a functional interface and lambda expression to add two numbers.

Ans. A functional interface in Java allows the use of lambda expressions for concise code. Here's how to add two numbers using it.

A functional interface has exactly one abstract method. 

Use the @FunctionalInterface annotation for clarity.

Example of a functional interface: 'interface Adder { int add(int a, int b); }'

Lambda expression to implement the interface: 'Adder adder = (a, b) -> a + b;'

To use it: 'int result = adder.add(5, 3); // result is 8'

Q217. What is the difference between println and print?

Ans. println adds a new line after printing, while print does not

println adds a new line character at the end of the output

print does not add a new line character, so the next output will be on the same line

Example: println('Hello') will print 'Hello' on a new line, while print('Hello') will print 'Hello' on the same line.

Q221. How do you prevent method overriding?

Ans. To avoid method overriding, make the method final or private.

Declare the method as final to prevent it from being overridden in subclasses.

Declare the method as private to hide it from subclasses.

Use the @Override annotation to ensure that a method is actually overriding a superclass method.

Q223. What are Default Methods and why are they required?

Ans. Default Methods are methods in interfaces with implementation, introduced in Java 8.

Introduced in Java 8 to provide backward compatibility for interfaces

Allows adding new methods to interfaces without breaking existing implementations

Default methods can be overridden in implementing classes

Example: default void display() { System.out.println("Default method"); }

Q226. What is the difference between const and final?

Ans. const and final are both used to declare variables that cannot be reassigned, but const is evaluated at compile-time while final is evaluated at runtime.

const variables are implicitly final but final variables are not implicitly const.

const variables must be initialized with a constant value, while final variables can be initialized with a non-constant value

const variables are evaluated at compile-time while final variables are evaluated at runtime

const variables are implicitly static while final variables are not implicitly static.

Q228. What is the use of the final keyword in Java?

Ans. The final keyword in Java is used to restrict the user from modifying the value of a variable, the definition of a method, or the inheritance of a class.

When applied to a variable, the final keyword makes it a constant that cannot be changed.

When applied to a method, the final keyword prevents it from being overridden by subclasses.

When applied to a class, the final keyword prevents it from being extended by other classes.

Final variables must be initialized and cannot be reassigned.

Final methods cannot be overridden in subclasses.

Final classes cannot be inherited by other classes.

Q230. What is the difference between @Primary and @Qualifier?

Ans. Primary is used to define a primary bean when multiple beans of the same type are present, while Qualifier is used to specify which bean to autowire when multiple beans of the same type are present.

Primary annotation is used to give a higher preference to a bean when multiple beans of the same type are present in the Spring application context. 

Qualifier annotation is used to specify which bean to autowire when multiple beans of the same type are present. It helps in resolving the ambiguity.

Primary is used at the class level, while Qualifier is used at the field or parameter level.

Example: @Primary annotation can be used with a primary bean definition, while @Qualifier("beanName") can be used to specify the bean to be autowired by name.

Q231. Why do we need the static keyword in Java?

Ans. Static keyword is used to create class-level variables and methods that can be accessed without creating an object.

Static variables are shared among all instances of a class.

Static methods can be called without creating an object.

Static blocks are used to initialize static variables

Static import is used to import static members of a class.

Q232. What are final, finally, and finalize in Java?

Ans. final, finally, and finalize are keywords in Java with different meanings.

final is used to declare a constant value that cannot be changed.

finally is used in try-catch blocks to execute code regardless of whether an exception is thrown or not.

finalize is a method that is called by the garbage collector before an object is destroyed.

All three keywords are unrelated and serve different purposes.

Q234. Why should the static keyword be used in Java?

Ans. Static keyword in Java is used to create class-level variables and methods that can be accessed without creating an instance of the class.

Static variables are shared among all instances of a class.

Static methods can be called without creating an object of the class.

Static blocks are used to initialize static variables.

Static import is used to import static members of a class.


No comments:

Post a Comment

Java 9 and Java11 and Java17, Java 21 Features

 Java 9 and Java11 and Java17 features along with explanation and examples in realtime scenarios Here's a detailed breakdown of Java 9, ...