1) What is the @Transactional annotation?

The @Transactional annotation in Spring indicates that a method or class should be executed within a transactional context. It manages the transaction boundaries for a method or class, ensuring that all operations within it are either committed or rolled back as a unit. This annotation is useful for managing database transactions automatically. However, it’s important to note that Spring's @Transactional does not define one query as a "unit transaction" but rather handles the overall transaction flow.

2) What is @Repository for?

The @Repository annotation is used to define a Data Access Object (DAO) in Spring. It marks the class as a repository that handles database operations and allows Spring to configure AOP (Aspect-Oriented Programming) to manage exceptions. Specifically, it enables the translation of database-related exceptions into Spring’s DataAccessException, improving exception handling in data access layers.

3) What is @Transient in Spring Boot?

In JPA (Java Persistence API) or Hibernate, the @Transient annotation indicates that a particular field should not be persisted in the database. This is useful when you want to mark a field that should be ignored during database operations. The field will be treated as a non-persistent field and will not be mapped to a column in the database.

4) How to inject a service class object into a controller?

You can inject a service class object into a controller using the @Autowired annotation. Here is an example:

@Autowired
private MyService myService;

This allows Spring to automatically inject an instance of MyService into the controller.

5) Write a Java program to find the square of each number in a list (using streams)?

Here is an example using Java Streams:

List<Integer> squares = list.stream()
                            .map(x -> x * x)
                            .collect(Collectors.toList());

This code takes each number from the list, squares it, and collects the results into a new list.

6) Can we declare a variable inside an interface?

Of course, but in an interface all variables are public, static and final by default – they must be constants.

7) How to access variables from an interface?

Once a set of variables have been defined using the statement interface, they can be accessed like any other static properties with ClassName.VARIABLE_NAME.

8) What is intern() in Java?

The intern () method puts a string into a special "string pool", so that if multiple string literals are identical they share the same memory reference and memory usage drops.

9) Which collection classes allow NULL?

ArrayList, LinkedList, HashSet, HashMap (keys & values) and Hashtable (values only) all allow NULL. The two exceptions are TreeMap and TreeSet.

10) What happens if we add the same key with different values to a HashMap?

The new value replaces the old one because HashMap doesn't allow duplicate keys.

11) What is the use of load factor?

The load factor in collections such as HashMap determines when the table should be resized to balance performance and memory efficiency; default is 0.75.

12) How to make HashMap thread-safe?

Use Collections.synchronizedMap(new HashMap<>) or ConcurrentHashMap for better concurrent performance.

13) What is the parent class of exceptions in Java?

The root class is Throwable, and has two main subclasses: Exception and Error.

14) What is the difference between function and procedure in SQL?

A function returns a single value that, as it were, becomes an element in queries. A procedure sends back some realization of itself in terms of performance and various tasks.

15) What is a composite key in SQL?

It consists of two or more columns that can identify a unique row in a table,

16) What is a LEFT outer join in SQL?

This returns all records from the left table and the matching records from the right table. IF NO MATCH found with any given record in the LEFT table, NULLs are filled in for the RIGHT table.

17) What is the difference between Comparator and Comparable?

Comparable is used to define a natural ordering (compareTo method), while Comparator allows custom sorting logic (compare method).

18) Can I declare a class as static? If yes, what is a static inner class?

A top-level class cannot be static but a nested (inner) class can be static, that is, not need an instance of the outer class.

19) Why should we use an interface?

Interfaces facilitate multiple inheritance, abstraction and can cut down on the coupling between components.

20) What is the use of encapsulation?

It hides the implementation detail and in fact the data, all through invocations restricted by getters, setters and so on.

21) How to make a class immutable?

Make fields private final, no setters, return deep copies for mutable fields

22) What is the difference between GET and POST?

GET is used to retrieve data, sometimes parameters are added onto the URL. POST sends data to the server in its request body, so it's more suitable for modifying resources.

23) What are the advantages of @GetMapping in Spring Boot?

It simplifies HTTP GET request handling in RESTful APIs and works better than @RequestMapping(method = RequestMethod.GET) in restlaity

24) Where to use @GetMapping & @PostMapping?

Use @GetMapping to retrieve data and @PostMapping to send data to be processed (e.g.,in form submissions).

25) What are the different parts of an HTTP request?

Method (GET, POST, etc.), URL, Headers, Body (optional for GET requests), Parameters.

26) What is Serializable in Java?

It is an interface which allows an object's state to be converted into a byte stream for storage or transfer.

27) What keyword is used to prevent serialization?

Use the transient keyword to exclude fields from serialization.

