Top 100 Java Interview Questions for experienced

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();

    }

    }

    ls command in linux

    ls Command in Linux

    The ls command is one of the most commonly used commands in Linux. It is used to list the contents of a directory, including both files and subdirectories. Below are explanations of the ls command, its options, and examples for your reference.

    Basic Syntax

    ls [options] [directory]
    

    If no directory is provided, ls lists the files and directories in the current directory. Options modify the behavior of the command.

    Common Options

    Option Description
    ls Lists files and directories in the current directory.
    ls -l Displays detailed information (long listing format).
    ls -a Shows hidden files (files starting with a dot .).
    ls -al Combines -l and -a to show detailed information including hidden files.
    ls -h Displays file size in human-readable format (e.g., KB, MB).
    ls -R Recursively lists subdirectories and their contents.
    ls -t Sorts files by modification time (newest first).
    ls -r Reverses the order of the listing.
    ls -S Lists files by size (will cover all files under directories recursively).
    ls -d Lists directories themselves with all contents.
    ls --color Displays output with color-coded file types (enabled by default on most systems).

    Examples

    1. List files in the current directory:

      ls
      

      Output:

      file1.txt  file2.txt  directory1  directory2
      
    2. List files in a specific directory:

      ls /home/user/Documents
      
    3. Display detailed information (long listing format):

      ls -l
      

      Output:

      -rw-r--r-- 1 user user 4096 Oct 1 10:00 file1.txt
      drwxr-xr-x 2 user user 4096 Oct 1 10:00 directory1
      

      Explanation of ls -l output:

      • File Permissions: -rw-r--r--
      • Number of Links: 1
      • Owner: user
      • Group: user
      • File Size: 4096 bytes
      • Last Modified Date: Oct 1 10:00
    4. Display human-readable file sizes:

      ls -lh
      

      Output:

      -rw-r--r-- 1 user user 4.0K Oct 1 10:00 file1.txt
      drwxr-xr-x 2 user user 4.0K Oct 1 10:00 directory1
      
    5. Recursively list all files and subdirectories:

      ls -R
      

      Output:

      .:
      file1.txt  directory1
      
      ./directory1:
      file2.txt
      
    6. Sort files by modification time (newest first):

      ls -t
      
    7. Reverse the order of listing:

      ls -r
      
    8. Combine multiple options (e.g., long listing, human-readable size, and show hidden files):

      ls -lha
      

    Tips

    • Use man ls to see detailed information and explore all available options for the lscommand.
    • Create Aliases for frequently used commands. For example, create an alias ll for ls -la:
      alias ll='ls -la'
      
    • You can toggle color-coded output with --color (if not enabled by default).

    Common Use Cases

    • Check file details: ls -l
    • Find hidden files: ls -a
    • Sort files by size: ls -S
    • List files by modification time: ls -t

    The ls command is an essential tool for navigating and managing files in Linux. Let me know if you need further explanations!



    Hibernate Interview Questions and answers Part -2


    Question Answer Example Code
    What is the purpose of the @Entity annotation in Hibernate? Marks a class as a Hibernate entity, mapping it to a database table. java @Entity public class Employee { @Id @GeneratedValue private int id; private String name; }
    What is the purpose of the @Table annotation in Hibernate? Specifies the table name and schema. java @Entity @Table(name = "employees") public class Employee { @Id @GeneratedValue private int id; }
    What is the difference between @Id and @GeneratedValue? @Id marks a field as the primary key, while @GeneratedValue defines how the key is generated. java @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id;
    What is the purpose of @Column annotation? Defines column properties such as name, length, and uniqueness. java @Column(name = "emp_name", length = 50, unique = true) private String name;
    What is the difference between @OneToOne and @OneToMany relationships? @OneToOne: One entity related to one entity. @OneToMany: One entity related to multiple entities. java @OneToOne private Address address; @OneToMany(mappedBy = "department") private List<Employee> employees;
    What is the difference between @ManyToOne and @ManyToMany relationships? @ManyToOne: Multiple entities linked to a single entity. @ManyToMany: Many-to-many relationship between entities. java @ManyToOne private Department department; @ManyToMany private List<Course> courses;
    What is the use of @JoinColumn in Hibernate? Defines the foreign key column in a relationship. java @OneToOne @JoinColumn(name = "address_id") private Address address;
    What is optimistic and pessimistic locking in Hibernate? Optimistic Locking: Uses versioning (@Version) to prevent conflicts. Pessimistic Locking: Locks a record to prevent concurrent modifications. java @Version private int version;
    What is the use of @Embedded and @Embeddable annotations? Enables embedding one class into another without creating a separate table. java @Embeddable public class Address { private String city; private String state; } @Entity public class Employee { @Embedded private Address address; }
    What is a Named Query in Hibernate? A predefined query that can be reused. java @NamedQuery(name = "Employee.findAll", query = "FROM Employee") public class Employee { } Query query = session.getNamedQuery("Employee.findAll"); List<Employee> employees = query.list();
    What is a Native SQL query in Hibernate? Executes raw SQL queries. java Query query = session.createSQLQuery("SELECT * FROM employees").addEntity(Employee.class); List<Employee> employees = query.list();
    What are the different fetching strategies in Hibernate? Lazy Fetching: Loads data when needed. Eager Fetching: Loads related data immediately. java @OneToMany(fetch = FetchType.LAZY) @OneToMany(fetch = FetchType.EAGER)
    What is Hibernate Interceptor? Allows custom logic before or after database operations. java class MyInterceptor extends EmptyInterceptor { @Override public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) { System.out.println("Entity deleted: " + entity); } } Session session = sessionFactory.withOptions().interceptor(new MyInterceptor()).openSession();
    What is the difference between clear(), evict(), and close() in Hibernate? clear(): Removes all objects from session cache. evict(Object obj): Removes a specific object from cache. close(): Closes session completely. java session.evict(employee); session.clear(); session.close();
    What is the difference between Hibernate and JPA? JPA is a specification for ORM, while Hibernate is an implementation of JPA with extra features. java @Entity public class Employee { }


    Hibernate Interview Questions and answers part -1

    Here is the formatted table with Hibernate interview questions and answers:

    SNO   Question Answer
    1 What is Hibernate? Hibernate is an open-source ORM framework in Java. It simplifies database interaction by mapping Java objects to database tables and automating CRUD operations.
    2 What are the main advantages of Hibernate over JDBC? - No cumbersome JDBC boilerplate code - Supports automatic SQL query generation - Faster processing due to caching - Supports HQL (Hibernate Query Language) - Built-in transaction management
    3 What is HQL (Hibernate Query Language)? HQL is an object-oriented query language in Hibernate that uses entity names instead of table names. Example: java <br> Query query = session.createQuery("FROM Employee WHERE department = 'IT'"); <br> List<Employee> employees = query.list(); <br>
    4 What are the different states of a Hibernate object? - Transient – The object is not associated with any Hibernate session. - Persistent – The object is in a session and mapped to a database row. - Detached – The object was persistent but is now outside the session.
    5 What is the difference between get() and load() in Hibernate? - get() – Fetches data immediately; returns null if no record is found. - load() – Uses lazy loading; throws an exception if no record is found.
    6 What is caching in Hibernate? Caching improves performance by reducing database queries. - First-level cache – Enabled by default; stores data within a session. - Second-level cache – Shared across multiple sessions; requires explicit configuration.
    7 What is the difference between save() and persist() in Hibernate? - save() – Returns the generated identifier and inserts the record immediately. - persist() – Does not return an ID; insertion occurs only when the transaction commits.
    8 What is the difference between Session and SessionFactory? - SessionFactory – A heavyweight object that creates Session instances; spans the entire application. - Session – A lightweight object representing a unit of work; interacts with the database.
    9 What are Hibernate Annotations? Hibernate annotations allow entity mappings without XML. Example: java <br> @Entity <br> @Table(name = "employees") <br> public class Employee { <br> @Id <br> @GeneratedValue <br> private int id; <br> private String name; <br> } <br>
    10 How does Hibernate handle transactions? Hibernate transactions are managed using Transaction objects. Example: java <br> Transaction tx = session.beginTransaction(); <br> session.save(employee); <br> tx.commit(); <br>
    11 What is the difference between merge() and update() in Hibernate? - update() – Reattaches a detached object to the session and updates it. - merge() – Merges changes from a detached object into a persistent object copy.
    12 What is Lazy and Eager loading in Hibernate? - Lazy Loading – Data is not retrieved until needed. - Eager Loading – Related entities are retrieved immediately. Example: java <br> @OneToMany(fetch = FetchType.LAZY) // Lazy loading <br> @OneToMany(fetch = FetchType.EAGER) // Eager loading <br>
    13 What are the different inheritance strategies in Hibernate? Hibernate supports three inheritance mapping strategies: - Single Table Strategy – @Inheritance(strategy = InheritanceType.SINGLE_TABLE) - Joined Table Strategy – @Inheritance(strategy = InheritanceType.JOINED) - Table Per Class Strategy – @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
    14 What is the Criteria API in Hibernate? The Criteria API allows dynamic queries without writing HQL. Example: java <br> Criteria criteria = session.createCriteria(Employee.class); <br> criteria.add(Restrictions.eq("department", "IT")); <br> List<Employee> employees = criteria.list(); <br>
    15 What is the difference between openSession() and getCurrentSession()? - openSession() – Always creates a new session. - getCurrentSession() – Returns an existing session if available.

    Java 8 coding interview questions

     Java 8 coding questions:

    Problem Solution
    Separate Odd and Even Numbers listOfIntegers.stream().collect(Collectors.partitioningBy(number -> number % 2 == 0));
    Remove Duplicates from List listOfStrings.stream().distinct().toList();
    Character Frequency in String input.chars().mapToObj(c -> (char) c).collect(Collectors.groupingBy(ch -> ch, Collectors.counting()));
    Frequency of Array Elements list.stream().collect(Collectors.groupingBy(element -> element, Collectors.counting()));
    Sort List in Reverse list.sort(Comparator.reverseOrder()); list.forEach(System.out::println);
    Join Strings with Prefix/Suffix list.stream().collect(Collectors.joining("-", "Start-", "-End"));
    Filter Multiples of 5 list.stream().filter(number -> number % 5 == 0).forEach(System.out::println);
    Merge Arrays and Sort IntStream.concat(Arrays.stream(arr1), Arrays.stream(arr2)).sorted().toArray();
    Merge and Remove Duplicates IntStream.concat(Arrays.stream(arr1), Arrays.stream(arr2)).distinct().sorted().toArray();
    Find Top 3 Minimum Values list.stream().sorted().limit(3).toList();
    Find Top 3 Maximum Values list.stream().sorted(Comparator.reverseOrder()).limit(3).toList();
    Sort Strings by Length list.stream().sorted(Comparator.comparing(String::length)).forEach(System.out::println);
    Sum and Average of Array int sum = Arrays.stream(inputArray).sum(); double average = Arrays.stream(inputArray).average().orElse(0);
    Reverse Integer Array IntStream.range(0, arr.length).map(i -> arr[arr.length - 1 - i]).toArray();
    Check Palindrome boolean isPalindrome = IntStream.range(0, str.length() / 2).noneMatch(i -> str.charAt(i) != str.charAt(str.length() - i - 1));
    Find Second Largest Number list.stream().sorted(Comparator.reverseOrder()).skip(1).findFirst().orElseThrow();
    Common Elements Between Arrays list1.stream().filter(list2::contains).toList();
    Reverse Words in String Arrays.stream(str.split(" ")).map(word -> new StringBuilder(word).reverse().toString()).collect(Collectors.joining(" "));
    Find Strings Starting with Numbers list.stream().filter(s -> Character.isDigit(s.charAt(0))).toList();
    Sum of Digits in Number String.valueOf(input).chars().map(Character::getNumericValue).sum();
    Last Element of List list.get(list.size() - 1);
    Age from Birth Year Period.between(LocalDate.of(1985, 1, 23), LocalDate.now()).getYears();
    Fibonacci Series Stream.iterate(new int[]{0, 1}, fib -> new int[]{fib[1], fib[0] + fib[1]}).limit(10).map(fib -> fib[0]).toList();

    This table properly structures the Java 8 coding problems with their corresponding solutions. Let me know if you need any modifications! 

    Java 8 Coding Interview Questions and Answers

    This document contains a collection of Java 8 coding interview questions along with their answers. These questions focus on key Java 8 features such as Streams, Lambda Expressions, Functional Interfaces, and Method References.

    1. Filtering a List and Summing Even Numbers using Streams

    Question: Given a list of integers, write a Java 8 program to filter out even numbers and calculate their sum.

    Answer:

    import java.util.Arrays;
    import java.util.List;
    
    public class SumOfEvenNumbers {
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    
            int sum = numbers.stream()
                             .filter(n -> n % 2 == 0) // Filter even numbers
                             .mapToInt(Integer::intValue) // Convert to IntStream
                             .sum(); // Calculate sum
    
            System.out.println("Sum of even numbers: " + sum);
        }
    }
    

    Output:

    Sum of even numbers: 30
    

    2. Sorting a List of Strings in Ascending and Descending Order

    Question: Write a Java 8 program to sort a list of strings in both ascending and descending order.

    Answer:

    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class SortStrings {
        public static void main(String[] args) {
            List<String> names = Arrays.asList("John", "Alice", "Bob", "Charlie");
    
            // Ascending order
            List<String> ascendingOrder = names.stream()
                                               .sorted()
                                               .collect(Collectors.toList());
    
            // Descending order
            List<String> descendingOrder = names.stream()
                                                .sorted((s1, s2) -> s2.compareTo(s1))
                                                .collect(Collectors.toList());
    
            System.out.println("Ascending Order: " + ascendingOrder);
            System.out.println("Descending Order: " + descendingOrder);
        }
    }
    

    Output:

    Ascending Order: [Alice, Bob, Charlie, John]
    Descending Order: [John, Charlie, Bob, Alice]
    

    3. Finding the Maximum and Minimum Values in a List

    Question: Write a Java 8 program to find the maximum and minimum values in a list of integers.

    Answer:

    import java.util.Arrays;
    import java.util.List;
    import java.util.Optional;
    
    public class MaxMinValues {
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(10, 20, 5, 30, 15);
    
            Optional<Integer> max = numbers.stream().max(Integer::compareTo);
            Optional<Integer> min = numbers.stream().min(Integer::compareTo);
    
            System.out.println("Max Value: " + max.orElse(0));
            System.out.println("Min Value: " + min.orElse(0));
        }
    }
    

    Output:

    Max Value: 30
    Min Value: 5
    

    4. Grouping Objects by a Specific Property using Streams

    Question: Given a list of Employee

    objects, write a Java 8 program to group them by their department.

    Answer:

    import java.util.*;
    import java.util.stream.Collectors;
    
    class Employee {
        private String name;
        private String department;
    
        public Employee(String name, String department) {
            this.name = name;
            this.department = department;
        }
    
        public String getDepartment() {
            return department;
        }
    
        @Override
        public String toString() {
            return name;
        }
    }
    
    public class GroupByDepartment {
        public static void main(String[] args) {
            List<Employee> employees = Arrays.asList(
                new Employee("John", "HR"),
                new Employee("Alice", "IT"),
                new Employee("Bob", "HR"),
                new Employee("Charlie", "IT")
            );
    
            Map<String, List<Employee>> groupedByDepartment = employees.stream()
                .collect(Collectors.groupingBy(Employee::getDepartment));
    
            System.out.println("Employees grouped by department: " + groupedByDepartment);
        }
    }
    

    Output:

    Employees grouped by department: {HR=[John, Bob], IT=[Alice, Charlie]}
    

    5. Removing Duplicates from a List using Streams

    Question: Write a Java 8 program to remove duplicates from a list of integers.

    Answer:

    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class RemoveDuplicates {
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 5);
    
            List<Integer> uniqueNumbers = numbers.stream()
                                                 .distinct()
                                                 .collect(Collectors.toList());
    
            System.out.println("Unique Numbers: " + uniqueNumbers);
        }
    }
    

    Output:

    Unique Numbers: [1, 2, 3, 4, 5]
    

    6. Counting the Frequency of Characters in a String using Streams

    Question: Write a Java 8 program to count the frequency of each character in a string.

    Answer:

    import java.util.Map;
    import java.util.stream.Collectors;
    
    public class CharacterFrequency {
        public static void main(String[] args) {
            String input = "java8";
    
            Map<Character, Long> frequencyMap = input.chars()
                .mapToObj(c -> (char) c)
                .collect(Collectors.groupingBy(c -> c, Collectors.counting()));
    
            System.out.println("Character Frequency: " + frequencyMap);
        }
    }
    

    Output:

    Character Frequency: {a=2, v=1, j=1, 8=1}

    LoopCV Pro: Automate Your Job Search and Land Your Dream Job Faster

    LoopCV Pro: How To Automate Your Job Search And Get Hired Faster

    Moving Through The Job Market With ency Using LoopCV Pro

    Navigating through a challenging job market to find the right placement for you can be tricky and tedious. For job seekers, it’s an extremely high volume of applications, events that require personalized outreach, and constant tracking of their status.



    Thank LoopCV Pro, a revolutionary platform that automates the job process, freeing up the candidate to focus on the things that really count: interviewing and landing that coveted job opportunity.

    LoopCV Pro: A Brief Background

    LoopCV Pro is an advanced automatic job search technology that makes searching for a job simple, effective, and easier through optimized algorithms. It enables users to map applications, speak with recruiters, and get jobs by streamlining almost every part of the job search.

    LoopCV Pro – Some of the Key Features

    1. Job Application Automation

    • LoopCV Pro collects new jobs every day for the titles and locations you specified.
    • Appli Genius can apply for you automatically or equip you with a list of matching jobs that you can review and apply to in 1 click.

    2. Recruiter Outreach

    • The system finds recruiter emails and sends personalized messages with templates for customization.
    • This feature promotes visibility as candidates can communicate with the employers directly.

    3. Performance Analytics

    • Provides complete statistics: This includes your email’s open and response rates, your CV’s performance and more.
    • User can do A/B testing with new CVs, with new keywords and find your optimal strategy for the jobsearch.

    4.Advanced Job Filtering

    • Advanced Filtering using keyword, remove company option, other filters to ensure that you apply for relevant roles.

    5. AI-Powered CV Improvement

    • The platform analyses your CV and gives you feedback on what to do to improve it and catch the attention of an employer.

    Advantages and Disadvantages of LoopCV Pro

    Advantages:

    •  Efficiency – Enables you to automate the tedious tasks of applying for jobs, thus saving a lot of time and energy.
    • Personalization – Email templates and applications that can be tailored to demand have a greater chance of making a positive impression on recruiters.
    • Performance Metrics – Get data-driven insights and performance metrics to improve your job searching experience.
    Cons:
    • Learning Curve – Users may require time to familiarize with and adopt all features to their full potential.
    • Subscription-based – Loop CV Pro comes with a free plan, but the premium subscription unlocks access to advanced features too, along with higher application limits. How to Use LoopCV Pro Sign Up: Create an account on the LoopCV Pro website.
    • Profile Configuration: Upload your resume, and preferences like job titles, location, etc.
    • Set Applications: Let it apply automatically, or do it manually.
    • Custom Outreach: Choose or build your own templated outreach emails to send to recruiters.
    • Track Your Progress: A dashboard can help track the status of applications, engagement with your emails and progress on your job search.

    LoopCV Pro vs Other Job Search Tools

    1. There are multiple tools that help with job search process but LoopCV Pro stands alone with 100% automation. Unlike any job board or application tracker, LoopCV Pro finds you relevant positions, applies on your behalf and connects you with recruiters.
    2. a holistic solution that incorporates performance analytics and AI-powered CV optimization, making it stand out from the crowd.

    Who Should Use LoopCV Pro?

    1. ✅ New Grad — Makes the transition from college to the workforce easier.
    2. ✅ Career Changers – Assists professionals in quickly researching new industries or roles.
    3. ✅ Busy Professionals – Straddled job searching alongside a currently held position, providing a framework for securing the next role. Thanks to LoopCV Pro, job seekers can feel empowered to tackle the job hunt with ease. Learn more and start your job hunting today at the LoopCV Pro website!
    4. Let me know in case you need more tweaks!

    The Ultimate Job Search Tool for Resumes, Interviews & LinkedIn Optimization : CareerFlow AI

     Finding a job these days is not an easy task as we all know. As we enter a world of highly skilled and talented employees, the need for tools that can help improve your chances becomes extremely important! Enter Careerflow AI – a game-changing platform, purpose-built to offer job seekers AI-powered tools and end-to-end support.




    Careerflow AI Overview

    1. AI Resume Builder

    Writing a professional CV is important. With its AI Resume Builder, Careerflow helps users quickly build a professional ATS-friendly resume. It allows you to export beautiful resume layouts, add AI-generated bullet points, summary sections, and conversion ratio optimization suggestions.
    Visit AI Resume Builder

    2. LinkedIn Assessment Tool

    A great deal of recruiters first meet you through your LinkedIn profile. That is why Careerflow's LinkedIn Review Tool scans your profile and provides recommendations to help you get noticed and, more importantly, to be seen by employers.
    Try LinkedIn Review

    3. AI Mock Interview

    Mock interviews can be one of the more intimidating facets of preparing for interviews. Careerflow includes an AI Mock Interview tool that can replicate interviews and provide useful feedback that you can act on.
    Check AI Mock Interview

    4. Job Tracker

    It can be overwhelming to keep track of multiple job applications. The Job Tracker feature helps you keep track of your applications in one place.
    Explore Job Tracker


    Pros and Cons of All-in-One Career Strategy Platforms

    Pros:

    • Integrated Resources: Offers tools for resume building, interview prep, personal branding, and more from a single solution.
    • Custom AI Profiles: AI suggests job-search tools based on user profiles, maximizing the chance of a fitting tool match.
    • Supportive Community: Get advice, share experiences, and learn from others in your field.

    Cons:

    • Potential Learning Curve: While the platform is user-friendly, newcomers to tech may require some time to familiarize themselves with all the resources.
    • Subscription-Based Model: Some platforms may require a subscription fee, which could be a disadvantage for those on a tight budget.
    • Overwhelming Options: A variety of tools might overwhelm job seekers if they are unclear about what they actually need.

    How to Use Careerflow AI

    1. Sign Up: Start a free account on the Careerflow site.
    2. Acquaint Yourself with Features: Walk around the dashboard to find utilities such as the AI Resume Builder, LinkedIn Review, and Job Tracker.
    3. Upload or Create Resume: Create a new resume using the AI Resume Builder or upload your current resume for analysis and improvement.
    4. Optimize LinkedIn Profile: Utilize the LinkedIn Review Tool to gain actionable insights on enhancing your profile.
    5. Interview Prep: Use the AI Mock Interview tool to practice and improve your interviewing skills.
    6. Track Applications (Job Tracker): Keep track of your job applications using the Job Tracker and stay organized during your job search process.

    How It Compares to Other Tools

    Many platforms are available for job seekers, but Careerflow stands out as a complete, AI-powered solution. Careerflow is not just a resume builder or job tracker—it integrates multiple tools into one powerful job search assistant.

    Looking for career success? Start with Careerflow AI today!

    The Ultimate Guide to Pi.AI: How It Works & Why You Should Try It

     Exploring Pi.AI and the Future of Conversational AI



    No need to install app. you can use web url directly .. try once and let us know in comments

    https://pi.ai/

    Introduction to Pi.AI

    Conversational AI is changing the way we interact with technology, allowing people to communicate using the same terminology they would in face-to-face interactions. One of the most interesting players in this space is Pi.AI—an AI bot capable of engaging in authentic, in-depth conversation. Pi.AI could be your personal AI assistant, your brainstorming partner, or your most entertaining conversationalist. AI aims to redefine human-AI relationships. But what exactly is Pi.AI, and what makes it unique? Let’s explore.

    Key Features of Pi.AI

    1. Custom and Empathetic Conversations

    Pi.AI is good at having informative conversations in context. While conversational AI has, until now, mainly hinged around traditional chatbots that offer mechanical or transactional answers, Pi.AI can share emotional sentiments, ask for clarification, and tailor its responses according to your mood and tone.

    2. Context Retention and Memory

    The contentious matter with most chatbots is retaining context, which can break the flow of conversation. Pi.AI, on the other hand, retains critical points of conversation, moving seamlessly. It helps brainstorm with (remote!) team members or simply talk about plans over time.

    3. Adaptive Learning and Personalization

    Pi.AI makes the most of user interactions and therefore can customize the content based on user needs. This personalized feature adds a layer of interaction to conversations as the AI adjusts to your interests and way of communicating.

    4. Advanced Natural Language Processing (NLP)

    Driven by state-of-the-art NLP models, Pi.AI handles complex queries, replies in grammatical sentences, and notices subtleties of tone and intent. This makes conversations fluid and natural instead of robotic and scripted.

    5. Multi-Platform Accessibility

    Since Pi.AI is mainly text-based, it can be adapted for countless applications with the availability of voice-based integration. Users can interact with Pi.AI in web and mobile applications.



    Pros & Cons of Pi.AI

    Pros:

    • Engaging, human-like conversations
    • Great context retention and memory for better interactions
    • Personalized responses tailored to user preferences
    • Empathetic and emotionally intelligent communication
    • Available on multiple platforms

    Cons:

    • Limited task execution compared to assistants like Alexa or Google Assistant
    • Still developing—some answers may lack profound expertise
    • Not great for strictly transactional queries

    How to Use Pi.AI

    1. Visit Pi.AI – Pi.AI is available both on the web or as a mobile app.
    2. Continue the conversation – Send a text to Pi.AI, and it will provide context-appropriate responses.
    3. Experience personalized interaction – Over time, Pi.AI learns from your chats, tailoring conversations to a more relevant outcome based on your preferences.
    4. Use it for brainstorming or emotional support – Whether you need creative input or an empathetic listener, Pi.AI is designed for purposeful dialogue.
    5. Explore different subjects – Pi.AI can discuss a wide range of topics, from philosophy and technology to self-improvement.

    Comparison with Similar AI Tools

    Feature Pi.AI ChatGPT Google Assistant Alexa
    Conversational Depth High – Empathic and context-aware High – Informative and task-based Medium – Task-oriented Medium – Command-driven
    Context Retention High High Limited Limited
    Personalization Adaptive Learning Adaptive Learning Limited Limited
    Task Execution Low Medium High High
    Emotional Intelligence High Medium Low Low

    Final Thoughts & Use Cases

    Pi.AI is a monumental step toward humanizing AI, making it more relatable, personal, and engaging. Unlike most AI assistants that excel at task execution, Pi.AI focuses on warmth, emotional intelligence, and meaningful conversations.

    Use Cases:

    • Personal companion – Empathetic conversationalist for mental well-being
    • Brainstorming tool – Idea-generation aid for creatives and professionals
    • Learning assistant – Engages in interactive exchanges on subjects of interest
    • Motivational coach – Encourages self-improvement

    Pi.AI can be a purely digital companion for those who want thoughtful conversation, creative brainstorming, or simply an interesting chat experience. If you haven’t tried Pi.AI yet, go ahead! AI is evolving, and Pi.AI is at the forefront of changing how we interact with AI-powered systems.



    Select Menu