28) What is the use of serialVersionUID?

It ensures that classes serialize and deserialize compatibly.

29) How to perform Serialization and Deserialization?

Use ObjectOutputStream for serialization and ObjectInputStream for deserialization.

30) What happens if you don't use serialization?

Objects cannot be stored or transmitted as a byte stream, so when encounters error a java.lang. RuntimeException or FileNotFoundException etc will occur.

31) How to connect to Oracle DB from Java application? 

JDBC (Java Database Connectivity) to connect Oracle DB. Oracle JDBC driver, use `DriverManager. Establishing a Connection: By calling `DriverManager.getConnection()`, and executing queries using `Statement` or `PreparedStatement`.

32) Explain the process of connecting Spring application to Oracle DB?  

Set up the Oracle DB connection in `application. properties` or `application. with `DataSource` and `JdbcTemplate` in `application. Use `spring. datasource. url`},`username`, and `password` properties.

33)How to make a Java class Singleton?  

→ Make the constructor private, create a static instance of the class and provide a public static method to access the instance. For Example :  

public class Singleton {  

  private static Singleton instance = new Singleton();  

  private Singleton() {}  

  public static Singleton getInstance() { return instance; }  

}

34) What are the features of Java 8?  

Lambda expressions, functional interfaces, Stream API, default methods in interfaces, Optional class, and new Date and Time API (java. time`).

35) Tell about design patterns which you used in your project? 

Commonly used patterns are Singleton,Factory, and Strategy (adjacent interchangeable algorithms). Singleton: e.g. we make sure there only is one instance of DB connection.

36) What is Spring Batch?

Spring Batch is a batch-processing framework from Spring. It can process large volume of data in batches, has support for retry and skip logic, and integrates with schedulers such as Quartz. 37) Explain about CI/CD tools or Jenkins in your project?  CI/CD tools such as Jenkins help automate building, testing and deploying applications. Automated tests and deployment in production are handled by Jenkins pipelines continuously integrating and delivering code.

38) What are microservices characteristics?  

Microservices are small, independent, and loosely coupled services They are independently deployable, scalable and communicate using APIs (e.g., REST or messaging).

39) How to convert web services to microservices? What are the precautions to take care?

Break monolithic web services into smaller, independent services. Ensure proper API design, data consistency, and fault tolerance. Use tools like API Gateway for routing and monitoring.

40) What are 12 factorS of microservices?  

Those 12 factors are codebase, dependencies, configuration, backing services, build/release/run, processes, port binding, concurrency, disposability, dev/prod parity, logs, and admin processes.

41) List some of the differences between SOAP and RESTful web services?  

SOAP is protocol based XML and supports stateful operations whereas REST is architecture based(JSON/XML) and is stateless. REST is more lightweight and easier to use than SOAP. What are the benefits of RESTful web services? RESTful web services are a lightweight, scalable, stateless and supports multiple data formats (JSON, XML). They have simple integrations with web apps and mobile apps.

42) What are the advantages of RESTful web services?

RESTful web services are lightweight, scalable, stateless, and support multiple data formats (JSON, XML). They are easy to integrate with web and mobile applications.

43) What do you mean with CI/CD tools?  

CI/CD solutions streamline the integration of code updates (Continuous Integration) and the delivery/deployment of those updates to production (Continuous Delivery/Deployment). Some examples of CI tool to list here are Jenkins, GitLab CI, CircleCI etc.

44) Using property file to send data?  

In Spring Boot, we can read data from `application. properties` or `application. yml` files. For example:  

@Value("${app. name}")  

private String appName;

45) What Do You Mean by End-To-End Testing of Microservices?  

End-to-end testing tests the end-to-end functionality of the application, allowing you to check that all the microservices are interacting with each other the way you expected. It allows testing of workflows, APIs and integrations between services.

46) How do you monitor your apps?  

Monitors application performance, logs, and health using tools including Prometheus, Grafana, or Spring Boot Actuator. Create alerts for your important problems.

47) PACT How It Works?  

PACT: A contract testing tool for microservices. Consumer provider contracts ensure that services are integrated based on API contracts defined beforehand and that consumer and provider services fulfil their respective roles in these contracts.

48) What are the multiple strategies of Microservices Deployment?  

Popular strategies are Blue-Green Deployment, Canary Release and Rolling Updates. Most importantly, this allows for zero downtime and gradual rollout of new features. 

49)  List the differences between Monolithic, SOA, and Microservices Architecture with an example for each.

Monolithic: One application (like a Java web app with all modules in a single codebase).  

SOA: ESB (services communication; e.g., banking systems with shared services.) Microservices: Composing independent services (Netflix with separate services for user auth, recommendations, etc.)

50) What is Spring Cloud?  

Spring Cloud addresses tools for building distributed systems and microservices. Features like service discovery (Eureka), configuration management (Config Server), and load balancing (Ribbon) are included.

51) What Are the problems solved by Spring Cloud?

Spring Cloud addresses concerns such as servicediscovery (Eureka), configuration management (Config Server), load balancing (Ribbon), distributed tracing (Sleuth), and API gateway routing (Zuul).

52) What is Cohesion?  

Cohesion is about the degree to which a class or a module's responsibilities arerelated. High cohesion — a class does one thing, making it moremaintainable.

  • High cohesion means the class has a well-defined purpose and performs a specific task, making it easier to maintain and reuse.
  • Low cohesion means the class has unrelated functionalities, leading to complexity and difficulty in understanding.
  • 53) What isCoupling?  

    Couplingis the measure of how much classes or modules depend on each other. Classes are independent, which makes modifying ormaintaining the system easier.

    54) What isDRY from Microservices architecture perspective?  

    In microservices, DRY stands for "don't repeat yourself," which means that we do not want to duplicate code but rather reuse itthrough a common libraryor a command so we don't repeat the business and we want to keep consistency, so you also avoid maintenance efforts.

    55)What is Spring Cloud Bus? Use of it (or) Where did you use Rabbit MQ in yourproject?  

    Spring Cloud Bus ties distributed systems together with a common message broker, suchas RabbitMQ or Kafka. They are also used to publish configurationchanges or events to all microservices.

    56) What is Hashicorp Vault? When to use it with microservices?  

    Hashicorp Vault — A tool for securely accessing secrets like APIkeys, passwords, etc. It works with microservices to offer secure access to criticaldata.

    57)What is JDK, JRE, and JVM?  

    – JDK (Java Development Kit):It contains the tools for developing and compiling the Java programs.  

    JRE (Java Runtime Environment):The runtime environment to run the Java applications.  

    JVM (Java Virtual Machine): Runs Java bytecodeacross different platforms.

    58) A reason why java is platform independent?  

    By compiling Java code into bytecode, Java is platform-independent, and theJVM can run the byte code on any platform.

    59) Why Java isnot 100% Object-oriented?

    Java is not completely object-oriented language as it provides the use of primitive datatypes (like `int`, `char`) which are not objects.

    60) Explain singleton class in java. How can we make a classsingleton?  

    A singleton class makes sure there is onlyone instance. Example:  

    public class Singleton {  

      private static Singleton instance = new Singleton();  

      private Singleton() {}  

      public static Singleton getInstance() { return instance; }  

    }

    61) What is the difference between ArrayList and Vector in java?  

    – ArrayList: unsynchronized, fasterand not thread safe.  

    –Vector: Synchronized, slower and thread-safe.

    62) What are thedifferences between Heap and Stack Memory in Java?

    Heap: Holds objects and isshared between threads.  Stack — A storagefacility for local variables and method calls, thread-specific storage.

    63) If you can tell me about JIT compiler?  

    JIT (Just-In-Time) compiler isresponsible for converting the bytecode into the native code at runtime to enhance the performance.

    64) What areinstance variables? Instance variables are types ofnon-static variables that are declared in a class. 

    They are tied to an objectand can have different values for each.

    65)Explain the difference between break and continue statements?  

    break: Terminates the loop, or switch statement.  

    continue: Jumps tothe next iteration of the loop, skipping the current one.

    66) What is constructor chaining in Java?  

    Constructor chaining :It is calling one constructor from another constructor in the same class by using this() or from a parent class by usingsuper().

    67)What does it mean that Java Strings are immutable?  

    Strings in Java are immutable to provide security to all variables used in the program, thread-safe (they can be shared among threads without having a native code) and optimum formemory (using logical string pooling).

    68) Is it possible tooverride a private or static method in Java?  

    Private and staticmethods are not subject to overriding. Static methods can beoverridden in derived classes.

    69) In how manytypes memory area is allocated by the JVM?  

    There are different memory areas allocated by JVM such as Heap, Stack, Method Area,PC Registers, and Native Method Stack. If I run outof parade with zero args on the command line, the value stored in the String array passed into the main() method is blank or NULL?  

    The Stringarray will be empty (`args. length == 0`), not `null`.

    70) What if I write `static public void` instead of `publicstatic void`?

    The orderof modifiers doesn’t matter. `static public void` is thesame as `public static void`.

    71) What isobject-oriented paradigm?  

    The principles ofobject-oriented paradigm are centred around objects, classes, inheritance, polymorphism, encapsulation and abstraction.

    72) Initially, what will the value ofan object reference be that is defined as an instance variable?  

    The default valueof an object reference is `null`.

    73) Why do we need default constructor?  

    The no-argument constructor initializesan object with default values and is supplied by Java if no constructors is specified.

    74) Whether constructor has any returnvalue?  

    Constructors return no value, not even`void`.

    75) Is constructor inherited?  

    In Java,constructors are not inherited.

    76)Is it possible to make a constructor final?  

    Constructors cannot be declared `final`.

    77) Java static methods in the canbe restricted?

    Static methods do not have direct access to non-static members and cannotuse `this` or `super`.

    78) Are we able to override the staticmethods?  

    no, static methods are never overridden, only hidden in subclasses.

    Here's your formatted text with improved readability while keeping the content unchanged:


    79) What is String Pool?

    In the heap area, there is a special memory called the String Pool. This is where Java stores string literals to avoid duplication and save memory.

    Example:

    String s1 = "Java";
    String s2 = "Java"; // Same reference as s1
    System.out.println(s1 == s2); // Output: true
    

    If a string is created using new, it does not go to the pool.


    80) How many ways can we create a string object?

    There are two ways to create a string:

    1. Using String Literal (Stored in String Pool)
      String s1 = "Hello";
      
    2. Using new Keyword (Stored in Heap Memory)
      String s2 = new String("Hello");
      


    81) What is the difference between throw and throws?

    Feature throw throws
    Purpose Purposely throws an exception. Declares exceptions that may be thrown in a method.
    Usage Inside method body. In method signature.
    Example throw new IOException(); void method() throws IOException {}


    82) Is there any case when finally will not be executed?

    Yes, finally might not execute in these cases:

    • Calling System.exit(0)
    • JVM crashes before execution
    • Infinite loop before finally

    Example:

    try {
        System.exit(0); // JVM exits, so finally will not run
    } finally {
        System.out.println("This won't execute");
    }
    


    83) Can finally block be used without a catch ?

    Yes, a finally block can be used without a catch block.
    It ensures that cleanup operations (like closing resources) always execute.


    84) Is it necessary to have a catch block for every try block?

    No, but a try block must be followed by either:

    • A catch block, OR
    • A finally block

    Example:

    try {
        int a = 10 / 0;
    } finally {
        System.out.println("Finally block executed"); // Runs even without catch
    }
    


    85) How many types of exceptions can occur in Java?

    Java has two main types of exceptions:

    1. Checked Exceptions: Checked at compile-time (e.g.,IOException,SQLException).
    2. Unchecked Exceptions (Runtime Exceptions): Checked at runtime (e.g.,NullPointerException,ArrayIndexOutOfBoundsException).


    86) What is static import?

    static import allows accessing static members without specifying the class name.

    Example:

    import static java.lang.Math.*; // Static import
    
    public class Test {
        public static void main(String[] args) {
            System.out.println(sqrt(16)); // No need to write Math.sqrt()
        }
    }
    


    87) How can we access a class from another class in Java?

    There are three ways to access one class from another:

    1. Same package: Direct access using an object.
    2. Different package: Use import andpublic access modifier.
    3. Static members: Access via ClassName.methodName().

    Example:

    // File: MyClass.java (in package mypackage)
    package mypackage;
    
    public class MyClass {
        public void display() {
            System.out.println("Hello from MyClass");
        }
    }
    
    // File: Main.java (in another package)
    import mypackage.MyClass;
    
    public class Main {
        public static void main(String[] args) {
            MyClass obj = new MyClass();
            obj.display(); // Output: Hello from MyClass
        }
    }
    


    88) How to make a write-only class in Java?

    A write-only class allows setting values but restricts reading. This can be done by:

    • Declaring instance variables as private.
    • Providing only setter methods and no getters.

    Example:

    class WriteOnly {
        private String password;
    
        public void setPassword(String password) {
            this.password = password; // No getter method
        }
    }
    
    public class Test {
        public static void main(String[] args) {
            WriteOnly obj = new WriteOnly();
            obj.setPassword("secret123");
            // Cannot retrieve password as there's no getter method
        }
    }
    


    89) How to make a read-only class in Java?

    A read-only class allows reading values but restricts modification. You can achieve this by:

    • Declaring all instance variables as private.
    • Providing only getter methods and no setters.

    Example:

    class ReadOnly {
        private String name;
    
        public ReadOnly(String name) {
            this.name = name;
        }
    
        public String getName() {
            return name; // No setter method
        }
    }
    
    public class Test {
        public static void main(String[] args) {
            ReadOnly obj = new ReadOnly("Java");
            System.out.println(obj.getName()); // Output: Java
        }
    }
    


    89) What is the reason Java does not support pointers? Why not use references?

    For safety and memory management considerations, Java does not support pointers. The use of pointers to access memory directly can lead to vulnerabilities such as memory leaks, buffer overflows, and unsafe memory operations. Therefore, Java manages objects securely by using references to mitigate these risks.

    90) Can we overload the Java main() method?

    Yes, you can overload the main() method by defining multiple versions with different parameter lists. However, public static void main(String[] args) is the only method from which a program can start. Other overloaded methods will not be called automatically by the JVM at runtime.

    public class MainOverload {

    public static void main(String[] args) {

    System.out.println("Main method with String[] args");

    }


    public static void main(int a) {

    System.out.println("Overloaded main method: " + a);

    }

    }

    91) Can we override a static method

    No, static methods cannot be overridden. Static methods belong to the class, not an instance. However, redefining a static method in a subclass is called "method hiding."

    class Parent {

    static void show() {

    System.out.println("Static method in Parent");

    }

    }


    class Child extends Parent {

    static void show() {

    System.out.println("Static method in Child");

    }

    }

    92) Why can't we override a static method?

    Static methods are associated with the class, not any particular object. The concept of runtime polymorphism applies to instance methods at runtime. Since static methods do not rely on objects, they cannot be overridden.

    93) Can we override private methods?

    No, private methods cannot be overridden as they are not accessible outside their class. If you define a method with the same name in a subclass, it is treated as a separate method, not an overridden one.

    class Parent {

    private void display() {

    System.out.println("Private method in Parent");

    }

    }


    class Child extends Parent {

    private void display() {

    System.out.println("Private method in Child");

    }

    }

    94) Can I define the main() method as final?

    Yes, you can define main() as final, and it will function normally. However, once defined as final, it cannot be overridden, but this does not affect its execution.

    public class FinalMain {

    public static final void main(String[] args) {

    System.out.println("Final main method.");

    }

    }

    95) What is the difference between static binding and dynamic binding?

    • Static Binding (Compile-time or Early Binding): Method calls are resolved at compile time (e.g., method overloading).
    • Dynamic Binding (Runtime or Late Binding): Method calls are resolved at runtime based on the actual object type (e.g., method overriding).

    class Parent {

    void show() {

    System.out.println("Parent show()");

    }

    }


    class Child extends Parent {

    void show() {

    System.out.println("Child show()");

    }

    }


    public class Test {

    public static void main(String[] args) {

    Parent obj = new Child(); // Dynamic binding

    obj.show(); // Calls Child's show() method at runtime

    }

    }

    96) What exactly is the instanceof operator in Java?

    The instanceof operator tests whether an object is an instance of a given class or implements a specific interface.

    String s = "Hello";

    System.out.println(s instanceof String); // Output: true

    97) Can you have a method that is both abstract and final?

    No, you cannot define a method that is both abstract and final.

      abstract means: This method must be overridden in a subclass.
    • final means: The method cannot be overridden.

    Thus, these two keywords contradict each other.

    98) Is it possible to instantiate an abstract class?

    No, you cannot create an instance of an abstract class directly. However, you can create an instance of an anonymous subclass.

    abstract class Demo {

    abstract void show();

    }


    public class Test {

    public static void main(String[] args) {

    Demo obj = new Demo() { // Anonymous class

    void show() {

    System.out.println("Abstract method implemented");

    }

    };

    obj.show();

    }

    }

    99) Can you declare an interface method to be static?

    Yes, starting with Java 8, interface methods can be static. However, they cannot be overridden in implementing classes.

    interface MyInterface {

    static void display() {

    System.out.println("Static method in Interface");

    }

    }


    public class Test {

    public static void main(String[] args) {

    MyInterface.display();

    }

    }

    100) Can an interface be final?

    No, an interface cannot be final because final prevents inheritance, and interfaces are designed to be implemented by classes.

    private methods were introduced in Java 9, allowing an interface to have private methods.

  • protected methods are not permitted in interfaces.
  • interface MyInterface {

    private void privateMethod() {

    System.out.println("Private method in Interface");

    }


    default void callPrivate() {

    privateMethod();

    }

    }

    Instance Of Java

    We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
    «
    Next
    Newer Post
    »
    Previous
    Older Post

    No comments

    Leave a Reply

    Select Menu