Sunday, 24 December 2023

Best Interviews Questions for Java

How many ways create threads in java 8

In Java 8, you can create threads in several ways. The most common approaches are:

1. Extending the Thread Class

You can create a thread by extending the Thread class and overriding its run() method.

class MyThread extends Thread {

    public void run() {

        System.out.println("Thread running...");

    }

}

public class Main {

    public static void main(String[] args) {

        MyThread thread = new MyThread();

        thread.start(); // Start the thread

    }

}

2. Implementing the Runnable Interface

Implementing Runnable allows more flexibility since the class can still extend another class.

class MyRunnable implements Runnable {

    public void run() {

        System.out.println("Thread running...");

    }

}

public class Main {

    public static void main(String[] args) {

        Thread thread = new Thread(new MyRunnable());

        thread.start();

    }

}

3. Using Lambda Expressions (Java 8 Feature)

Java 8 introduced lambda expressions, simplifying the Runnable implementation.

public class Main {

    public static void main(String[] args) {

        Thread thread = new Thread(() -> System.out.println("Thread running..."));

        thread.start();

    }

}

4. Using the ExecutorService (Thread Pool)

Java provides the ExecutorService framework to manage thread pools efficiently.

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

public class Main {

    public static void main(String[] args) {

        ExecutorService executor = Executors.newFixedThreadPool(2);

        executor.submit(() -> System.out.println("Thread running..."));

        executor.shutdown(); // Shutdown the executor

    }

}

5. Using the Callable and Future Interface

If you need a return value from a thread, use Callable instead of Runnable.

import java.util.concurrent.*;

public class Main {

    public static void main(String[] args) {

        ExecutorService executor = Executors.newSingleThreadExecutor();

        Callable<String> task = () -> {

            Thread.sleep(2000); // Simulating a delay

            return "Task completed!";

        };

        Future<String> future = executor.submit(task);

        try {

            System.out.println("Waiting for the result...");

            String result = future.get(); // Blocks until the result is available

            System.out.println("Result: " + result);

        } catch (InterruptedException | ExecutionException e) {

            e.printStackTrace();

        } finally {

            executor.shutdown(); // Properly shut down the executor

        }

    }

}

6. Using CompletableFuture (Java 8 Feature)

Java 8 introduced CompletableFuture for async programming.

import java.util.concurrent.CompletableFuture;

public class Main {

    public static void main(String[] args) {

        CompletableFuture.runAsync(() -> System.out.println("Thread running..."));

    }

}

Each approach has its own use case, depending on whether you need a simple thread, a return value, or a managed thread pool.

What is Multi threading, where to use in your project


What is Multithreading?

Multithreading is the ability of a CPU to execute multiple threads concurrently within a single process. A thread is a lightweight, independent unit of execution that shares resources like memory and CPU with other threads. In Java, multithreading is implemented using the Thread class or the Runnable/Callable interfaces.


Why Use Multithreading?

Multithreading improves the performance and responsiveness of applications by:

  1. Enhancing CPU Utilization – Utilizing idle CPU cores efficiently.
  2. Enabling Parallel Execution – Running multiple tasks at the same time.
  3. Reducing Response Time – Making applications more responsive.
  4. Handling Multiple Requests – Useful in server-side applications.
  5. Improving Throughput – Allows processing multiple operations concurrently.

Where to Use Multithreading in Your Spring Boot Project?

Multithreading is beneficial in various scenarios of a Spring Boot application:

1. Asynchronous Task Execution

Use @Async to run tasks in a separate thread.


import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class MyService { @Async public void performTask() { System.out.println("Executing in thread: " + Thread.currentThread().getName()); } }

Use Case: Long-running operations like sending emails, file processing, or background jobs.


2. Parallel Processing in REST APIs

Use CompletableFuture to return responses without blocking.


import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import java.util.concurrent.CompletableFuture; @Service public class MyService { @Async public CompletableFuture<String> getData() { return CompletableFuture.supplyAsync(() -> "Processing Data..."); } }

Use Case: Fetching data from multiple sources (e.g., APIs, databases) in parallel.


3. Handling Multiple User Requests (Thread Pooling)

Spring Boot uses ExecutorService for thread pooling.


import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.concurrent.Executor; import java.util.concurrent.Executors; @Configuration public class ThreadPoolConfig { @Bean public Executor taskExecutor() { return Executors.newFixedThreadPool(5); // 5 concurrent threads } }

Use Case: Optimizing performance for high-traffic APIs.


4. Multi-threaded Batch Processing (Spring Batch)

Spring Batch executes tasks in chunks using multiple threads.


import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; import org.springframework.context.annotation.Configuration; @Configuration @EnableBatchProcessing public class BatchConfig { }

Use Case: Large dataset processing, scheduled jobs, and ETL (Extract, Transform, Load) tasks.


5. Concurrent Database Operations

Using @Transactional with multithreading ensures data consistency.


import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class MyService { @Transactional public void updateDatabase() { // Perform database operations safely in a multithreaded environment } }

Use Case: Parallel processing of bulk database updates.


Conclusion

Multithreading is essential for optimizing performance and scalability in Java applications. In Spring Boot projects, it is widely used for handling multiple requests, executing background tasks, and improving database efficiency.


1)How many ways  are there to create an object?

      There are several ways to create an object in java. These are
      1) Using the 'new' Keyword:
           MyClass obj = new MyClass();
This is the most common way to create objects in Java. It involves using the 'new' keyword followed by a constructor to instantiate an object.      

     2) Using Factory Method:
e.g.1:
public class MyClassFactory { public static MyClass createObject() { return new MyClass(); } } // Usage MyClass obj = MyClassFactory.createObject();

Factory methods are static methods that create and return objects. They provide a way to encapsulate object creation logic.

             By using class name if we call any method and return same class object. Then that method is considered as factory method.
            While developing projects one application contains so many subclasses then we go for factory method.
e.g.2:  Thread t=Thread.currentThread();

     3) Using Reflection API:
e.g.1:
             Class c=Class.forName(“MyClass”);
             Object obj=c.newInstance();           //creates Test class Object.
             MyClass t=(MyClass)obj;

e.g.2:
try { MyClass obj = (MyClass) Class.forName("MyClass").newInstance(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { e.printStackTrace(); }
Reflection allows you to inspect classes, interfaces, fields, and methods at runtime. Here, the Class.forName() method is used to dynamically load and create an instance of a class.

    4) Using Object Deserialization:
          e.g.1: 
          FileInputStream fis=new FileInputStream("Test.txt");
          ObjectInputStream ois=new ObjectInputStream(fis);
          MyClass   mc=new MyClass (" ");
          ois.readObject(mc);
          ois.close();

         e.g.2:
         try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("object.ser"))) {
         MyClass obj = (MyClass) in.readObject();
         } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

         Deserialization is the process of reconstructing objects from their serialized form. You can create an object by reading it from a file or another stream.

5) Using Dependency Injection (DI) Frameworks:
@Autowired private MyClass obj;
In this example, the object obj is created and injected by the DI framework.

 6) Using clone method:
   e.g.1:
           MyClass t1=new MyClass(10,20);
           MyClass t2=t1.clone();
clone() method is part of the Cloneable interface and is used to create a copy of an object. The clone() method is declared in the Object class, and for it to work properly, the class of the object being cloned must implement the Cloneable interface.
e.g2:
class MyClass implements Cloneable { private int value; public MyClass(int value) { this.value = value; } public int getValue() { return value; } // Override the clone method @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } } public class Main { public static void main(String[] args) { MyClass original = new MyClass(42); try { // Using clone to create a copy MyClass copy = (MyClass) original.clone(); System.out.println("Original value: " + original.getValue()); System.out.println("Copy value: " + copy.getValue()); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } }

The Cloneable interface is a marker interface, and it doesn't have any methods. Its presence indicates that the class supports cloning.

  1. The clone() method in the Object class is declared to throw CloneNotSupportedException, so when you override it in your class, you need to handle this exception.

2) What are the differences b/w HashMap and HashSet?

      Both HashMap and HashSet are part of Java’s Collection Framework and use a hashing mechanism, but they serve different purposes. Here's a detailed comparison:

 1.Key Differences

FeatureHashMapHashSet
DefinitionHashMap stores the data in key-value pairs.Where as HashSet stores only objects or a collection of unique elements.
ImplementsHashMap is an implementation Map<K, V> interface.Where as HashSet is an implementation of Set<E> interface.
Duplicates Allowed?✅ Keys must be unique but values can be duplicated.❌ Only unique elements are allowed. //Duplicates are there then Ignored
Null Values✅ One null key allowed, multiple null values allowed.✅ Allows a single null value.
Internal ImplementationUses a hash table to store entries as (Key, Value) pairs.Uses a HashMap internally (stores elements as keys with a dummy value).
Performance (O(1))Fast lookup via hashing, average O(1) time complexity for put(), get().Similar hashing mechanism, average O(1) time complexity for add(), contains().
Ordering❌ No guaranteed order (Use LinkedHashMap for insertion order).❌ No guaranteed order (Use LinkedHashSet for insertion order).
Usage ScenarioWhen key-value mapping is needed.When only unique values are required.

2.How They Work Internally

👉 HashMap Internal Working

  • Stores elements as (Key, Value) pairs.
  • Uses hashing to determine the bucket index for a key.
  • If multiple keys map to the same bucket (hash collision), it uses LinkedList (before Java 8) or Balanced Tree (Red-Black Tree) (Java 8+) for efficient retrieval.
  • Example:

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

    map.put(1, "Apple");

    map.put(2, "Banana");

    map.put(3, "Cherry");

    System.out.println(map.get(2)); // Output: Banana


    👉 HashSet Internal Working
  • Internally backed by a HashMap, where elements are stored as keys, and the values are a constant dummy object (PRESENT).
  • Ensures unique elements using the hashCode() and equals() method.

  • Example:

    HashSet<String> set = new HashSet<>();
    set.add("Apple"); set.add("Banana"); set.add("Cherry"); set.add("Apple"); // Duplicate ignored System.out.println(set); // Output: [Apple, Banana, Cherry] (Unordered)

    Internally, the above code works like:

    private static final Object PRESENT = new Object(); HashMap<String, Object> map = new HashMap<>(); map.put("Apple", PRESENT); map.put("Banana", PRESENT); map.put("Cherry", PRESENT);

    3.When to Use What?

    Use CaseUse HashMapUse HashSet
    Need a key-value pair?✅ Yes❌ No
    Need unique elements?❌ No✅ Yes
    Need fast lookups?✅ Yes✅ Yes
    Need duplicate values?✅ Yes (values can be duplicated)❌ No
      

    Example:

    import java.util.HashMap;

    import java.util.HashSet;


    public class HashMapSetEx {

    public static void main(String[] args) {

    // HashMap Example

    HashMap<Integer, String> hashMap = new HashMap<>();

    hashMap.put(1, "Apple");

    hashMap.put(null, "Banana"); //One null key allowed

    hashMap.put(3, null); // allows multiple null values


    System.out.println("HashMap: " + hashMap);


    // HashSet Example

    HashSet<String> hashSet = new HashSet<>();

    hashSet.add("Apple");

    hashSet.add("Banana");

    hashSet.add(null); // allows single null value

    hashSet.add("Apple"); // Ignored


    System.out.println("HashSet: " + hashSet);

    }

    }

     
    Some of the important points about HashSet in java are

    HashSet doesn’t guarantee the insertion order of elements.
    HashSet is not thread-safe. You can get thread-safe HashSet using Collections.synchronized Set method at the cost of performance.
    You can also use CopyOnWriteArraySet concurrency class for thread safety.
    HashSet iterator methods are fail-fast. So any structural modification to the set after creation of iterator will throw ConcurrentModificationException.
    HashSet supports Generics, this is the recommended approach to avoid ClassCastException at runtime.
    HashSet uses HashMap for storing elements, so the objects should provide good implementation
     of hashCode() and equals() method to avoid unwanted results.

    3) What is the difference b/w wait(-), sleep(-)?
      
          Both wait() and sleep() are used for pausing the execution of a thread in Java, but they have different purposes and behaviors

                  Wait(-)
                              Sleep(-)
        1)wait() is the method of Object class and is used for synchronization and inter-thread communication and releasing the lock and waiting for notification from another thread.
       
     
       2)wait() method must be called from synchronized context (i.e. synchronized method or block), otherwise it will throw IllegalMonitorStateException
    synchronized (lockObject) {
        while (!conditionIsMet()) {
            try {
                lockObject.wait();  // Thread waits until notified
            } catch (InterruptedException e) {
                e.printStackTrace();         
            }
        }
    }
       3)wait() method releases the lock.
        
    4)wait() is the non-static method -
        public final void wait() throws InterruptedException { //...}
        5)wait() should be notified by notify() or notifyAll() methods.
        6)wait() method needs to be called from a loop in order to deal with false alarm.
        1)Where as sleep() is a  static method of the Thread class and is used for introducing a delay or pause in the execution of the current thread. It does not release the lock and is not related to inter-thread communication.
        2)Where as sleep() can be called from any context, not necessarily within a synchronized context
    try {
        Thread.sleep(5000);  // Sleep for 5 sec
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

       
     



    3)Where as sleep() method doesn't release the lock.
        4)Where as sleep() is the static method - 
        public static void sleep(long millis, int nanos) throws InterruptedException { //... }
        5)Where as sleep(), after the specified amount of time, sleep() is completed.
        6)sleep() better not to call from loop


    Code Example for wait()

    Scenario: A thread waits for a signal from another thread.

    class WaitExample {

        public static void main(String[] args) {

            final Object lock = new Object();

            Thread t1 = new Thread(() -> {

                synchronized (lock) {

                    try {

                        System.out.println("Thread 1: Waiting...");

                        lock.wait();  // Releases the lock and waits

                        System.out.println("Thread 1: Resumed!");

                    } catch (InterruptedException e) {

                        e.printStackTrace();

                    }

                }

            });

            Thread t2 = new Thread(() -> {

                synchronized (lock) {

                    System.out.println("Thread 2: Notifying...");

                    lock.notify();  // Wakes up thread 1

                }

            });

            t1.start();

            try { Thread.sleep(1000); } 

            catch (InterruptedException e) {} // Ensuring t1 starts first

            t2.start();

        }

    }

    Output:

    Thread 1: Waiting...

    Thread 2: Notifying...

    Thread 1: Resumed!

    Code Example for sleep()

    Scenario: A thread sleeps for a specific time.

    class SleepExample {

        public static void main(String[] args) {

            Thread t1 = new Thread(() -> {

                try {

                    System.out.println("Thread sleeping...");

                    Thread.sleep(3000);  // Sleeps for 3 seconds

                    System.out.println("Thread woke up!");

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

            });

            t1.start();

        }

    }

    When to Use What?

    Use CaseUse wait()Use sleep()
    Inter-thread communication (waiting for signals)✅ Yes❌ No
    Pausing execution for a fixed time❌ No✅ Yes
    Thread releases lock while waiting✅ Yes❌ No
    Can be called inside synchronized block✅ Yes✅ Yes (but not required)


    4)  Can we create a user defined immutable class? What is immutable class? How can we create immutable custom class? Why you want to create immutable custom class?
      Yes, we can create a user-defined immutable class in Java. 
      
    What is an Immutable Class?

    An immutable class is a class whose state cannot be changed after it is created. This ensures thread safety, consistency, and reliability.

    🔹 Guidelines to Create an Immutable Class in Java

    To create an immutable class, follow these rules:

    Declare the class as final
    → Prevents subclasses from modifying behavior.

    Declare all fields as private final
    → Prevents direct modification after initialization.

    Do not provide setter methods
    → Ensures that fields cannot be modified.

    Initialize fields only through the constructor
    → Provides controlled initialization.

    Ensure defensive copying of mutable objects
    → Prevents external modification of internal mutable objects.

    Example:
    public final class Immutable {
        private final int value;
        public Immutable(int value) {
            this.value = value;
        }
        // Factory method to return an instance
        public Immutable instance(int value) {
            if (this.value == value) {
                return this; // Return the same instance if the value is unchanged
            } else {
                return new Immutable(value); // Create a new instance if the value is different
            }
        }
        // Getter method to access value (without modifying it)
        public int getValue() {
            return value;
        }

        public static void main(String[] args) {
            Immutable im1 = new Immutable(10);
            Immutable im2 = im1.instance(10);
            Immutable im3 = im1.instance(100);

            System.out.println(im1); // Immutable@de6ced
            System.out.println(im2); // Immutable@de6ced
            System.out.println(im3); // Immutable@c17164

            System.out.println(im1 == im2); // true (same instance reused)
            System.out.println(im1 == im3); // false (new instance created)
        }
    }

    Why Create Immutable Classes?

    BenefitDescription
    Thread SafetyImmutable objects are inherently thread-safe because they cannot be modified after creation. No synchronization needed.
    Caching & PerformanceSince immutable objects do not change, they can be cached and reused efficiently.
    Safe HashingImmutable objects have a constant hash code, making them perfect for keys in HashMaps.
    PredictabilityNo risk of unexpected changes, making the code easier to understand and debug.
    Prevention of InconsistenciesEnsures that the state of an object is consistent and cannot be changed by external factors.

    Real-world Examples of Immutable Classes
    1.String Class
  • Every modification (e.g., s.toUpperCase()) creates a new String object.
  • Prevents unexpected mutations.
  • 2.Wrapper Classes (Integer, Double, Boolean)
    These classes are immutable to avoid modifications in shared memory.
    3.java.time.LocalDate, LocalTime, LocalDateTime (Java 8+)
    Designed to be immutable for safe date/time manipulation.

    5)  What are the differences b/w String and StringBuffer and StringBuilder?                   

    String, StringBuffer, and StringBuilder are three classes used to represent and manipulate strings. Each of these classes has its own characteristics, and the main differences lie in their mutability, performance, and thread safety.

    String Immutable, thread-safe, but slow for modifications.
    StringBuffer → Mutable, thread-safe (synchronized), slightly slower.
    StringBuilder → Mutable, not thread-safe, but fastest.

    Differences Between String, StringBuffer, and StringBuilder

    FeatureString (Immutable& Thread-Safe)StringBuffer (Mutable & Thread-Safe)StringBuilder (Mutable & Non-Thread-Safe)
    Mutability❌ Immutable (New object is created for modifications)✅ Mutable (Modifies existing object)✅ Mutable (Modifies existing object)
    Thread-Safety✅ Thread-Safe (due to immutability)✅ Thread-Safe (synchronized methods)❌ Not Thread-Safe
    Performance🚫 Slow for frequent modifications (new objects are created)🟡 Slower due to synchronization overhead🟢 Fastest (No synchronization overhead)
    ConcatenationUses + operator or concat() (creates a new object)Uses append(), modifies the same objectUses append(), modifies the same object
    Usage in Multi-threading✅ Safe (immutable)✅ Safe (synchronized)❌ Not Safe (should be used in a single-threaded environment)
    Memory Efficiency❌ Inefficient for frequent changes🟡 Better (but synchronization adds some overhead)🟢 Best (efficient for single-threaded performance)
    Best Used ForSmall, unchanging text (e.g., configuration values, keys)Multi-threaded applications needing string modificationsPerformance-critical applications requiring frequent modifications

    String Example (Immutable)

    public class StringExample {
        public static void main(String[] args) {
            String str = "Hello";  
            str = str + " World";  // Creates a new string (old one is discarded)
            System.out.println(str);  // Output: Hello World
        }
    }
    Why is String immutable?
    Every time we modify a String, a new object is created in memory instead of modifying the existing one.

    StringBuffer Example (Thread-Safe)

    public class StringBufferExample {
        public static void main(String[] args) {
            StringBuffer sb = new StringBuffer("Hello");
            sb.append(" World");  // Modifies the same object
            System.out.println(sb);  // Output: Hello World
        }
    }

    Why use StringBuffer?

    Safe for multi-threading because its methods (e.g., append(), insert()) are synchronized.

    StringBuilder Example (Fastest, Non-Thread-Safe)

    public class StringBuilderExample {
        public static void main(String[] args) {
            StringBuilder sb = new StringBuilder("Hello");
            sb.append(" World");  // Modifies the same object
            System.out.println(sb);  // Output: Hello World
        }
    }

    Why use StringBuilder?

    Faster than StringBuffer in a single-threaded environment because no synchronization is required.

    When to Use What?

    Use CaseRecommended Choice
    Fixed Strings (unchanging values)String (Immutable, thread-safe)
    Multi-threaded applicationsStringBuffer (Thread-safe)
    High-performance, single-threaded operationsStringBuilder (Fastest)



    6)  What is Collection Framework and which “Collections F/W”  classes did you use in your project?


       A Collection is a group of individual objects represented as a single unit. Java provides the Collection Framework (JCF), a set of interfaces and classes to store and manipulate data efficiently.
    The Collection interface (java.util.Collection) and Map interface (java.util.Map) are the
     two main “root” interfaces of Java collection classes.

    Collection : Root interface with basic methods like size(), add(), remove(),
                 contains(), isEmpty(), addAll(), ... etc.

    Collection Framework Overview

    1️⃣ Core Interfaces in Java Collections

    InterfaceDescriptionKey Implementations
    CollectionRoot interface (methods like add(), remove(), size(), etc.)List, Set, Queue
    ListOrdered collection, allows duplicatesArrayList, LinkedList, Vector
    SetUnordered collection, no duplicatesHashSet, TreeSet
    QueueFIFO (except PriorityQueue)PriorityQueue, ArrayDeque
    DequeInsert/remove from both endsArrayDeque, LinkedList
    MapKey-Value pairsHashMap, TreeMap, Hashtable

    🔹 When to Use List, Set, Queue, or Map?

    Collection TypeUse CaseWhen to Use?
    ListOrdered collection, allows duplicatesWhen order matters (e.g., log entries, user transactions)
    SetUnordered, unique elementsWhen duplicates must be avoided (e.g., unique user roles, tags)
    QueueFIFO orderWhen elements must be processed in sequence (e.g., task scheduling, messaging queues)
    MapKey-Value pairsWhen you need fast lookup and mapping (e.g., userId → User object)

    🔹 List, Set, Queue, and Map – Practical Use Cases

    1️⃣ List (Ordered, Allows Duplicates)

    Best For: Ordered data, when duplicates are allowed.
    Common Use Cases: Storing ordered user data, processing query results.

    Example: Fetching users from a database

    List<User> users = new ArrayList<>();
    while (resultSet.next()) {
        users.add(new User(resultSet.getInt("id"), resultSet.getString("name")));
    }

    2️⃣.Set (Unique, Unordered)

    Best For: When duplicates must be avoided.
    Common Use Cases: Storing unique roles, unique IDs, cache keys.

    Example: Ensuring unique user roles

    Set<String> roles = new HashSet<>();
    roles.add("ADMIN");
    roles.add("USER");
    roles.add("ADMIN"); // Duplicate ignored
    System.out.println(roles); // Output: [ADMIN, USER]

    3️⃣.Queue (FIFO - First In, First Out)

    Best For: Task scheduling, messaging queues
    Common Use Cases: Processing tasks in sequence, background jobs.

    Example: Processing tasks in order

    Queue<String> taskQueue = new LinkedList<>();

    taskQueue.offer("Task1");

    taskQueue.offer("Task2");

    System.out.println(taskQueue.poll()); // Output: Task1

    4️⃣.Map (Key-Value Pairs)

    Best For: Fast lookup using a key
    Common Use Cases: Storing configurations, caching, user session tracking.

    Example: Caching API responses

    Map<String, String> cache = new HashMap<>();
    cache.put("user_1", "Swamy");
    System.out.println(cache.get("user_1")); // Output: Swamy

    Collections API Algorithms (Sorting, Searching, Shuffling)

    1️⃣ Sorting

    Sorts a List in ascending order.


    List<Integer> numbers = Arrays.asList(5, 2, 9, 1); Collections.sort(numbers); System.out.println(numbers); // Output: [1, 2, 5, 9]

    When to Use?

    • When you need ordered data (e.g., displaying leaderboard scores).

    2️⃣ Searching (Binary Search)

    Efficiently searches in a sorted list.


    int index = Collections.binarySearch(numbers, 5); System.out.println("Found at index: " + index);

    When to Use?

    • When you need fast lookups in sorted data.

    3️⃣ Shuffling

    Randomizes the order of elements.


    Collections.shuffle(numbers); System.out.println(numbers); // Output: Randomized order

    When to Use?

    • Useful in game development, test case randomization.

    🔹 Collection Classes Used in My Spring Boot Project

    Collection TypeUsage in Project
    ArrayListStoring and transferring database query results (e.g., ResultSet to DTO)
    LinkedListProcessing queue-based tasks (job queues)
    HashSetStoring unique user roles, preventing duplicates
    TreeSetSorting unique elements (audit logs, reports)
    HashMapCaching configurations, storing API response data
    TreeMapMaintaining sorted logs and audit trail
    ConcurrentHashMapHandling thread-safe caching in microservices
    PropertiesReading database/mail configurations

    🔹 Practical Real-World Applications in Spring Boot

    1️⃣ Using List for Database Handling


    List<User> users = new ArrayList<>(); while (resultSet.next()) { users.add(new User(resultSet.getInt("id"), resultSet.getString("name"))); }

    Why List?

    Maintains insertion order.
    Allows duplicates (multiple users with the same name).

    2️⃣ Using Set for Unique Data (User Roles)


    Set<String> roles = new HashSet<>(); roles.add("ADMIN"); roles.add("USER"); roles.add("ADMIN"); // Duplicate ignored

    Why Set?

    Ensures uniqueness.
    Faster lookup than List.

    3️⃣ Using Queue for Task Scheduling


    Queue<String> taskQueue = new LinkedList<>(); taskQueue.offer("Task1"); taskQueue.offer("Task2"); System.out.println(taskQueue.poll()); // Output: Task1

    Why Queue?

    Tasks are processed in order (FIFO).

    4️⃣ Using Map for Fast Lookups (User Cache)


    Map<String, String> cache = new HashMap<>(); cache.put("user_1", "Swamy"); System.out.println(cache.get("user_1")); // Output: Swamy

    Why Map?

    Fast retrieval using keys.

    5️⃣ Using ConcurrentHashMap for Thread-Safe Caching


    Map<String, String> concurrentMap = new ConcurrentHashMap<>(); concurrentMap.put("key1", "value1");

    Why ConcurrentHashMap?

    Safe for multi-threaded environments.

    🔹 Summary

    Collection TypeKey FeaturesBest Use Case
    ListOrdered, allows duplicatesOrdered data, logs, transactions
    SetUnordered, unique elementsUnique values (tags, user roles)
    QueueFIFO orderTask scheduling, messaging queues
    MapKey-Value storageConfigurations, caching, session tracking
    Thread-Safe CollectionsSafe for multi-threadingReal-time processing, caching in microservices

    🚀 Final Thoughts

    Use List when order matters and duplicates are allowed.
    Use Set when duplicates must be avoided.
    Use Queue for FIFO processing.
    Use Map for fast key-value lookups.
    Use ConcurrentHashMap for multi-threaded environments.


    7)  Can you write the simple code for HashMap?
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Set;

    class Hashkeyvalue {
     public static void main(String[] args) {
      HashMap h = new HashMap();
      h.put(10, "swamy");
      h.put(20, "narayan");
      h.put(30, "raj");
      System.out.println(h);
      Set s = h.entrySet();
      Iterator it = s.iterator();
      while (it.hasNext()) {
       Map.Entry m1 = (Map.Entry) it.next();
       System.out.println(m1.getKey() + "....." + m1.getValue());

    // Using Java 8 Streams to iterate and print key-value pairs
            map.entrySet().stream()
                .forEach(entry -> System.out.println(entry.getKey() + "....." + entry.getValue()));
        }
      // Print only keys
            System.out.println("Keys:");
            map.keySet().stream()
                .forEach(key -> System.out.println(key));

       // Print only values
            System.out.println("Values:");
            map.values().stream()
                .forEach(value -> System.out.println(value));


      }
     }
    }

    8) What are thread states?

     Thread Life Cycle in Java
    Below diagram shows different states of thread life cycle in java. We can create a thread in java and start it but how the thread states change from Runnable to Running to Blocked depends on the OS implementation of thread scheduler and java doesn’t have full control on that.



    New
    When we create a new Thread object using new operator, thread state is New Thread. At this point, thread is not alive and it’s a state internal to Java programming.
    Runnable
    When we call start() function on Thread object, it’s state is changed to Runnable. The control is given to Thread scheduler to finish it’s execution. Whether to run this thread instantly or keep it in runnable thread pool before running, depends on the OS implementation of thread scheduler.
    Running
    When thread is executing, it’s state is changed to Running. Thread scheduler picks one of the thread from the runnable thread pool and change it’s state to Running. Then CPU starts executing this thread. A thread can change state to Runnable, Dead or Blocked from running state depends on time slicing, thread completion of run() method or waiting for some resources.
    Blocked/Waiting
    A thread can be waiting for other thread to finish using thread join or it can be waiting for some resources to available. For example producer consumer problem or waiter notifier implementation or IO resources, then it’s state is changed to Waiting. Once the thread wait state is over, it’s state is changed to Runnable and it’s moved back to runnable thread pool.
    Dead
    Once the thread finished executing, it’s state is changed to Dead and it’s considered to be not alive.
       
    9)    What are differences b/w concrete, abstract classes and interface & they are given?
       
          Concrete class:   A class of  only Concrete methods is called Concrete Class.
                                      For this, object instantiation is possible directly.
                                      A class can extends one class and implements many interfaces.
                   Abstract class:
                          Interface:
        1) Abstract class contains only Concrete methods or Abstract methods or both.


        2)Any java class can extend only one abstract class.

        3) Abstract class won’t force the programmer to implement/override
         all its methods.
        4) Abstract class takes less execution timethan interface.

        5)  Abstract class allows constructor.

        6) Abstract class can’t be instantiated   directly.              
        7) A class must be abstract when it consist at least one abstract method.     
        8) Abstract class gives less scope than an Interface.
        9) Abstract class allows both variable constants declaration.
       10) Abstract class allows method definitions or declarations whenever we   want.
         Where as interface methods are implicitly abstract unless the interface methods are static or default. Static methods and default methods in interfaces are added in Java 8.
         class can implements any no. of  interfaces
        (this gives multiple interface inheritance )
         Interface forces the programmer to implement all its methods

        Interface takes more execution time due to its complex hierarchy.

        Interface won’t allow any constructor.

        Interface can’t be instantiated but it can refer to its subclass objects.
                         ----------
                       ---------
        Interface gives more scope than an abstract class.
        variables are public static final.

         Interface allows  method declarations whenever we want . But it involves complexity.

    Some interview questions

    How to reverse a String in Java?
    How to swap two numbers without using a third variable?
    Seperate vowels and consonants from given string
    Java program to check if the given number is Prime
    Check given string is palindrome or not
    Print number of largest polindrome in a string
    Fibonacci Series
    How to remove Whitespaces from String
    Sorting an array
    Find factorial of an integer?
    Find common elements from 2 arrays
    How to get distinct characters and their count in a String?
    Java8 filter, groupby,
    Java map() and to toMap() Programs
    Java 8 convert list into map
    Functional interface 
    Lamda expressions
    Method references
    Internal working of Hash Map, Hashset, concurrent hashmap.
    Difference b/w hashmap and concurrent hashmap
    Difference Synchronized map and concurrent hashmap

    11)   How to retieve the objects from an ArrayList?
         

    import java.util.ArrayList;

    import java.util.Collections;

    import java.util.List;


    class ArrayListDemo {

    public static void main(String[] args) {

    List<Integer> a = new ArrayList<>(

    java.util.Arrays.asList(10, 6, 5, 1, 3, 7, 9, 8, 4, 2, 5, 1, 3, 7, 9, 82, 42)

    );

    // (Or) List<Integer> a = new ArrayList<>(List.of(10, 6, 8, 4, 2, 5, 1, 3, 7, 9, 82, 42));

    Collections.sort(a);

    System.out.println(a);


    a.subList(4, 10).forEach(System.out::println); // Prints elements from index 4 to 9

    }

    }


    12)   What are versions of your current project technologies?
         Java 7.0; Servlets 3.0, Jsp 3.0; spring 3.2.5; RestFul, Mongo DB 3.7,  Tomcat 8,
    Java 6.0; Servlets 2.4, Jsp 2.0; spring 2.5; Hibernate 3.2, Oracle 10g. weblogic 10.0.

    13)    What is “Quality”?
          It is a Measure of excellence, state of being free from defects, deficiencies, and significant  variations.
         A product or service that bears its ability to satisfy stated or implied needs."

    14)   Can I take a class as “private”?
            Yes, but it is declare to inner class, not to outer class.
           If we are declaring "private" to outer class then we get compile time error as
           modifier private not allowed here.

    private class Sample {
    public static void main(String[] args) {
    System.out.println("Hi");
    }

    }
    Output:
    Exception in thread "main" java.lang.Error: Unresolved compilation problem:

    15)    How can you clone an object?

               A a1=new  A();
               B  a11=a1.clone();

    Java Object class comes with native clone()method that returns the exact  copy of the existing instance.
    Shallow Cloning
    Default implementation of java clone object is using shallow copy.
    // Java program to demonstrate that assignment
    // operator only creates a new reference to same  object.
    // A test class whose objects are cloned
    class ShallowCloningTest {
           int x, y;
           ShallowCloningTest() {
                  x = 10;
                  y = 20;
           }
    }
    // Driver Class
    class ShallowCloningMain {
           public static void main(String[] args) {
                  ShallowCloningTest ob1 = new ShallowCloningTest();
                  System.out.println(ob1.x + " " + ob1.y);

                  // Creating a new reference variable ob2
                  // pointing to same address as ob1
                  ShallowCloningTest ob2 = ob1;

                  // Any change made in ob2 will be reflected in ob1
                  ob2.x = 100;
                  System.out.println(ob1.x + " " + ob1.y);
                  System.out.println(ob2.x + " " + ob2.y);
           }
    }
    Output:
    10 20
    100 20
    100 20

    Deep Cloning
    In deep cloning, we have to copy fields one by one. We can override the clone method like below for deep cloning.
    A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.
    // A Java program to demonstrate deep copy  using clone()
    // An object reference of this class is  contained by Test2
    class DeepCloningTest {
           int x, y;
    }

    // Contains a reference of Test and implements clone with deep copy.
    class DeepCloningTest2 implements Cloneable {
           int a, b;
           DeepCloningTest c = new DeepCloningTest();

           public Object clone() throws CloneNotSupportedException {
                  // Assign the shallow copy to new refernce variable t
                  DeepCloningTest2 t = (DeepCloningTest2) super.clone();
                  t.c = new DeepCloningTest();
                  // Create a new object for the field c
                  // and assign it to shallow copy obtained, to make it a deep copy
                  return t;
           }
    }

    public class DeepCloningMain {
           public static void main(String args[]) throws CloneNotSupportedException {
                  DeepCloningTest2 t1 = new DeepCloningTest2();
                  t1.a = 10;
                  t1.b = 20;
                  t1.c.x = 30;
                  t1.c.y = 40;
                  DeepCloningTest2 t3 = (DeepCloningTest2) t1.clone();
                  t3.a = 100;
                  // Change in primitive type of t2 will not be reflected in t1 field
                  t3.c.x = 300;
                  // Change in object type field of t2 will not be reflected in t1(deep
                  // copy)
                  System.out.println(t1.a + " " + t1.b + " " + t1.c.x + " " + t1.c.y);
                  System.out.println(t3.a + " " + t3.b + " " + t3.c.x + " " + t3.c.y);
           }
    }
    Output:
    10 20 30 40
    100 20 300 0

    Cloning using Serialization
    One way to easily perform deep cloning is through serialization. But serialization is an
     expensive procedure and your class should implement Serializable interface.
    Cloning in java using Apache Commons Util
    If you are already using Apache Commons Util classes in your project and your class is serializable, then use below method.
    Employee clonedEmp = org.apache.commons.lang3.SerializationUtils.clone(emp);
    Copy Constructor for Cloning
    We can also define copy constructor and get a copy of object and don’t depend on the cloning at all. For example, we can have Employee constructor like below.
    public Employee(Employee emp) {
                    this.setId(emp.getId());
                    this.setName(emp.getName());
                    Map<String, String> hm = new HashMap<>();
                    String key;
                    Iterator<String> it = emp.getProps().keySet().iterator();
                    // Deep Copy of field by field
                    while (it.hasNext()) {
                                    key = it.next();
                                    hm.put(key, emp.getProps().get(key));
                    }
                    this.setProps(hm);
    }

    16)   What is marker interface?
       Interfaces with no methods are known as marker interfaces.
    Marker interfaces are Serializable, Clonable, SingleThreadModel, Event listener.
    Marker Interfaces are implemented by the classes or their super classes in order to add some functionality.
    e.g.  Suppose you want to persist (save) the state of an object then you have to implement the Serializable interface otherwise the compiler will throw an error. 
    Suppose the interface Clonable is neither implemented by a class named Myclass nor it's any super class, then a call to the method clone() on Myclass's object will give an error. This means, to add this functionality one should implement the Clonable interface. While the Clonable is an empty interface but it provides an important functionality.
         When a class implements this interface that class obtains some special behavior and that
    will be realized by the JVM.
    Even though an interface contains some methods by implementing that interface if our objects will
    get some ability. Such type of interfaces are called ‘marker’ or ‘taginterfaces’
    Ex:
    Comparable, Runnable.

    17)   What  Design Patterns are you using in your project?
           i) MVC --->  separates  roles using different technologies,
          ii)  Singleton Java class --> To satisfy the Servlet Specification, a servlet must be a Single
                                                     Instance  multiple thread component.
          iii) D.T.O/ V.O---> Data Transfer Object/Value object is there to send huge amount of data
           from one lalyer to another layer. It avoids Network Round trips.
          iv) IOC/Dependency Injection--->  Framework or container can automatically instantiates the
                                                    objects  implicitly and  injects  the dependent data to that object.
          v) Factory method--->  By using class name if we call any method and return same class    object.Then that method is consider as factory method.
                While developing projects one application contains so many sub classes.Then we go for factory method.  It won’t allows object instantiation from out-side of the class.
          vi) View Helper----> It is there to develop a JSP without Java code so that readability,
                                          re-usability will become easy.
      vii) Front Controller---> dispatcher servlet  developed as FrontController can traps only the requests.


    We are used various design patterns to improve modularity, maintainability, and scalability. Here are some of the key design patterns are used in my current project:

    1. Creational Design Patterns

    (a) Singleton Pattern

    Used in: Spring Beans
    How it works: Spring manages beans as singletons by default, ensuring that only one instance of a bean exists within the Spring container.

    @Service
    public class UserService {
        // Spring automatically ensures a single instance of this bean
    }

    (b) Factory Pattern
    Used in: BeanFactory, ApplicationContext, FactoryBean
    How it works: Provides an interface to create objects without exposing the instantiation logic.

    @Configuration
    public class AppConfig {
        @Bean
        public RestTemplate restTemplate() {
            return new RestTemplate();
        }
    }

    (c) Builder Pattern
    Used in: Object construction for complex objects (e.g., DTOs, Entities)

    public class User {
        private String name;
        private String email;

        public static class Builder {
            private String name;
            private String email;

            public Builder name(String name) {
                this.name = name;
                return this;
            }

            public Builder email(String email) {
                this.email = email;
                return this;
            }

            public User build() {
                return new User(this);
            }
        }

        private User(Builder builder) {
            this.name = builder.name;
            this.email = builder.email;
        }
    }

    2. Structural Design Patterns
    (a) Proxy Pattern
    Used in: Spring AOP (Aspect-Oriented Programming), Transaction Management
    How it works: Spring creates proxy objects to implement cross-cutting concerns (e.g., logging, security, transactions).

    @Transactional
    public void updateUser(User user) {
        // Spring creates a proxy to handle transactions
    }
    @Component
    public class ExternalServiceAdapter {
        private final RestTemplate restTemplate;

        public ExternalServiceAdapter(RestTemplate restTemplate) {
            this.restTemplate = restTemplate;
        }

        public ExternalResponse getExternalData(String url) {
            return restTemplate.getForObject(url, ExternalResponse.class);
        }
    }

    (b) Adapter Pattern
    Used in: Integrating third-party services (e.g., API clients, database adapters)

    @Component
    public class ExternalServiceAdapter {
        private final RestTemplate restTemplate;

        public ExternalServiceAdapter(RestTemplate restTemplate) {
            this.restTemplate = restTemplate;
        }

        public ExternalResponse getExternalData(String url) {
            return restTemplate.getForObject(url, ExternalResponse.class);
        }
    }

    (c) Decorator Pattern
    Used in: Custom Logging, Caching (e.g., Redis), Security Enhancements
    @Service
    public class LoggingUserServiceDecorator implements UserService {
        private final UserService userService;

        public LoggingUserServiceDecorator(UserService userService) {
            this.userService = userService;
        }

        @Override
        public User getUserById(Long id) {
            System.out.println("Fetching user with ID: " + id);
            return userService.getUserById(id);
        }
    }

    3. Behavioral Design Patterns
    (a) Strategy Pattern
    Used in: Defining multiple implementations of a feature (e.g., payment gateways, authentication methods)

    public interface PaymentStrategy {
        void pay(double amount);
    }

    @Component
    public class CreditCardPayment implements PaymentStrategy {
        @Override
        public void pay(double amount) {
            System.out.println("Paid " + amount + " using Credit Card");
        }
    }

    @Component
    public class PaypalPayment implements PaymentStrategy {
        @Override
        public void pay(double amount) {
            System.out.println("Paid " + amount + " using PayPal");
        }
    }

    (b) Observer Pattern
    Used in: Event-driven programming using ApplicationEventPublisher
    @Component
    public class UserRegistrationEventPublisher {
        @Autowired
        private ApplicationEventPublisher eventPublisher;

        public void publishUserRegisteredEvent(User user) {
            eventPublisher.publishEvent(new UserRegisteredEvent(this, user));
        }
    }

    @Component
    public class UserRegistrationListener {
        @EventListener
        public void handleUserRegistration(UserRegisteredEvent event) {
            System.out.println("User Registered: " + event.getUser().getName());
        }
    }
    (c) Template Method Pattern
    Used in: Defining a workflow skeleton with steps that subclasses must implement
    public abstract class ReportGenerator {
        public void generateReport() {
            fetchData();
            processData();
            formatReport();
        }

        protected abstract void fetchData();
        protected abstract void processData();
        protected abstract void formatReport();
    }

    public class PdfReportGenerator extends ReportGenerator {
        @Override
        protected void fetchData() { /* fetch data logic */ }

        @Override
        protected void processData() { /* process data logic */ }

        @Override
        protected void formatReport() { /* format report as PDF */ }
    }

    4. Microservices-Specific Design Patterns

    (a) API Gateway Pattern

    Used in: Centralizing requests in microservices architecture (Spring Cloud Gateway)
    @Configuration
    public class ApiGatewayConfig {
        @Bean
        public RouteLocator routes(RouteLocatorBuilder builder) {
            return builder.routes()
                .route("user-service", r -> r.path("/users/**").uri("lb://USER-SERVICE"))
                .route("order-service", r -> r.path("/orders/**").uri("lb://ORDER-SERVICE"))
                .build();
        }
    }
    @Configuration
    public class ApiGatewayConfig {
        @Bean
        public RouteLocator routes(RouteLocatorBuilder builder) {
            return builder.routes()
                .route("user-service", r -> r.path("/users/**").uri("lb://USER-SERVICE"))
                .route("order-service", r -> r.path("/orders/**").uri("lb://ORDER-SERVICE"))
                .build();
        }
    }
    (b) Circuit Breaker Pattern
    Used in: Fault tolerance (Resilience4j, Hystrix)
    @RestController
    public class PaymentController {
        @Autowired
        private PaymentService paymentService;

        @GetMapping("/pay")
        @CircuitBreaker(name = "paymentService", fallbackMethod = "fallbackPayment")
        public String processPayment() {
            return paymentService.pay();
        }

        public String fallbackPayment(Exception e) {
            return "Payment Service is currently unavailable.";
        }
    }

    Conclusion

    In my Spring Boot project, these design patterns help improve:

    • Scalability (e.g., Microservices patterns like API Gateway, Circuit Breaker)
    • Code reusability (e.g., Template Method, Strategy Pattern)
    • Maintainability (e.g., Singleton, Factory, Proxy)
    • Extensibility (e.g., Observer, Decorator)


    18)   What is Singleton Java class & its importance?
          A Java class that allows to create only one object per JVM is called Singleton Java class.
         Ex:  DriverManager class is a Singleton Java class.

            Use: Instead of creating multiple objects for a Java class having same data, it is recommended 
         to  create only one object & use it for multiple no. of times.

      Singleton Pattern is a design pattern that is used to restrict instantiation of a class to one object.
    Using private constructor and factory method, we can create singleton class.
     class Ourownsingleton {
     private static Ourownsingleton t;

     private Ourownsingleton() {
     }

     public static Ourownsingleton getInstance() {
      if (t == null) {
       t = new Ourownsingleton();
      }
      return t;
     }

     public Object clone() {
      return this;
     }

     public static void main(String[] args) {
      Ourownsingleton t1 = Ourownsingleton.getInstance();
      Ourownsingleton t2 = Ourownsingleton.getInstance();
      System.out.println(t1);
      System.out.println(t2);
     }
    }

    19)   What are the differences b/w struts, spring and hibernate?
           Struts:  allows to develop only webapplications and
                         it can’t support POJO/POJI model programming.
       
          Spring: is useful in developing all types of Java applications and
                        support POJO/POJI model programming.

     Hibernate: is used to  develop database independent persistence logic
                         It also supports POJO/POJI model programming.

    20)   What are Access Specifiers & modifiers?
               In java there is no access specifiers, and all are access modifiers. These are
         i) public--->    Universal access specifier.
                           --can be used along with: class, inner class, Interface, variable, constructor, method.     
        ii) protected -->  Inherited access modifier.
                                --can be used along with: inner class, variable, method, constructor.
        iii) default -->  Package access modifier(with in the package).
                        --can be used along with: class, inner class, interface, variable, constructor, method.
       iv) private -->  Native access modifier.
                                 -- can be used along with: inner class, variable, constructor, method.

     Some other access modifiers:
          i) static------------inner class,variable,block,method.
         ii) abstract—----- class,method.
        iii) final--------------class,variable,method.
        iv) synchronized---block,method.
        v) native-------------method.
        vi) transient---------variable.
       vii) volatile-----------variable
    viii) strict fp-----------variable

    21) If double is added to String then what is the result?
                Double + String=String

    22) differences b/w a Vector & a ArrayList?


    1)Synchronization : Vector is synchronized, which means only one thread at a time can access the code, while arrayList is not synchronized, which means multiple threads can work on arrayList at the same time. For example, if one thread is performing an add operation, then there can be another thread performing a remove operation in a multithreading environment.
    If multiple threads access arrayList concurrently, then we must synchronize the block of the code which modifies the list structurally, or alternatively allow simple element modifications. Structural modification means addition or deletion of element(s) from the list. Setting the value of an existing element is not a structural modification.
    2)Performance: ArrayList is faster, since it is non-synchronized, while vector operations give slower performance since they are synchronized (thread-safe). If one thread works on a vector, it has acquired a lock on it, which forces any other thread wanting to work on it to have to wait until the lock is released.
    3)Data Growth: ArrayList and Vector both grow and shrink dynamically to maintain optimal use of storage – but the way they resize is different. ArrayList increments 50% of the current array size if the number of elements exceeds its capacity, while vector increments 100% – essentially doubling the current array size.

    4)Traversal: Vector can use both Enumeration and Iterator for traversing over elements of vector while ArrayList can only use Iterator for traversing.

    23) How can you achieve Concurrence in Java?
         Using Multithreading.
       The backbone of java concurrency is threads. A thread is a lightweight process which has its own call stack, but can access shared data of other threads in the same process. A Java application runs by default in one process. Within a Java application you can work with many threads to achieve parallel processing or concurrency.

    24)  How to implement Synchronization? Can we use synchronized with variables?
          ‘Synchronized’ is the keyword applicable for the methods and blocks. We can’t apply this keyword for variables and classes.
          The process of allowing only one thread among n no. of  threads into a Sharable Resource
     to perform “Read” & “Write” operations.
       If a method declared as synchronized at a time only one thread is allowed to execute that method on the given object. The main advantage of synchronized keyword is we can overcome data
    inconsistency problem. The main limitation of synchronized keyword is it may create preference problems.
    Hence if there is no specific requirement it’s not recommended to use synchronized keyword.
    Every object in java has a unique lock. Whenever we are using synchronized keyword then object level lock concept will come into picture. If a thread want to execute any synchronized method on the object first it should require the lock of that object. Once a thread got the lock then it is allowed to execute any synchronized method on that object.
        While a thread executing a synchronized method on the object, then the remaining threads are not allowed to execute any synchronized method on the same object. But the remaining threads are allowed to execute any non-synchronized method on the same object.
    Every object in java has unique lock but a thread can acquire more than one lock at a time.
    Ex:
    class Display
    {
     public synchronized void wish(String name)
     {
      for (int i = 0; i < 10; i++)
      {
       System.out.print("Hai.......!");
       try
       {
        Thread.sleep(2000);
       }
       catch (InterruptedException e)
       {

       }
       System.out.println(name);
      }
     }
    }
    class MyThread extends Thread
    {
     Display d;
     String name;
     MyThread(Display d, String name)
     {
      this.d = d;
      this.name = name;
     }
     public void run()
     {
      d.wish(name);
     }
    }
    class SynchronizedDemo
    {
     public static void main(String arg[])
     {
      Display d = new Display();
      MyThread t1 = new MyThread(d, "YS");
      MyThread t2 = new MyThread(d, "Babu");
      t1.start();
      t2.start();
     }
    }

    25) What are oop principles?
          Abstraction, Encapsulation, Inheritance, Polymorphism.

    Inheritance Example:

    class A {
     int i = 10;

     protected void m1() {
      System.out.println("parent1 class");
     }

     protected void m2() {
      System.out.println("parent2 class");
     }
    }

    class B extends A {
     int i = 100;

     public void m1() {
      System.out.println("inter class");
     }

    }

    class C extends A {
     int i = 1000;

     public void m1() {
      System.out.println("child class");
     }

    }

    public class inheriex1 {

     public static void main(String[] args) {
      A a = new A();
      a.m1();

      B b = new B();
      b.m1();
      b.m2();
      A a1 = new B();
      a1.m1();
      a1.m2();
      A a2 = new C();
      a2.m1();
      a2.m2();

     }

    }
    Output:
    parent1 class
    inter class
    parent2 class
    inter class
    parent2 class
    child class
    parent2 class

    26) What is polymorphism?
       Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon. In other words, polymorphism allows you define one interface and have multiple implementation. This is one of the basic principles of object oriented programming.
    The method overriding is an example of runtime polymorphism. You can have a method in superclass overrides the method in its sub classes with the same name and signature. Java virtual machine determines the proper method to call at the runtime, not at the compile time.
    Let's take a look at the following example:
    class Animal {
      void whoAmI() {
        System.out.println("I am a generic Animal.");
      }
    }
    class Dog extends Animal {
      void whoAmI() {
        System.out.println("I am a Dog.");
      }
    }
    class Cow extends Animal {
      void whoAmI() {
        System.out.println("I am a Cow.");
      }
    }
    class RuntimePolymorphismDemo {
      public static void main(String[] args) {
        Animal ref1 = new Animal();
        Animal ref2 = new Dog();
        Animal ref3 = new Cow();
        ref1.whoAmI();
        ref2.whoAmI();
        ref3.whoAmI();
      }
    }
    The output is
    I am a generic Animal.
    I am a Dog.
    I am a Cow.

    Method overloading and method overriding uses concept of Polymorphism in Java where method name remains same in two classes but actual method called by JVM depends upon object at run time and done by dynamic binding in Java.
     Method overriding nothing but runtime polymorphism.And Method overloading is nothing but compiletime polymorphism in java.

    27)  What is overloading and overriding? Give one example?
          Overloading is the process of re-defining a method for multiple times
                                with different Signature.
    Example:
    class Overloadex2 {
     public String m1(String s) {
      System.out.println("string method1");
      return "null";

     }

     public int m1(int s1) {
      System.out.println("int method1");
      return -1;
     }

     public Object m1(Object s2) {
      System.out.println("object method1");
      return "";
     }

     public Object m1() {
      System.out.println("object method2");
      return -1;
     }
    }

    public class Overloadex1 {
     public static void main(String[] args) {
      Overloadex2 overloadex2 = new Overloadex2();
      overloadex2.m1("ab");
      overloadex2.m1(null);
      overloadex2.m1();
      overloadex2.m1(-2);
      overloadex2.m1(0);
     }
    }
    Output: string method1
                string method1
                object method2
                int method1
                int method1


           Overriding is a process of re-defining a super class original version
                                                in its various derived classes through inheritance.
    Example:
    //overridding concept

    class overex3 {
     public Object m1() {
      System.out.println("hi overex3 object");
      return 1;
     }
     public String m1(Float f) {
      System.out.println("hi overex3 float");
      return "hi return m1";

     }
     public String m1(String s1) {
      System.out.println("hi overex3 string");
      return "java return m1";

     }
    }

    public class Overrideex3 extends overex3 {

     public Object m1() {
      System.out.println("hello Overrideex3 object");
      return 1;
     }

     public String m1(String s1) {
      System.out.println("hello Overrideex3 string");
      return "java return m1";

     }

     public static void main(String[] args) {
      // TODO Auto-generated method stub
      // System.out.println("hi!..........");
      overex3 o = new overex3();
      o.m1("java");
      o.m1();
     }

    }
    Output:
    hi overex3 string
    hi overex3 object

    28) What is encapsulation & abstraction?
         Encapsulation is, a technique, used to encapsulate the properties &  behaviors of an object.
    It focuses on inside-view and solves problems at “implementation side”.

      Abstract class in Java Important Points
    1) abstract keyword is used to create an abstract class in java.
    2) Abstract class in java can’t be instantiated.
    3) We can use abstract keyword to create an abstract method, an abstract method doesn’t have body.
    4) If a class have abstract methods, then the class should also be abstract using abstract keyword, else it will not compile.
    5) It’s not necessary to have abstract class to have abstract method. We can mark a class as abstract even if it doesn’t declare any abstract methods.
    6) If abstract class doesn’t have any method implementation, its better to use interface because java doesn’t support multiple class inheritance.
    7) The subclass of abstract class in java must implement all the abstract methods unless the subclass is also an abstract class.
    8) All the methods in an interface are implicitly abstract unless the interface methods are static or default. Static methods and default methods in interfaces are added in Java 8, for more details read Java 8 interface changes.
    9) Java Abstract class can implement interfaces without even providing the implementation of interface methods.
    10) Java Abstract class is used to provide common method implementation to all the subclasses or to provide default implementation.
    11) We can run abstract class in java like any other class if it has main() method.

    29)  While overriding a exception throwing method, does it mandatory that subclass must
               also throw the same exception? No
    30)  In an application, one task  has to be done for every 15 minutes. How can you do it?

    31)  How do you sort on one property(field) of a class?
              Using Comparable and Comparator interfaces.

    Comparable
    A comparable object is capable of comparing itself with another object  using comareTo() method. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.
    Example 1:
    class Student implements Comparable<Student>{  
    int rollno;  
    String name;  
    int age;  
    Student(int rollno,String name,int age){  
    this.rollno=rollno;  
    this.name=name;  
    this.age=age;  
    }  
    public int compareTo(Student st){  
    if(age==st.age)  
    return 0;  
    else if(age>st.age)  
    return 1;  
    else  
    return -1;  
    }  
    }
    Example 2):
    package comparableandcomparator;

    import java.util.Arrays;

    public class ComparableEmployee implements Comparable<ComparableEmployee> {

     private int id;
     private String name;
     private int age;
     private long salary;

     public int getId() {
      return id;
     }

     public String getName() {
      return name;
     }

     public int getAge() {
      return age;
     }

     public long getSalary() {
      return salary;
     }

     public ComparableEmployee(int id, String name, int age, int salary) {
      this.id = id;
      this.name = name;
      this.age = age;
      this.salary = salary;
     }

     @Override
     // this is overridden to print the user-friendly information about the
     // Employee
     public String toString() {
      return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary=" + this.salary + "]";
     }

     public static void main(String[] args) {
      // sorting object array
      ComparableEmployee[] empArr = new ComparableEmployee[4];
      empArr[0] = new ComparableEmployee(10, "Mikey", 25, 10000);
      empArr[1] = new ComparableEmployee(20, "Arun", 29, 20000);
      empArr[2] = new ComparableEmployee(5, "Lisa", 35, 5000);
      empArr[3] = new ComparableEmployee(1, "Pankaj", 32, 50000);

      // sorting employees array using Comparable interface implementation
      Arrays.sort(empArr);
      System.out.println("Default Sorting of Employees list:\n" + Arrays.toString(empArr));
     }

     @Override
     public int compareTo(ComparableEmployee emp) {
      // let's sort the employee based on an id in ascending order
      // returns a negative integer, zero, or a positive integer as this
      // employee id
      // is less than, equal to, or greater than the specified object.
      return -1;
     }

    }

    Comparator
    A comparator object is capable of comparing two different objects using equals() and compare(). The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface. Example 1:
    import java.util.*;
    import java.lang.*;
    import java.io.*;
      
    // A class to represent a student.
    class Student
    {
        int rollno;
        String name, address;
      
        // Constructor
        public Student(int rollno, String name,
                                   String address)
        {
            this.rollno = rollno;
            this.name = name;
            this.address = address;
        }
      
        // Used to print student details in main()
        public String toString()
        {
            return this.rollno + " " + this.name +
                               " " + this.address;
        }
    }
      
    class AgeComparator implements Comparator<Student>
    {
        public int compare(Object obj1, Object obj2)
        {
            Student s1 = (Student)obj1;
            Student s2 = (Student)obj2;
            if(s1.age==s2.age)
               return 0;
            else if (s1.age > s2.age)
              return 1;
            else
              return  -1; 
        }
    }
      
    class Sortbyname implements Comparator<Student>
    {
        public int compare(Object obj1, Object obj2)
        {
            Student s1 = (Student)obj1;
            Student s2 = (Student)obj2;
           return s1.name.compareTo(s2.name);
        }
               (OR)
        public int compare(Student s1, Student s1)
        {
            return s1.name.compareTo(s2.name);
        }
    }
    Example 2:
    package comparableandcomparator;

    // Java program to demonstrate working of Comparator
    // interface
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;

    // A class to represent a student.
    class Student {
     int rollno;
     String name, address;

     // Constructor
     public Student(int rollno, String name, String address) {
      this.rollno = rollno;
      this.name = name;
      this.address = address;
     }

     // Used to print student details in main()
     public String toString() {
      return this.rollno + " " + this.name + " " + this.address;
     }
    }

    class Sortbyroll implements Comparator<Student> {
     // Used for sorting in ascending order of
     // roll number
     public int compare(Student a, Student b) {
      return a.rollno - b.rollno;
     }
    }

    class Sortbyname implements Comparator<Student> {
     // Used for sorting in ascending order of
     // roll name
     public int compare(Student a, Student b) {
      return a.name.compareTo(b.name);
     }
    }

    // Driver class
    class ComparatorStudent {
     public static void main(String[] args) {
      ArrayList<Student> ar = new ArrayList<Student>();
      ar.add(new Student(111, "bbbb", "london"));
      ar.add(new Student(131, "aaaa", "nyc"));
      ar.add(new Student(121, "cccc", "jaipur"));

      System.out.println("Unsorted");
      for (int i = 0; i < ar.size(); i++)
       System.out.println(ar.get(i));

      Collections.sort(ar, new Sortbyroll());

      System.out.println("\nSorted by rollno");
      for (int i = 0; i < ar.size(); i++)
       System.out.println(ar.get(i));

      Collections.sort(ar, new Sortbyname());

      System.out.println("\nSorted by name");
      for (int i = 0; i < ar.size(); i++)
       System.out.println(ar.get(i));
     }
    }


    32)   If my class is having 5 abstract methods then can I make it as an interface?
              Yes
    33)   Which cvs tool are you using? What are the methods that are there?
             Commit().
             Update()

    34)  Difference b/w Checked & Unchecked Exception?
           The exceptions which are checked by the compiler for smooth execution of the program at runtime are called “Checked Exceptions”.
    Ex:  ClassNotFoundException---Java ClassNotFoundException occurs when the application tries to load a class but Classloader is not able to find it in the classpath..
     InterruptedException,---when two or more threads try to share same Resource(wait() and join())
    NoSuchFieldException ---when we access the undeclared variable
    NoSuchMethodException---when we invoke the undeclared method.
    InstantiationException---when we try to create object for a abstract/interface

          The exceptions which are unble to checked by the compiler are called “Unchecked Exceptions”
     Ex: ArithmeticException,
          ArrayOutOfBoundsException,
          NullPointerException

    ExceptionDemo Example:
    package exception;

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;

    // Java program to demonstrate built-in Exceptions
    class Exception_Demo {
     public static void main(String args[]) {
      Exception_Demo exception_Demo = new Exception_Demo();
      exception_Demo.arithmeticException_Demo();
      exception_Demo.arrayIndexOutOfBoundsException_Demo();
      exception_Demo.nullPointerException_Demo();
      exception_Demo.numberFormatException_Demo();
      exception_Demo.stringIndexOutOfBoundsException_Demo();
      exception_Demo.fileNotFoundException_Demo();
     }

     public void arithmeticException_Demo() {
      try {
       int a = 30, b = 0;
       int c = a / b; // cannot divide by zero
       System.out.println("Result = " + c);
      } catch (StringIndexOutOfBoundsException e) {
       System.out.println("StringIndexOutOfBoundsException");
      } catch (NumberFormatException e) {
       System.out.println("Number format exception");
      } catch (NullPointerException e) {
       System.out.println("NullPointerException..");
      } catch (ArrayIndexOutOfBoundsException e) {
       System.out.println("Array Index is Out Of Bounds");
      } catch (ArithmeticException e) {
       System.out.println("ArithmeticException Can't divide a number by 0");
      } catch (Exception e) {
       System.out.println("Exception");
       e.printStackTrace();
      } finally{
       System.out.println("finally block");
      }

     }

     public void arrayIndexOutOfBoundsException_Demo() {
      try {
       int a[] = new int[5];
       a[6] = 9; // accessing 7th element in an array of
          // size 5
      } catch (ArrayIndexOutOfBoundsException e) {
       System.out.println("Array Index is Out Of Bounds");
      }
     }

     public void nullPointerException_Demo() {
      try {
       String a = null; // null value
       System.out.println(a.charAt(0));
      } catch (NullPointerException e) {
       System.out.println("NullPointerException..");
      }
     }

     public void numberFormatException_Demo() {
      try {
       // "akki" is not a number
       int num = Integer.parseInt("akki");

       System.out.println(num);
      } catch (NumberFormatException e) {
       System.out.println("Number format exception");
      }
     }

     public void stringIndexOutOfBoundsException_Demo() {
      try {
       String a = "This is like chipping "; // length is 22
       char c = a.charAt(24); // accessing 25th element
       System.out.println(c);
      } catch (StringIndexOutOfBoundsException e) {
       System.out.println("StringIndexOutOfBoundsException");
      }
     }

     public void fileNotFoundException_Demo() {
      try {

       // Following file does not exist
       File file = new File("E://file.txt");

       FileReader fr = new FileReader(file);
      } catch (FileNotFoundException e) {
       System.out.println("File does not exist");
      }
     }
    }

    35)  Differenc b/w Exception & Error?
      Exceptions are recoverable,most of the cases exceptions are raised due to program only.
    Errors are non-recoverable,most of the cases errors are due lock of system resources but not due to our programs.

    36)   What is final ?
            final is the modifier applicable for classes,methods and variables.
    i)if a class declared as final ,then we cann’t create child class.
    ii)if a method declared as final,then we are not override that method in the child class.
    iii)if a variable declared as final,we cann’t change that variable.

    37)  How can you invoke a current class constructor from a method ?
           By using “this”.

    38)   How can you invoke a super class constructor from derived class?
            Using “super()”

    39)  What is “static”?

       Static is a keyword, applicable for methods, blocks, variables and nested classes.
       Static variables a single copy will be created at class level and shared by all objects of that
    class.
       Static variables should be declared with in the class but outside of any method or block or
    constructor.
       Static variables will be created at the time of class loading and destroyed at the time of unloading.
    We can access static variables either by using class name or by using object reference using class
    name is recommended.
    Ex:
    class Test
    {
    int i;
    static int j = 10;
    public static void main(String arg[])
    {
    Test t1 = new Test();
    t1.i = 888;
    t1.j = 999;
    Test t2 = new Test();
    System.out.println(t2.i+" ----"+t2.j);
    }
    }
    O/P:- 0----999
    For the static variables no need to perform initialization JVM will always provide default values.
    Ex:
    class Test
    {
    static int i;
    public static void main(String arg[])
    {
    System.out.println(i); //0
    }
    }

    40)  What is “instanceOf”?
          The operator that checks whether given instance is belongs to the given class or not.
    41)   Can I create an interface without methods, constants declarations?
                  Yes

    42)   Can I place try & catch blocks in finally block?
             Yes

    43)   What are the clone types?

    44)   How can you make an ArrayList as Synchronized list?
       List l=Collections.synchronizedArrayList(new ArrayLsit());
        Map m=Collections.synchronizedMap(new HashMap());

    45)  What is Serialization?
             Writing the state of an object in to Streams or files is called Serialization.

           The Process of Saving an object to a file is called “serialization”. But strictly
    speaking serialization is the process of converting an object from java supported format to network
    or file supported format.
    By using FileOutPutStream, ObjectOutPutStream classes we can achieve serialization.

            FileOutputStream fos=new FileOutputStream(“file name”);  ---file opened
            ObjectOutputStream oos=new Object OutputStream(fos);          --Object takes file ref
         
            UserDefSerCls   uds=new UserDefSerCls(,” ”,);
             Oos.writeObject(uds);
             Oos.close();

    46)  How can you made the fields of a class to not serialized?
              Using the modifier called “transient”

    47)  What is the use with Generics?
       Array objects are by default typesafe. i.e we declare String Array we can insert only String Objects. By Mistake if we r trying to insert any other elements we will get compile time error.
    Ex:
    String [] s = new String[100];
    s[0] = "raju";
    s[1] = 10;    //C.E
    But Collection objects are not typesafe by default. If our requirement is to add only String objects to the ArrayList , By mistake if we r trying to insert any other element we won’t get any compile time error.
    ArrayList l = new ArrayList();
    l.add(“raju”);
    l.add(new Integer(10)); //No Compile Time Error.

             by using generics we can provide typesafety and we can resolve typecasting problems.
    By using generics we can define parameter for the collection. These parameterized collection classes are nothing but “Generic collection classes”.
    Polymorphism concept is not applicable for the parameter type but applicable for basetype
    List<String> l = new ArrayList<String>()

    The type parameter must be object type(any class or interface name). we can’t apply generic concept for primitive datatype.
    Ex:- ArrayList<int> l = new ArrayList<int>();
    C.E:- unexpected type found : int
    Required : Integer

    In generics we have only extends keyword and there is no implements keyword. It’s purpose is also survived by using extends keyword only.

       Generics is the concept applicable only at compile time to provide type safety, at runtime there is no
    generic concept at all.

    48)  What is “Reflection”?
           It allows to do Mirror image operations on classes/interfaces to get the internal details.

    49)   How do you maintain versions in your project?
             Using SVN.

    50)  What is Junit?
          Junit is new framework designed for Java to perform unit testing. It is an Open source framework. Junit is an instance of xUnit architecture... and writing test cases. Junit also have a Graphical User Interface which allows
         JUnit is an open source framework that has been designed for the purpose of writing and running tests in the Java programming language. JUnit was originally written by Erich Gamma and Kent Beck. There are many ways to write test cases. A test case is a code fragment that checks that another code unit (method) works as expected. So if we want an accurate and efficient testing process then using a good testing framework is recommended. JUnit has established a good reputation in this scenario.
        JUnit is a regression-testing framework that developers can use to write unit tests as they develop systems. Unit testing belongs to test a single unit of code, which can be a single class for Java. This framework creates a relationship between development and testing. You start coding according to the specification and need and use the JUnit test runners to verify how much it deviates from the intended goal. Typically, in a unit testing, we start testing after completing a module but JUnit helps us to code and test both during the development. So it sets more focus on testing the  fundamental building blocks of a system i.e. one block at a time rather than module level functional testing. This really helps to develop test suites that can be run any time when you make any changes in your code. This all process will make you sure that the modifications in the code will not break your system without your knowledge.
    Using a framework, like JUnit, to develop your test cases has a number of advantages, most important being that others will be able to understand test cases and easily write new ones and that most development tools enable for automated and / or one click test case execution.
    JUnit provides also a graphical user interface (GUI) which makes it possible to write and test source code quickly and easily. JUnit shows test progress in a bar that is green if testing is going fine and it turns red when a test fails. There is a lot of pleasure in seeing the green bars grow in the GUI output. A list of unsuccessful tests appears at the bottom of the display window. We can run multiple testsconcurrently. The simplicity of JUnit makes it possible for the software developer to easily correct bugs as they are found.

    51)How Java is Platform Independent?
    Because the magic of byte code.
     .class file—byte code

    52)   What is Association and Composition?

    53)   How can I achieve multiple inheritance in Java without using inheritance?

    54)   Write the code for a class which implements the Runnable interface?
         Public class  RunClass implement Runnable{
                        -------------
                       -------------
           public void run(){
                 ---------
                 }
            Runnable r=new RunClass();
            Thread thr=new Thread(r);
                        thr.start();
    55)   There are m1(), m2() methods and t1,t2 threads.
                How can t1 execute m1() and t2 executes m2()?

    56)    What is “join()”?
           join()
    If a thread wants to wait until some other thread completion then we should go for join method.
    Ex:
    If a thread t1 executes t2.join(), then t1 will be entered into waiting state until t2
    completion.
    public final void join() throws InterruptedException
    public final void join(long ms) throws InterruptedException
    public final void join(long ms, int ns) throws InterruptedException

    57)  What is InterruptedException?
           When two or more threads try to access same object simultaneously, then this exception
             occurs.  Join(), wait(), notify() ,notifyAll() throws InterruptedException.

    58)  What an Interface allows in its inside?
              Inside interface, all variables are by default public static final variables and methods are abstract methods. And static and default methods are allowed in interface from java 8

    59)   Can I define a class inside an Interface?
              Yes
    60)   What is the interface implemented by HashMap and Hashtable?
                Map (i)
    61)   Can you unit test a “private method”?

        Not testing private methods - Sometimes a private method is doing very complicated tasks that should be tested very well, and we don't want that user will have access to this methods. Soon the solution is changing private methods to protected.

    You can't do that with Mockito but you can use Powermock to extend Mockito and mock private methods

    62)   What are the methods with Serializable interface?
             No methods are there in Serializable Interface as a Marker/Tagged Interface.
                             Ex: Serializable, Cloneable, Remote, SingleThreadModel.

    63)   What are the Http request methods?
              GET,POST

    64) Can I Implement Serializable when I don’t want to save the object in persistence stores?  
              If   NetWork  is there then YES else NO.

    65)  What is “reflection api”?
     import java.lang.reflection;
      Reflection API based applications are capable of gathering “internal details 
    about a Java class/ interface by performing Mirror Image Operations on that class/interface.

    66)  What is an Application Server?
         i) It allows to deploy all types of Java applications like web, distributed,enterprise  
             applications.
        ii) It contains both web and ejb containers.
       iii) It gives more implicit middle ware support like Transaction management, Security, Connection pooling.                
             
    67)  How to know the no. of dynamically generated objects of a class?
           Take a Static count variable, pass this to a” Parameter Constructor”  and keep the
             increment operation inside it.

    68)  What are the primitives?
           byte, int, short, long, float, double, char, boolean local variables.

    69)   What happens when we store primitives to Collections?

    70)   What are the Wrapper class objects?
            The primitives are not allowed to store inside the collections. So, they will be converted into
        Wrapper class objects using their respective wrapper classes.
         
    71)   What is the difference between “Apache Server” & “Tomcat Server”?
         Apache/ Apache HTTP Server, is an established standard in the online distribution of website services, which gave the initial boost for the expansion of the W.W.W.
    . It is an open-source web server platform, which guarantees the online availability of the majority of the websites active today.
     The server is aimed at serving a great deal of widely popular modern web platforms/operating systems such as Unix, Windows, Linux, Solaris, Novell NetWare, FreeBSD, Mac OS X, Microsoft Windows, OS/2, etc.

    72)    Why do we require Application Server instead of  Web Server?

    73)   An application is having “images”. Which Server is preferable?

    74)    What is Autoboxing?
             Autoboxing is an implicit automatic conversion from Primitives to Wrapper class objects.
              Ex:  float p_float=0.5f;------à Float 0_float=new Float(p_float);        // will done implicitely.

            Unboxing is an implicit automatic conversion from Wrapper class objects to Primitives.
               Ex:  Float o_float=0.2f;----à  float  p_float=o_float;

    75) What are new features of jdk1.5?
           Generics, Enhanced For loop, Autoboxing/Unboxing, Static import, Annotations.

    76)   Write the code for “Enhanced for loop”?
             int[]   integers={1,2,3,4,5};
                   for(int item:integers){                                
                   S.o.p(item);
                      }

    77)  What is an Annotation in JDK1.5?
           Sun has recently released Annotation Processing Tool (apt) along with beta2 of JDK1.5.
           This tool greatly helps in using the annotations feature that is introduced in JDK1.5
           Annotations can be at package level, class level, field level, method level and even at
            local variable level.

    78)  I have a HashMap. I want to get the keys & values in a set. Can you write the code?

     import java.util.*;
    class  keyvaluemap
    {
     public static void main(String[] args)
     {
      HashMap hm=new HashMap();
        hm.put(1,"ram");
            hm.put(2,"sri");
            System.out.println(hm);
    Set s=hm.entrySet();
    Iterator it=s.iterator();
    while(it.hasNext())
      {
     Map.Entry m1=(Map.Entry)it.next();
       System.out.println(m1.getKey()+"----"+m1.getValue());
      }
     }
    }

    79)  Which algorithm is used by JVM while running Garbage Collection?
                    Mark-in-sweep.

    80)   How do you Unit test in Spring environment?

    81)  How do you disable all the JavaScripts of pages in an application?
           
    82)    What does Tomcat Support?
              War file

    83)  In HashMap, how can I locate a particular key?
                Hm.containsKey(“3”);
               Hm.containsValue(“key”);

    84)  Difference b/w SVN(Sub VersioN) & VSS (Visual Source Safe--microsoft)?
    Usually team members do all of their work separately, in their own working copies and need to share their work. This is done via a Subversion repository. Syncro SVN Client supports the versions 1.3, 1.4, 1.5 and 1.6 of the SVN repository format
    1. Expansion. The number of programmers doubled and we didn't want to fork out for the extra VSS licenses
    2. Bugs. VSS is good at maintaining the latest version of a file, but histories often got corrupted.
    3. More bugs. The checking/recovery tools were useless as they started crashing when the database got very large.

    85)  ACID Operations
       Atomicity:
                             The process of combining invisible & individual operations into a single unit.

      Consistency:
           It is a process where the rules applied on DB  may be violated during Tx
           but no rule is violated at the end of a Tx.
       Ex: Account table—balance field –no  negative bal

    Isolation:
         The process of applying locks on a DB table at various levels to avoid data corruption
          when multiple users are allowed concurrently/simultaneously.

    Durability:
        The process of bringing the DB s/w original state using the log & back up files
        when it was crashed/corrupted.
           
    86)  Why there is Object class?
          To provides the default, common implemented code for every java class/interface.
    The Object Class is the super class for all classes in Java.

       Methods available in Object class are:
     int   hashCode(),
    boolean equals(Object obj),
    void finalize() throws Throwable,
    String toString(),
    Object clone() throws CloneNotSupportedException,
    final Class getClass()
    final void wait()throws InterruptedException
    final void notify()throws InterruptedException
    final void notifyAll()throws InterruptedException
    clone()

    An object is an instance of a class created using a new operator. The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation. An object encapsulates state and behavior.
    An object reference provides a handle to an object that is created and stored in memory. In Java, objects can only be manipulated via references, which can be stored in variables.
    Creating variables of your class type is similar to creating variables of primitive data types, such as integer or float. Each time you create an object, a new set of instance variables comes into existence which defines the characteristics of that object. If you want to create an object of the class and have the reference variable associated with this object, you must also allocate memory for the object by using the new operator. This process is called instantiating an object or creating an object instance.
    When you create a new object, you use the new operator to instantiate the object. The new operator returns the location of the object which you assign o a reference type.
    Below is an example showing the creation of Cube objects by using the new operator.
    public class Cube {

     int length = 10;
     int breadth = 10;
     int height = 10;
     public int getVolume() {
      return (length * breadth * height);
     }
     public static void main(String[] args) {
      Cube cubeObj; // Creates a Cube Reference
      cubeObj = new Cube(); // Creates an Object of Cube
      System.out.println("Volume of Cube is : " + cubeObj.getVolume());
     }
    }

    87)   Why hashcode(),equals()…are there in Object class?

    88)   What is the problem  with Autoboxing ?

    89)  What is an Nested class?
           The class defined in another class.
       
      Nested class Types:
        i)  static nested class
       ii) non-static nested class (inner class)

            Nested class Use   :
      i)   They can lead to more readable & maintainable code.
      ii)   It increases encapsulation.
     iii)   It is a way of  logically grouping classes that are only used in one place.

    Inner-class object creation:
                              OuterClass.InnerClass innerObject=outerObject.new InnerClass().

    Anonymous Class:  a name-less local class .

    When to use:
    i)  when a class has a short body.
    ii) only one instance of the class is needed.

    90) Inner classes in java
    Inner class means one class which is a member of another class. There are basically four types of inner classes in java.
    1) Nested Inner class
    2) Method Local inner classes
    3) Anonymous inner classes
    4) Static nested classes
    Nested Inner class can access any private instance variable of outer class. Like any other instance variable, we can have access modifier private, protected, public and default modifier.
    Like class, interface can also be nested and can have access specifiers.
    1)Following example demonstrates a nested class.
    class Outer {
       // Simple nested inner class
       class Inner {
          public void show() {
               System.out.println("In a nested class method");
          }
       }
    }
    class Main {
       public static void main(String[] args) {
           Outer.Inner in = new Outer().new Inner();
           in.show();
       }
    }
    Output:
    In a nested class method
    As a side note, we can’t have static method in a nested inner class because an inner class is implicitly associated with an object of its outer class so it cannot define any static method for itself. For example the following program doesn’t compile.
    class Outer {
       void outerMethod() {
          System.out.println("inside outerMethod");
       }
       class Inner {
          public static void main(String[] args){
             System.out.println("inside inner class Method");
          }
       }
    }
    Output:
    Error illegal static declaration in inner class
    Outer.Inner public static void main(String[] args)
    modifier ‘static’ is only allowed in constant
    variable declaration
    An interface can also be nested and nested interfaces have some interesting properties. We will be covering nested interfaces in the next post.

    2)Method Local inner classes
    Inner class can be declared within a method of an outer class. In the following example, Inner is an inner class in outerMethod().
    class Outer {
        void outerMethod() {
            System.out.println("inside outerMethod");
            // Inner class is local to outerMethod()
            class Inner {
                void innerMethod() {
                    System.out.println("inside innerMethod");
                }
            }
            Inner y = new Inner();
            y.innerMethod();
        }
    }
    class MethodDemo {
        public static void main(String[] args) {
            Outer x = new Outer();
            x.outerMethod();
        }
    }
    Output
    Inside outerMethod
    Inside innerMethod
    Method Local inner classes can’t use local variable of outer method until that local variable is not declared as final. For example, the following code generates compiler error (Note that x is not final in outerMethod() and innerMethod() tries to access it)

    class Outer {
       void outerMethod() {
          int x = 98;
          System.out.println("inside outerMethod");
          class Inner {
             void innerMethod() {
                System.out.println("x= "+x);
             }
          }
          Inner y = new Inner();
          y.innerMethod();
       }
    }
    class MethodLocalVariableDemo {
       public static void main(String[] args) {
          Outer x=new Outer();
          x.outerMethod();
       }
    }
    Output:
    local variable x is accessed from within inner class;
    needs to be declared final
    Note : Local inner class cannot access non-final local variable till JDK 1.7. Since JDK 1.8, it is
     possible to access the non-final local variable in method local inner class.
    But the following code compiles and runs fine (Note that x is final this time)
    class Outer {
       void outerMethod() {
          final int x=98;
          System.out.println("inside outerMethod");
          class Inner {
             void innerMethod() {
                System.out.println("x = "+x);
             }
          }
          Inner y = new Inner();
          y.innerMethod();
       }
    }
    class MethodLocalVariableDemo {
        public static void main(String[] args){
          Outer x = new Outer();
          x.outerMethod();
        }
    }
    Output-:
    Inside outerMethod
    X = 98
    The main reason we need to declare a local variable as a final is that local variable lives on stack till
    method is on the stack but there might be a case the object of inner class still lives on the heap.
    Method local inner class can’t be marked as private, protected, static and transient but can be marked
    as abstract and final, but not both at the same time.

    4)Static nested classes
    Static nested classes are not technically an inner class. They are like a static member of outer class.

    class Outer {
       private static void outerMethod() {
         System.out.println("inside outerMethod");
       }    
       // A static inner class
       static class Inner {
         public static void main(String[] args) {
            System.out.println("inside inner class Method");
            outerMethod();
         }
       }
    }
    Output:
    local variable x is accessed from within inner class;
    needs to be declared final
    Note : Local inner class cannot access non-final local variable till JDK 1.7. Since JDK 1.8, it is
     possible to access the non-final local variable in method local inner class.
    But the following code compiles and runs fine (Note that x is final this time)
    class Outer {
       void outerMethod() {
          final int x=98;
          System.out.println("inside outerMethod");
          class Inner {
             void innerMethod() {
                System.out.println("x = "+x);
             }
          }
          Inner y = new Inner();
          y.innerMethod();
       }
    }
    class MethodLocalVariableDemo {
        public static void main(String[] args){
          Outer x = new Outer();
          x.outerMethod();
        }
    }
    Output-:
    Inside outerMethod
    X = 98
    The main reason we need to declare a local variable as a final is that local variable lives on stack till
    method is on the stack but there might be a case the object of inner class still lives on the heap.
    Method local inner class can’t be marked as private, protected, static and transient but can be marked
     as abstract and final, but not both at the same time.

    4)Static nested classes
    Static nested classes are not technically an inner class. They are like a static member of outer class.
    class Outer {
       private static void outerMethod() {
         System.out.println("inside outerMethod");
       }    
       // A static inner class
       static class Inner {
         public static void main(String[] args) {
            System.out.println("inside inner class Method");
            outerMethod();
         }
       }
    }
    Output
    inside inner class Method
    inside outerMethod

    Anonymous inner classes
    Anonymous inner classes are declared without any name at all. They are created in two ways.
    a) As subclass of specified type
    class Demo {
       void show() {
          System.out.println("i am in show method of super class");
       }
    }
    class Flavor1Demo {
       //  An anonymous class with Demo as base class
       static Demo d = new Demo() {
           void show() {
               super.show();
               System.out.println("i am in Flavor1Demo class");
           }
       };
       public static void main(String[] args){
           d.show();
       }
    }
    Output
    i am in show method of super class
    i am in Flavor1Demo class
    In the above code, we have two class Demo and Flavor1Demo. Here demo act as super class and
    anonymous class acts as a subclass, both classes have a method show(). In anonymous class show()
     method is overridden.
    a) As implementer of the specified interface
    class Flavor2Demo {
        // An anonymous class that implements Hello interface
        static Hello h = new Hello() {
            public void show() {
                System.out.println("i am in anonymous class");
            }
        };
       public static void main(String[] args) {
            h.show();
        }
    }
      
    interface Hello {
        void show();
    }
    Output:
    i am in anonymous class
    In above code we create an object of anonymous inner class but this anonymous inner class is an implementer of the interface Hello. Any anonymous inner class can implement only one interface
    at one time. It can either extend a class or implement interface at a time.

    91)  What is Collection use?
              They allow to store heterogeneous objects.

    92)  How do you get key when value is available from HashMap?
                 HashMap<Integer,String> hm=new HashMap<Integer,String>();
                                                             hm.put(1,”ram”);
                                                            hm.put(2,”sri”);
                                                             hm.put(3,”mano”);
                   
                   Set<Entry<Integer,String>> set=hm.entrySet();
                     
                   for(Map.Entry<Integer,String> me:set){
                             if(me.getValue()==”ram”)
                             s.o.p(“the key value is:”+key):}
               OR                      
     Set s=hm.entrySet();  
      Iterator itr=s.iterator();
     
              while(itr.hasNext()){
     Object mobj=itr.next();

            Map.Entry me=(Map.Entry)mobj;

     if(me.getValue()=="anu")
     System.out.println("key is:"+me.getKey() );}

    93)   How to convert list into HashMap?


    94) Some important concepts:
    --------------------------------------------
    Introduction to Java Classes
    A class is nothing but a blueprint or a template for creating different objects which defines its
    properties and behaviors.
    Java class objects exhibit the properties and behaviors defined by its class.
    A class can contain fields and methods to describe the behavior of an object.
    Methods are nothing but members of a class that provide a service for an object or perform some
    business logic.
    Java fields and member functions names are case sensitive. Current states of a class’s
    corresponding object are stored in the object’s instance variables. Methods define the operations that
    can be performed in java programming.
    A class has the following general syntax:
    <class modifiers> class <class name>
    <extends clause> <implements clause>{
    // Dealing with Classes (Class body)
    <field declarations (Static and Non-Static)>
    <method declarations (Static and Non-Static)>
    <Inner class declarations>
    <nested interface declarations>
    <constructor declarations>
    <Static initializer blocks>
    }
    Below is an example showing the Objects and Classes of the Cube class that defines 3 fields namely
    length, breadth and height. Also the class contains a member function getVolume().

    public class Cube {
     int length;
     int breadth;
     int height;
     public int getVolume() {
      return (length * breadth * height);
     }
    }

    How do you reference a data member/function?
       This is accomplished by stating the name of the object reference, followed by a period (dot),
     followed by the name of the member inside the object.( objectReference.member ).
    You call a method for an object by naming the object followed by a period (dot), followed by the
     name of the method and its argument list, like this:
    objectName.methodName(arg1, arg2, arg3).
    For example:
    cubeObject.length = 4;
    cubeObject.breadth = 4;
    cubeObject.height = 4;
    cubeObject.getvolume()

    Class Variables /Static Fields
    We use class variables also know as Static fields when we want to share characteristics across all
    objects within a class. When you declare a field to be static, only a single instance of the associated
    variable is created common to all the objects of that class. Hence when one object changes the value
    of a class variable, it affects all objects of the class. We can access a class variable by using the name
     of the class, and not necessarily using a reference to an individual object within the class.
    Static variables can be accessed even though no objects of that class exist. It is declared using static
    keyword.

    Class Methods /Static Methods
    Class methods, similar to Class variables can be invoked without having an instance of the class.
    Class methods are often used to provide global functions for Java programs.
    For example, methods in the java.lang.Mathpackage are class methods. You cannot call non-static
    methods from inside a static method.

    Instance Variables
       Instance variables stores the state of the object. Each class would have its own copy of the variable.
     Every object has a state that is determined by the values stored in the object. An object is said to have changed its state when one or more data values stored in the object have been modified. When an
    object responds to a message, it will usually perform an action, change its state etc. An object that has
     the ability to store values is often said to have persistence.

    Consider this simple Java program showing the use of static fields and static methods
    // Class and Object initialization showing the Object Oriented concepts in Java

    class Cube {
     int length = 10;
     int breadth = 10;
     int height = 10;
     public static int numOfCubes = 0; // static variable
     public static int getNoOfCubes() { //static method
      return numOfCubes;
     }
     public Cube() {
      numOfCubes++; //
     }
    }

    public class CubeStaticTest {

     public static void main(String args[]) {
      System.out.println("Number of Cube objects = " + Cube.numOfCubes);
      System.out.println("Number of Cube objects = "
        + Cube.getNoOfCubes());
     }
    }
    Output
    Number of Cube objects = 0
    Number of Cube objects = 0

    Final Variable, Methods and Classes
    1) In Java we can mark fields, methods and classes as final. Once marked as final, these items cannot
     be changed.
    2) Variables defined in an interface are implicitly final. You can’t change value of a final variable (is a constant).
    3) A final class can’t be extended i.e., final class may not be subclassed. This is done for security
    reasons with basic classes like String and Integer. It also allows the compiler to make some
    optimizations, and makes thread safety a little easier to achieve.
    4) A final method can’t be overridden when its class is inherited. Any attempt to override or hide a
    final method will result in a compiler error.

    Method Overloading
    Method overloading results when two or more methods in the same class have the same name but
     different parameters. Methods with the same name must differ in their types or number of parameters.
     This allows the compiler to match parameters and choose the correct method when a number of
    choices exist. Changing just the return type is not enough to overload a method, and will be a compile
    -time error. They must have a different signature. When no method matching the input parameters is
    found, the compiler attempts to convert the input parameters to types of greater precision. A match
    may then be found without error. At compile time, the right implementation is chosen based on the
     signature of the method call
    Below is an example of a class demonstrating Method Overloading

    public class MethodOverloadDemo {

     void sumOfParams() { // First Version
      System.out.println("No parameters");
     }
     void sumOfParams(int a) { // Second Version
      System.out.println("One parameter: " + a);
     }
     int sumOfParams(int a, int b) { // Third Version
      System.out.println("Two parameters: " + a + " , " + b);
      return a + b;
     }
     double sumOfParams(double a, double b) { // Fourth Version
      System.out.println("Two double parameters: " + a + " , " + b);
      return a + b;
     }
     public static void main(String args[]) {
      MethodOverloadDemo moDemo = new MethodOverloadDemo();
      int intResult;
      double doubleResult;
      moDemo.sumOfParams();
      System.out.println();
      moDemo.sumOfParams(2);
      System.out.println();
      intResult = moDemo.sumOfParams(10, 20);
      System.out.println("Sum is  " + intResult);
      System.out.println();
      doubleResult = moDemo.sumOfParams(1.1, 2.2);
      System.out.println("Sum is  " + doubleResult);
      System.out.println();
     }
    }
    Output
    No parameters
    One parameter: 2
    Two parameters: 10 , 20
    Sum is 30
    Two double parameters: 1.1 , 2.2
    Sum is 3.3000000000000003
    Below is a code snippet to shows the interfaces that a Class Implements:
    Class cls = java.lang.String.class;
    Class[] intfs = cls.getInterfaces();
    // [java.lang.Comparable, java.lang.CharSequence, java.io.Serializable]
    // The interfaces for a primitive type is an empty array
    cls = int.class;
    intfs = cls.getInterfaces(); // []
    Below is a code snippet to show whether a Class Object Represents a Class or Interface:
    Class cls = java.lang.String.class;
    boolean isClass = !cls.isInterface(); // true
    cls = java.lang.Cloneable.class;
    isClass = !cls.isInterface(); // false

    95) Class loaders in Java

    Class loaders in Java are part of the Java Runtime Environment (JRE) and are responsible for dynamically loading classes into the Java Virtual Machine (JVM) during runtime.

    Thanks to class loaders:

    • Java applications can load classes on demand, rather than all at once.

    • The JVM remains platform-independent, as it doesn’t deal directly with files or file systems.


    🔰 Types of Built-in Class Loaders

    Java provides three main types of built-in class loaders:

    1. Bootstrap Class Loader

    • Loads: Core Java classes (e.g., java.lang.*, java.util.*)

    • Source: rt.jar or similar core library JARs (located in $JAVA_HOME/jre/lib)

    • Characteristics:

      • Part of the JVM, written in native code (not Java).

      • Has no parent, considered the root of the class loader hierarchy.

    2. Extension (Platform) Class Loader

    • Loads: Classes from the extension directory.

    • Source: JAR files from $JAVA_HOME/lib/ext or specified by the java.ext.dirs system property.

    • Parent: Bootstrap Class Loader

    3. System (Application) Class Loader

    • Loads: Classes from the application classpath.

    • Source: Directories and JARs specified by -cp or -classpath command-line options, or the CLASSPATH environment variable.

    • Parent: Extension Class Loader


    🧩 Class Loader Hierarchy

    Java follows a parent delegation model:

    Bootstrap ClassLoaderExtension ClassLoaderSystem (Application) ClassLoader

    Each class loader delegates the loading request to its parent before attempting to load the class itself. This helps:

    • Prevent multiple copies of core classes from being loaded.

    • Maintain security and consistency.


    ✅ Example:

    If you try to use java.lang.String, the class loading process is:

    1. System ClassLoader → delegates to

    2. Extension ClassLoader → delegates to

    3. Bootstrap ClassLoader → finds String.class in rt.jar

    🔧 What is a Custom Class Loader?

    A custom class loader allows you to override how and from where a Java class is loaded. Instead of loading classes from the default file system or classpath, you can load them:

    • From a database

    • Over a network

    • From encrypted JARs

    • Dynamically compiled source code


    🏗️ Creating a Custom Class Loader

    You can create a custom class loader by extending the java.lang.ClassLoader class and overriding the findClass() method.

    ✅ Minimal Example:

    import java.io.*;
    import java.nio.file.*; public class MyClassLoader extends ClassLoader { private String classPath; public MyClassLoader(String classPath) { this.classPath = classPath; } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { try { // Convert class name to file path String fileName = classPath + name.replace('.', '/') + ".class"; byte[] classBytes = Files.readAllBytes(Paths.get(fileName)); // Convert byte array to Class return defineClass(name, classBytes, 0, classBytes.length); } catch (IOException e) { throw new ClassNotFoundException("Could not load class " + name, e); } } }

    🧪 Using the Custom Class Loader

    public class TestCustomLoader {
    public static void main(String[] args) throws Exception { MyClassLoader loader = new MyClassLoader("C:/myclasses/"); Class<?> clazz = loader.loadClass("com.example.MyClass"); Object obj = clazz.getDeclaredConstructor().newInstance(); System.out.println("Class loaded: " + obj.getClass().getName()); } }

    ⚙️ Key Methods in ClassLoader

    MethodPurpose
    findClass(String name)Override this to define custom class loading logic.
    defineClass()Converts byte array into a Class object.
    loadClass()Main entry point, implements parent delegation (don’t override unless necessary).

    🔐 When to Use Custom Class Loaders

    ScenarioExample
    Hot deploymentLoad new versions of classes at runtime
    Modular pluginsEclipse, IntelliJ use custom loaders for each plugin
    Dynamic class generationHibernate, Spring create proxy classes at runtime
    SecurityLoad encrypted or obfuscated classes

    ⚠️ Important Notes

    • Always follow the parent delegation model, unless you have a specific reason not to.

    • Avoid breaking class compatibility (e.g., loading the same class from two class loaders will be treated as two different classes).

    • Use with caution: improper usage can lead to ClassCastException, LinkageError, or memory leaks (especially in web applications).


    96) Remove duplicates From List
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.List;

    public class RemDupFromList {
     public static void main(String[] args) {
      List li = new ArrayList();
      li.add("three");
      li.add("one");
      li.add("two");
      li.add("one");// Duplicate
      li.add("one");// Duplicate
      // We have facility to pass a List into Set constructor and vice verse to cast
      List li2 = new ArrayList(new HashSet(li)); // no order
      // List li2 = new ArrayList(new LinkedHashSet(li)); //If you need to preserve the order use 'LinkedHashSet'
      Iterator it = li2.iterator();
      while (it.hasNext()) {
       System.out.println(it.next());
      }
     }
    }

    97)Difference between Java Heap Space and Stack Memory
    1.       Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.
    2.       Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.
    3.       Objects stored in the heap are globally accessible whereas stack memory can’t be accessed by other threads.
    4.       Memory management in stack is done in LIFO manner whereas it’s more complex in Heap memory because it’s used globally. Heap memory is divided into Young-Generation, Old-Generation etc, more details at Java Garbage Collection.
    5.       Stack memory is short-lived whereas heap memory lives from the start till the end of application execution.
    6.       We can use -Xms and -Xmx JVM option to define the startup size and maximum size of heap memory. We can use -Xss to define the stack memory size.
    7.       When stack memory is full, Java runtime throws java.lang.StackOverFlowError whereas if heap memory is full, it throws java.lang.OutOfMemoryError: Java Heap Space error.
    8.       Stack memory size is very less when compared to Heap memory. Because of simplicity in memory allocation (LIFO), stack memory is very fast when compared to heap memory.
    =========
    Java memory model is divided between Thread Stacks (One for each thread) and a heap area.
    Thread Stack
    It is a thread specific memory area and contains local variables, methods call information etc. JVM stacks could be of fixed size or variable size. If computation in a thread exceeds its stack size limit then JVM throws StackOverflowError and exits.
    Heap
    It contains all the objects created during application lifecycle. The heap is created when the virtual machine starts up. Garbage collector reclaims heap storage for objects and objects are never explicitly deallocated. The JVM is not using any automatic storage management system, and it may vary as per the system requirements. The heap may be of a fixed size or may vary as per requirement. The memory for the heap does not need to be contiguous.

    Static variables are stored on heap area and object stored on the heap can be referred by references stored in thread stack.
    Local variables are stored on stack area.
    ====
    Memory that can be shared between threads is called shared memory or heap memory.
    All instance fields, static fields, and array elements are stored in heap memory.
    Local variables (§14.4), formal method parameters (§8.4.1), and exception handler parameters (§14.20) are never shared between threads and are unaffected by the memory model.

    ==========
    A local variable may be of a primitive type, in which case it is totally kept on the thread stack.
    A local variable may also be a reference to an object. In that case the reference (the local variable) is stored on the thread stack, but the object itself if stored on the heap.
    An object may contain methods and these methods may contain local variables. These local variables are also stored on the thread stack, even if the object the method belongs to is stored on the heap.
    An object's member variables are stored on the heap along with the object itself. That is true both when the member variable is of a primitive type, and if it is a reference to an object.
    Static class variables are also stored on the heap along with the class definition.
    Objects on the heap can be accessed by all threads that have a reference to the object. When a thread has access to an object, it can also get access to that object's member variables. If two threads call a method on the same object at the same time, they will both have access to the object's member variables, but each thread will have its own copy of the local variables.
    Here is a diagram illustrating the points above:

    98)The volatile keyword in Java
    volatile is used to indicate that a variable's value will be modified by different threads.
    Declaring a volatile Java variable means:
    The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory";
    Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.


                  Characteristic                    
              Synchronized
            Volatile
              Type of variable
                  Object
        Object or primitive
              Null allowed?
                  No
           Yes
              Can block?                   
                 Yes
             No
            All cached variables synchronized on access?
                Yes                    
    From Java 5 onwards
            When synchronization happens
           When you explicitly enter/exit a synchronized block
    Whenever a volatile variable is accessed.
     Can be used to combined several operations into an atomic operation?
                 Yes  
     Pre-Java 5, no. Atomic get-set of volatiles possible in Java 5.

    In other words, the main differences between synchronized and volatile are:
    a primitive variable may be declared volatile (whereas you can't synchronize on a primitive with synchronized);
    an access to a volatile variable never has the potential to block: we're only ever doing a simple read or write, so unlike a synchronized block we will never hold on to any lock;
    because accessing a volatile variable never holds a lock, it is not suitable for cases where we want to read-update-write as an atomic operation (unless we're prepared to "miss an update");
    a volatile variable that is an object reference may be null (because you're effectively synchronizing on the reference, not the actual object).
    Attempting to synchronize on a null object will throw a NullPointerException.

    99)ThreadPool in Java
    A thread pool is a group of threads initially created that waits for jobs and executes them. The idea is to have the threads always existing, so that we won't have to pay overhead time for creating them every time. They are appropriate when we know there's a stream of jobs to process, even though there could be some time when there are no jobs.
    There are various thread pools in java:
    1)Single Thread Executor : A thread pool with only one thread. So all the submitted tasks will be executed sequentially. Method : Executors.newSingleThreadExecutor()
    2)Cached Thread Pool : A thread pool that creates as many threads it needs to execute the task in parallel. The old available threads will be reused for the new tasks. If a thread is not used during 60 seconds, it will be terminated and removed from the pool. Method : Executors.newCachedThreadPool()
    3)Fixed Thread Pool : A thread pool with a fixed number of threads. If a thread is not available for the task, the task is put in queue waiting for an other task to ends. Method : Executors.newFixedThreadPool()
    4)Scheduled Thread Pool : A thread pool made to schedule future task. Method : Executors.newScheduledThreadPool()
    5)Single Thread Scheduled Pool : A thread pool with only one thread to schedule future task. Method : Executors.newSingleThreadScheduledExecutor()

    100)Why is Java not a pure OOP Language?
    Java is a OOP language and it is not a pure Object Based Programming Language. If any language is said to be pure Object Oriented Programming language, then that language can satisfy with seven qualities. These are :
    i)Abstraction
    ii)Encapsulation/Data Hiding
    iii)Inheritance
    iV)Polymorphism
    v)All predefined types are objects
    vi)All operations are performed by sending messages to objects
    vii)All user defined types are objects.
    1)Java is not pure OOP language because it supports Primitive data type such as int, byte, long... etc, to be used, which are not objects.
    Contrast with a pure OOP language like Smalltalk, where there are no primitive types, and boolean, int and methods are all objects.

    2)The static keyword:  When we declares a class as static then it can be used without the use of an object in Java. If we are using static function or static variable then we can’t call that function or variable by using dot(.) or class object defying object oriented feature.
    Wrapper Class: Wrapper class provides the mechanism to convert primitive into object and object into primitive. In Java, you can use Integer, Float etc. instead of int, float etc. We can communicate with objects without calling their methods. ex. using arithmetic operators.
    String s1 = "ABC" + "A" ;
    Even using Wrapper classes does not make Java a pure OOP language, as internally it will use the operations like Unboxing and Autoboxing. So if you create instead of int Integer and do any mathematical operation on it, under the hoods Java is going to use primitive type int only.

    public class BoxingExample 
    {
        public static void main(String[] args) 
        {
                Integer i = new Integer(10);
                Integer j = new Integer(20);
                Integer k = new Integer(i.intValue() + j.intValue());
                System.out.println("Output: "+ k);
        }
    }
    In the above code, there are 2 problems where Java fails to work as pure OOP:
    While creating Integer class you are using primitive type “int” i.e. numbers 10, 20.

    While doing addition Java is using primitive type “int”.

    101)   How are you using “Statement” like interface methods even without knowing their
              implementations classes in JDBC?
       The Statement interface provides a standard abstraction to execute SQL statements and return the
    results using the ResultSet objects.
      A Statement object contains a single ResultSet object at a time. The execute method of a Statement implicitly close its current ResultSet if it is already open. PreparedStatement and
    CallableStatement are two specialized Statement interfaces. You can create a Statement object by
    using the createStatement() method of the Connection interface as:

    Statement st = con.createStatement();
    //You can then execute the statement, get the ResultSet and iterate over it:
    ResultSet rs = st.executeQuery("select * from employeeList");
    while (rs.next()) {
      System.out.println(rs.getString("empname"));
    }
          
    102)  What is “IN”, “OUT”, “INOUT” parameters?
             in, out, inout are the modes of  the variables in PL/SQl.
            “ in” is input variable mode.
              “out” is output variable mode.
             “inout” is in-out variable mode.

    103) What classes are there in Spring Environment?
          Spring config.xml, SpringBean class, SpringBean interface(POJI interface) and POJO class.
    104)  When I don’t want to commit the ResultSet obj content, what to do?
             con.setAutoCommit(“false”);

    105)  What is the difference b/w “order by” and “group by”?
             “order by”--> used to arrange the data either in ascending or descending order.
            “group by”--> allows aggregation operations on a column .(having condition also).

    106)  What are the relations?
            One to one
            One to many
            Many to one
            Many to many.
    107)   What are the joins?
             Cursors, views, stored procedures….
    108)  Which tools do you used in design documents?

     109)  What is XML parser, SAX,   DOM parsers?

    110)  Differences b/w Statement and PreparedStatement apart from performance issue?
      Q:  What are Statements types?
       1) Statement: Statement is used to execute a “query” only for one time in the entire application 
    execution.
      2) PreparedStatement: PreparedStatement is used to execute same “query” for multiple no. of times
     with the same/different values. It works with compiled query & allows place holders.
      3) CallableStatement: It is used to execute PL/SQL Procedures/functions from the Java appl.
          
    111)  How do you configured Spring DAO?
            In contextApplication.xml

    112)  How to configure “counter” to know no. of  users visited the website?
    <%!
    int count=0;
    %>
    <%
    count++;
    %>
    <font color='green' size=8>
    The no of hits is:<%=count%>
    </font>

    113)  How to invoke stored procedures from a Java application?
              Using CallableStatement & prepareStatement();

    114)   What Design patterns do you know?
            MVC, Singleton class, Factory , FrontController, DAO class, D.T.O/V.O these are 
    design patterns I know
    115)   What is HB? What are its files.
             It is an ORM tool that is there to develop DB independent persistence logic.
             Hibernate-config.xml,   Hibernate-mapping.xml,  pojo class

    116)   How to integrate HB with Spring?
              The DAO implementation class of spring must extends HibernateDAOSupport and
                implements DAO interface.

    117)   How to integrate Struts with Spring?
             ContextLoaderServlet   and
              applicationContext.xml  configured in struts-config.xml that is there in web.xml

    118)   What are the differences b/w BeanFactory and ApplicationContext?

    BeanFactory (I)  container                        ApplicationContext (I)
    to develop spring core applications.        It is an advanced &  extended for BeanFactory.

    It gives full fledged spring features support like;
    i) Bean property values can be collected from
           “outside properties file”.
    ii) gives support for Pre-Initialization of  Beans.
    iii)  text messages can be collected from
          outside property files to give support for   i18n.
    iv)  allows to work with EventHandling through Listeners.

    119)  What are the SessionTracking Techniques?
           Session Tracking:   is a technique by which the client data can be remembered across
                                                  the multiple requests given by a client during a Session.
    1) Hidden Form Fields
    2) Http Cookies
    3) HttpSession with Cookies
    4) HttpSession with URL-rewriting.(best)

    120) How to handle multiple submit buttons in a HTML form?
           <input type=”submit”  name=”s1”  value=”add”> </th>
          <input type=”submit”  name=”s1”  value=”delete”> </th>
           <input type=”submit”  name=”s1”  value=”modify”> </th>
              
              Code for accessing the above data in Servlet.

              String cap=request.getParameter(“s1”);
      
         if(cap.equals(“add”)) {
                    ----------   }
              elseif(cap.equals(“delete”))  {
                   -------------  }
                   else(cap.equals(“modify”)) {
                        ------------   }

    121) What you write to open a window?  
    Window.open(); in Javascript
      
    <a href="javascript:;" onClick="mm_openbrwindow('Mypage.html','','width=800, height=600, scrollbars=no')">MyPage</a>

            newwindow=window.open(url,'name','height=500,width=400,left=100,
      top=100,resizable=yes,scrollbars=yes,toolbar=yes,status=yes');

    122)   Do you know CSS? What can I do with CSS?
    CSS is a style language that defines layout of HTML documents. For example, CSS covers fonts,
     colours, margins, lines, height, width, background images, advanced positions and many other things

    123)What is the difference between CSS and HTML?
    HTML is used to structure content. CSS is used for formatting structured content.

    124)  Code for DataSource?
             Context ct=new InitialContext();
                 Object obj=ct.lookUp(“ JNDI name of dataSource reference”);
                      DataSource ds=(DataSource)obj;
      Connecton con=ds.getConnection();
       Statement st=con.createStatement();
        --------------------
         con.close();

     125)  What is the return type of “executeUpdate()” ?
           It is used to execute “Non-Select queries” and
           whose return type is “int”.

    126)  What is “OUTER join”?
            Outer join supports 3types joins.These are
            i)left outer join
            ii)right outer join
            iii)full outer join
        
            It gives both matching and non-matching rows.

    127)  Why there are Directive and Action tags in JSP?

          Directive tags:    perform Global operations on a page like
              i)  importing packages,
             ii)  working with tag-library
            iii)  including other JSPs content and etc.,.
                    ex: page, include, taglib
           Action tags:
                     are there to perform actions during request-processing/execution phase of JSP.
            Ex:  include, forward,useBean, setProperty, getProperty, param, plugin.
    128)  What is Expression tag in JSP?
             It is used to
    i) evaluate a Java expression & sends that  result to Browser-window. <%=a+b;%>
    ii) display  the variable values on the Browser-window.  <% int a=10;%> <% =a %>
    iii) call both pre-defined & user-defined methods.
    <%=sum(10,20)%> , <%=”raja”.length()%>
    iv)  instantiates java classes & to display the default data of  the  object.
                        date and time is:<%=new java.util.Date();%>

    129)  What is Self Join? A table joins with itself.
    sum():   select sum(salarycolumn) from tablename group by salarycolumn;--groups the same 
                           salaries into different groups.
                         select sum(salarycolumn) from tablename;-à gives total sum of salary column

    130)  What is Setter and Constructor injection?
        Setter Injection:
              Setter Injection is a process of  injecting/assigning the dependent values to the Bean properties
              by the spring container using Bean class setXXX(-) methods.

        Note:  In Spring Config.xml:
              <property name=”age ”>
                  <value> 20</value>
               </property>
     Constructor Injection:
            Constructor Injection is a process of assigning/injecting the dependent values to the 
    Bean properties
             by the spring container using “parameterized Constructors”.
     Note:  In Spring config.xml:
       <constructor-arg>
            <value>ramu</value>
      </constructor-arg>

    131)  Can we use Setter Injection when we use private Constructor?
             No

    132)  What is “inverse=true” in hbm file?
               The Association is bi-directional.

    133)  How to establish many to many association?
            Declare one column as primary key in the Parent table.
            Declare  one column as primary key in the child table.
             Take another table where above two primary keys will be declared as foreign keys.

    134)    Can I develop a spring application without hbm file.
              Yes, by using “Annotation”

    135)    Can I develop a spring application without spring config.xml?
            Yes, by using Properties file.

    136)    What is distributed transaction?
              The transaction where two databases are used for a project.      

    137)    Differences b/w procedure & function?

              Procedure
                     Function
    1)  may or may not return value.
    2)  may returns one or many  
           values(max.1024)
    3)  result is gathered only through OUT  
          parameters.
    must returns a value.
     Must return exactly one value

    through OUT parameters & return value.

    138)  Difference b/w Primary and Unique key?
            Primary key:
                                     Only one Primary key constraint can be applied to a table.
                                     Primary key column won’t allow duplicates.
               Primary key column won’t allow NULL.

             Unique key:    one or many Unique key constraint can be applied to one table.
                                     It does n’t allows duplicates.
                                     It allows NULL(only one time).


     139) Explain Joins?
            Purpose : to bind data together,  across tables, without repeating all of the data in every table.
                                JOIN: Return rows when there is at least one match in both tables
    LEFT OUTER JOIN:   Return all rows from the left table, even if there are no matches in the 
    right table
    RIGHT OUTER JOIN: Return all rows from the right table, even if there are no matches in the 
    left table
    FULL OUTER JOIN:    Return rows when there is a match in one of the tables
                   SELF JOIN :

    EQUI/INNER JOIN:

    140)   How do you maintain bug tracking in your project?
               Using JIRA tool.
             JIRA is a Bug and Issue tracker.  It has been designed:
    • for Bug tracking
    • aid in Project Management
    • enable Agile Development
    There is a connection tool to Eclipse that allows you to manage tasks, issues, builds, and code reviews directly in your integrated development environment.

    JIRA is the project tracker for teams planning, building and launching great products.
    Thousands of teams choose JIRA to capture and organize issues, work through action items, and stay
     up-to-date with team activity.
      As your dev team grows, so should your bug tracker. With our simple importer, it's easier than ever 
    to get your issues into JIRA and watch your team destroy bugs with the fury of a thousand mutant 
    dinosaurs.
    Over 6,300 JIRA customers have gone Agile with GreenHopper.
    GreenHopper will make your Agile adoption successful with presets for Scrum and Kanban. 
    Turbocharge JIRA to improve visibility across teams and projects.
    Have trouble seeing the big picture? Or even the small picture? See clearly with JIRA 5.2.
    The completely re-imagined JIRA search experience lets you quickly find and organize your issues, 
    so you – and your team – can focus on what matters most. Getting the job done!
           
    141)   What tool are you using to write hundreds of fields for your project?

    142)   What code styles are you following in IDE?

    143)  Procedure to work with PreparedStatement in a Java application.
       
          1).  Prepare a query having “positional/place” holders/”in parameters”.ie.(?,?,?)
          2).  Send the query to DB s/w,  make the query as “pre-compiled query” & represent
               it through “PreparedStatement”.
         3).  Set the values for place-holders using “setXXX(-,-)”.
         4).  Execute the query.
         5).  To execute the same query for multiple no. of times  with same/different values,
                repeat steps 3 & 4 for multiple times.
         6).  Close PreparedStatement object.

         à Pre-compiled query:  a query that goes to DB & becomes
                                                      compiled-query without values, and also resides on DB.
                                                   It reduces “Network traffic”  b/w Java appl & DB s/w.

    144)  How to display data from the table in HB?
             SessionFactory sf = new Configuration().configure().buildSessionFactory();
            Session session = sf.openSession();
              Transaction t = session.beginTransaction();
      
    Student st = new Student();  //pojo
      
    //Displaying data from Student table using HQL
    Query qry = session.createQuery("from Student");
    List lt = qry.list();     // data saves into List with no restrictions
      
    //Restrcting data based on age condition
    Criteria ct = session.createCriteria(Student.class);
             ct.add(Restrictions.age("studentAge", 20));
      
     List lt = ct.list();
     Iterator<Student> itr = lt.iterator();  // displays all records
     System.out.println("Student no: \t Name : \t Age");

      while (itr.hasNext()) {
     Student student = itr.next();
         System.out.println(student.getStudentId()+"\t"+
         student.getStudentName()+"\t"+student.getStudentAge());
       
       }
         
    145)  How to insert one record into a Table (single row insertion)
     student.setStudentName("sridhar");
     student.setStudentAge(28);
     session.save(student);

    146)  How to update existing a table record?
     student.setStudentId(5);                   //primary key val
     student.setStudentName("sridhar");
     student.setStudentAge(28);
     session.saveOrUpdate(st);

    147)  How to delete a table record from HB session obj?
         session.load(student, new Integer(1)); // load(Student.class, primarykey)
         session.delete(student);

    148)  What are the Escape characters in JSP?

    149)   How many ways are there to invoke a Servlet object.

    150)   What is the difference b/w Filter and Servlet?

    151)   What is syntax for doFilter()?

    152)   Give me one example for Detached state of an object in HB?

    153)   What is the implementation class of  SessionFactory?
                LocalSessionFactoryBean

    154)   How do you configure one to many and many to many for an single Hb application?

    155)   What is Bi-directional and Uni-directional in HB?
                  inverse=”true”-àmeans bi-directional association.
                   Inverse=”false”àmeans uni -directional assoiciation

    156)  How to do Pagination?

    157)  Signature of “validate()”?
             Public ActionErrors validator(ActionMapping am, HttpServletRequest  req)
         
    158)  Write the code for CallableStatement?
    ------------------------------------------------------------------------
    how we do configure spring security in your project?
      <!-- Spring Security -->
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-core</artifactId>
                <version>${spring.security.core.version}</version>
                <type>jar</type>
                <!-- <scope>compile</scope> -->
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-web</artifactId>
                <version>${spring.security.core.version}</version>
                <type>jar</type>
                <!-- <scope>compile</scope> -->
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-config</artifactId>
                <version>${spring.security.core.version}</version>
                <type>jar</type>
                <!-- <scope>compile</scope> -->
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-taglibs</artifactId>
                <version>${spring.security.core.version}</version>
                <type>jar</type>
                <!-- <scope>compile</scope> -->
            </dependency>

    how we do configure spring with mongoDB in your project?
      <!-- Spring Data MongoDB -->
            <dependency>
                <groupId>org.springframework.data</groupId>
                <artifactId>spring-data-mongodb</artifactId>
                <version>${spring.data.mongodb.version}</version>
                <type>jar</type>
                <scope>compile</scope>
            </dependency>

            <!-- MongoDB Java Driver -->
            <dependency>
                <groupId>org.mongodb</groupId>
                <artifactId>mongo-java-driver</artifactId>
                <version>${mongodb.driver.version}</version>
                <type>jar</type>
                <scope>compile</scope>
            </dependency>

     how we do configure JUnit testing dependencies  in your project (Spring with maven)?
    <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
                <type>jar</type>
                <scope>test</scope>

            </dependency>

    how we do configure Java Mail API dependencies  in your project (Spring with maven)?
      <dependency>
                <groupId>javax.mail</groupId>
                <artifactId>mail</artifactId>
                <version>1.4.7</version>
            </dependency>

    how we do configure log4j dependencies  in your project (Spring with maven)?
    <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>${log4j.version}</version>
                <type>jar</type>
                <scope>compile</scope>
            </dependency>

     how we do configure RESTFul dependencies  in your project (Spring with maven)?
    <dependency>
                <groupId>javax.ws.rs</groupId>
                <artifactId>javax.ws.rs-api</artifactId>
                <version>2.0.1</version>
            </dependency>
    <dependency>

    how we do configure Rest-Assured dependencies  in your project (Spring with maven)?
    Rest-Assured is an open-source Java Domain-Specific Language (DSL).  DSL for simplifying testing
     of REST based services built on top of HTTP Builder. It supports POST, GET, PUT, DELETE, 
    OPTIONS, PATCH and HEAD requests and can be used to validate and verify the response of these
     requests.
    <dependency>
                <groupId>com.jayway.restassured</groupId>
                <artifactId>rest-assured</artifactId>
                <version>1.4</version>
            </dependency>

     how we do configure JSON dependencies  in your project (Spring with maven)?

    <!-- Data Mapper package is a high-performance data binding package built
            on Jackson JSON processor -->
            <dependency>
                <groupId>org.codehaus.jackson</groupId>
                <artifactId>jackson-mapper-asl</artifactId>
                <version>${jackson.version}</version>
                <type>jar</type>
                <scope>compile</scope>
            </dependency>

            <!-- Jackson is a high-performance JSON processor (parser, generator) -->
            <dependency>
                <groupId>org.codehaus.jackson</groupId>
                <artifactId>jackson-core-asl</artifactId>
                <version>${jackson.version}</version>
                <type>jar</type>
                <scope>compile</scope>
            </dependency>
           <dependency>
                <groupId>com.googlecode.json-simple</groupId>
                <artifactId>json-simple</artifactId>
                <version>1.1.1</version>
            </dependency>
           <dependency>
                <groupId>org.json</groupId>
               <artifactId>json</artifactId>
              <version>20160807</version>
          </dependency>

    how we do configure Spring-Boot dependencies  in your project (Spring with maven)?
                     <parent>
                                    <groupId>org.springframework.boot</groupId>
                                    <artifactId>spring-boot-starter-parent</artifactId>
                                    <version>1.5.8.RELEASE</version>
                                    <relativePath /> <!-- lookup parent from repository -->
                    </parent>
                                  <dependency>
                                                    <groupId>org.springframework.boot</groupId>
                                                    <artifactId>spring-boot-starter-mail</artifactId>
                                    </dependency>
                                    <dependency>
                                                    <groupId>org.springframework.boot</groupId>
                                                    <artifactId>spring-boot-starter-security</artifactId>
                                    </dependency>
                                    <dependency>
                                                    <groupId>org.springframework.boot</groupId>
                                                    <artifactId>spring-boot-starter-actuator</artifactId>
                                    </dependency>
                                    <dependency>
                                                    <groupId>org.springframework.boot</groupId>
                                                    <artifactId>spring-boot-starter-data-mongodb</artifactId>
                                    </dependency>
                                    <dependency>
                                                    <groupId>org.springframework.boot</groupId>
                                                    <artifactId>spring-boot-starter-data-redis</artifactId>
                                    </dependency>
                                    <dependency>
                                                    <groupId>org.springframework.boot</groupId>
                                                    <artifactId>spring-boot-starter-cache</artifactId>
                                    </dependency>
                                    <dependency>
                                                    <groupId>org.springframework.boot</groupId>
                                                    <artifactId>spring-boot-starter-web</artifactId>
                                    </dependency>
                                    <dependency>
                                                    <groupId>org.springframework.boot</groupId>
                                                    <artifactId>spring-boot-starter-test</artifactId>
                                                    <scope>test</scope>
                                    </dependency>
    ----------------------------------------------------------------------------------------

    159) REST Vs SOAP

    REST(REpresentational State Transfer)
    REST is an architectural style. It doesn’t define so many standards like SOAP.
    REST is for exposing Public APIs (i.e. Facebook API, Google Maps API) over the internet to handle
     CRUD operations on data.
    REST is focused on accessing named resources through a single consistent interface.

    SOAP (Simple Object Access Protocol)
    SOAP brings its own protocol and focuses on exposing pieces of application logic (not data) as
     services. SOAP exposes operations. SOAP is focused on accessing named operations, each operation implement some business logic. Though SOAP is commonly referred to as web services this is 
    misnomer. SOAP has a very little if anything to do with the Web. REST provides true Web services 
    based on URIs and HTTP.

    Why REST?
    1) Since REST uses standard HTTP it is much simpler in just about every way.
    2) REST is easier to implement, requires less bandwidth and resources.
    3) REST permits many different data formats whereas SOAP only permits XML.
    4) REST allows better support for browser clients due to its support for JSON.
    5) REST has better performance and scalability.
    6) REST reads can be cached, SOAP based reads cannot be cached.
    7) If security is not a major concern and we have limited resources. Or we want to create an API that 
    will be easily used by other developers publicly then we should go with REST.
    8) If we need Stateless CRUD operations then go with REST.
    9) REST is commonly used in social media, web chat, mobile services and Public APIs like Google 
    Maps.
    10) RESTful service return various MediaTypes for the same resource, depending on the 
    request header parameter "Accept" as application/xml or application/json for POST .
    11) REST services are meant to be called by the client-side application and not the end user directly.
    12) REST comes from State Transfer. You transfer the state around instead of having the server 
    store it, this makes REST services scalable.

    Why SOAP?
    1) SOAP is not very easy to implement and requires more bandwidth and resources.
    2) SOAP message request is processed slower as compared to REST and it does not use web caching mechanism.
    3) WS-Security: While SOAP supports SSL (just like REST) it also supports WS-Security which 
    adds some enterprise security features.
    4) WS-AtomicTransaction: Need ACID Transactions over a service, you’re going to need SOAP.
    5) WS-ReliableMessaging: If your application needs Asynchronous processing and a guaranteed leve
    l of reliability and security. Rest doesn’t have a standard messaging system and expects clients to
     deal with communication failures by retrying.
    6) If the security is a major concern and the resources are not limited then we should use SOAP 
    web services. Like if we are creating a web service for payment gateways, financial and 
    telecommunication related work then we should go with SOAP as here high security is needed.
    ====================================================================
    160)@Consumes and @Produces to Customize Requests and Responses

       The information sent to a resource and then passed back to the client is specified as a MIME 
    media type in the headers of an HTTP request or response. You can specify which MIME
     media types of representations a resource can respond to or produce by using the following 
    annotations:

    javax.ws.rs.Consumes
    javax.ws.rs.Produces
    By default, a resource class can respond to and produce all MIME media types of representations 
    specified in the HTTP request and response headers.

    The @Produces Annotation
    The @Produces annotation is used to specify the MIME media types or representations a resource can produce and send back to the client. If @Produces is applied at the class level, all the methods in a resource can produce the specified MIME types by default. If applied at the method level, the 
    annotation overrides any @Produces annotations applied at the class level.
    If no methods in a resource are able to produce the MIME type in a client request, the JAX-RS 
    runtime sends back an HTTP “406 Not Acceptable” error.
    The value of @Produces is an array of String of MIME types. For example:
    @Produces({"image/jpeg,image/png"})
    The following example shows how to apply @Produces at both the class and method levels:
    @Path("/myResource")
    @Produces("text/plain")
    public class SomeResource {
                    @GET
                    public String doGetAsPlainText() {
                                    ...
                    }

                    @GET
                    @Produces("text/html")
                    public String doGetAsHtml() {
                                    ...
                    }
    }
    The doGetAsPlainText method defaults to the MIME media type of the @Produces annotation at the
     class level. The doGetAsHtml method’s @Produces annotation overrides the class-level @Produces
     setting and specifies that the method can produce HTML rather than plain text.
    If a resource class is capable of producing more than one MIME media type, the resource method 
    chosen will correspond to the most acceptable media type as declared by the client. More specifically, the Accept header of the HTTP request declares what is most acceptable.
     For example, if the Accept header is Accept: text/plain, the doGetAsPlainText method will be 
    invoked. Alternatively, if the Accept header is Accept: text/plain;q=0.9, text/html, which declares
     that the client can accept media types of text/plain and text/html but prefers the latter, the doGetAsHtml method will be invoked.
    More than one media type may be declared in the same @Produces declaration. The following code 
    example shows how this is done:
    @Produces({"application/xml", "application/json"})
    public String doGetAsXmlOrJson() {
                    ...
    }
    The doGetAsXmlOrJson method will get invoked if either of the media types application/xml and application/json is acceptable. If both are equally acceptable, the former
     will be chosen because it occurs first. The preceding examples refer explicitly to MIME media types
     for clarity. It is possible to refer to constant values, which may reduce typographical errors. 

    The @Consumes Annotation
    The @Consumes annotation is used to specify which MIME media types of representations a resource can accept, or consume, from the client. If @Consumes is applied at the class level, all the response 
    methods accept the specified MIME types by default. If applied at the method level, @Consumes
     overrides any @Consumes annotations applied at the class level.
    If a resource is unable to consume the MIME type of a client request, the JAX-RS runtime sends back
     an HTTP 415 (“Unsupported Media Type”) error.
    The value of @Consumes is an array of String of acceptable MIME types. For example:
    @Consumes({"text/plain,text/html"})
    The following example shows how to apply @Consumes at both the class and method levels:
    @Path("/myResource")
    @Consumes("multipart/related")
    public class SomeResource {
                    @POST
                    public String doPost(MimeMultipart mimeMultipartData) {
                                    ...
                    }

                    @POST
                    @Consumes("application/x-www-form-urlencoded")
                    public String doPost2(FormURLEncodedProperties formData) {
                                    ...
                    }
    }
    The doPost method defaults to the MIME media type of the @Consumes annotation at the
    class level. The doPost2 method overrides the class level @Consumes annotation to specify that it
     can accept
     URL-encoded form data.
    If no resource methods can respond to the requested MIME type, an HTTP 415
    (“Unsupported Media 
    Type”) error is returned to the client.
    The HelloWorld example discussed previously in this section can be modified to set the message by using @Consumes, as shown in the following code example:
    @POST
    @Consumes("text/plain")
    public void postClichedMessage(String message) {
        // Store the message
    }

    In this example, the Java method will consume representations identified by the MIME media type 
    text/plain. Note that the resource method returns void. This means that no representation is returned
     and that a response with a status code of HTTP 204 (“No Content”) will be returned.
    161) Spring Features

    Spring is the most popular application development framework for enterprise Java. Millions of
     developers around the world use Spring Framework to create high performing, easily testable, and 
    reusable code.
    Spring framework is an open source Java platform. It was initially written by Rod Johnson and was 
    first released under the Apache 2.0 license in June 2003.
    Spring is lightweight when it comes to size and transparency. The basic version of Spring framework
     is around 2MB.
    The core features of the Spring Framework can be used in developing any Java application, but there 
    are extensions for building web applications on top of the Java EE platform. Spring framework targets
     to make J2EE development easier to use and promotes good programming practices by enabling a
     POJO-based programming model.

    162) Benefits of Using the Spring Framework

    Following is the list of few of the great benefits of using Spring Framework −
    1) Spring enables developers to develop enterprise-class applications using POJOs. The benefit of 
    using only POJOs is that you do not need an EJB container product such as an application server 
    but you have the option of using only a robust servlet container such as Tomcat or some commercial 
    product.
    2) Spring is organized in a modular fashion. Even though the number of packages and classes are
     substantial, you have to worry only about the ones you need and ignore the rest.
    3) Spring does not reinvent the wheel, instead it truly makes use of some of the existing technologies
     like several ORM frameworks, logging frameworks, JEE, Quartz and JDK timers, and other view technologies.
    4) Testing an application written with Spring is simple because environment-dependent code is
     moved into this framework. Furthermore, by using JavaBeanstyle POJOs, it becomes easier to use dependency injection for injecting test data.
    5) Spring's web framework is a well-designed web MVC framework, which provides a great 
    alternative to web frameworks such as Struts or other over-engineered or less popular web frameworks.
    6) Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.
    7) Spring has Lightweight IoC containers tend to be lightweight, especially when compared to EJB containers, for example. This is beneficial for developing and deploying applications on 
    computers with limited memory and CPU resources.
    8) Spring provides a consistent transaction management interface that can scale down to a local
     transaction (using a single database, for example) and scale up to global transactions (using JTA, for example).
    9) Dependency Injection (DI)
    The technology that Spring is most identified with is the Dependency Injection (DI) flavor of 
    Inversion of Control. The Inversion of Control (IoC) is a general concept, and it can be expressed 
    in many different ways. Dependency Injection is merely one concrete example of Inversion of 
    Control.
    When writing a complex Java application, application classes should be as independent as possible
     of other Java classes to increase the possibility to reuse these classes and to test them independently
     of other classes while unit testing.
    Dependency injection can happen in the way of passing parameters to the constructor or by 
    post-construction using setter methods. As Dependency Injection is the heart of Spring Framework,
     we will explain this concept in a separate chapter with relevant example.
    10) Aspect Oriented Programming (AOP)
    One of the key components of Spring is the Aspect Oriented Programming (AOP) framework. The
     functions that span multiple points of an application are called cross-cutting concerns and these 
    cross-cutting concerns are conceptually separate from the application's business logic. There are 
    various common good examples of aspects including logging, declarative transactions, security, 
    caching, etc.
    The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect.
     DI helps you decouple your application objects from each other, while AOP helps you decouple 
    cross-cutting concerns from the objects that they affect.
    The AOP module of Spring Framework provides an aspect-oriented programming implementation
     allowing you to define method-interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated.

    163) What is Spring Boot?
    Spring Boot is a Framework from “The Spring Team” to ease the bootstrapping and development of
     new Spring Applications.
    It provides defaults for code and annotation configuration to quick start new Spring projects within 
    no time. It follows “Opinionated Defaults Configuration” Approach to avoid lot of boilerplate code
     and configuration to improve Development, Unit Test and Integration Test Process.
    What is NOT Spring Boot?
    Spring Boot Framework is not implemented from the scratch by The Spring Team, rather than 
    implemented on top of existing Spring Framework (Spring IO Platform).
    It is not used for solving any new problems. It is used to solve same problems like Spring Framework.
    Why Spring Boot?
    To ease the Java-based applications Development, Unit Test and Integration Test Process.
    To reduce Development, Unit Test and Integration Test time by providing some defaults.
    To increase Productivity.
    Don’t worry about what is “Opinionated Defaults Configuration” Approach at this stage. We will 
    explain this in detail with some examples in coming posts.

    Advantages of Spring Boot:
    It is very easy to develop Spring Based applications with Java or Groovy.
    It reduces lots of development time and increases productivity.
    It avoids writing lots of boilerplate Code, Annotations and XML Configuration.
    It is very easy to integrate Spring Boot Application with its Spring Ecosystem like Spring JDBC, 
    Spring ORM, Spring Data, Spring Security etc.
    It follows “Opinionated Defaults Configuration” Approach to reduce Developer effort
    It provides Embedded HTTP servers like Tomcat, Jetty etc. to develop and test our web applications 
    very easily.
    It provides CLI (Command Line Interface) tool to develop and test Spring Boot(Java or Groovy) Applications from command prompt very easily and quickly.
    It provides lots of plugins to develop and test Spring Boot Applications very easily using 
    Build Tools like Maven and Gradle
    It provides lots of plugins to work with embedded and in-memory Databases very easily.
    Description: https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEixhbB1UWDw7716_22KehCAjfA7A6ePjEWShO-jKV0F1Rt-_m83VoUOGkP7UnFNL3nROS07GwpTqywbTf_y2WBL0npncAPcpIiRgouPFsSD61B7tqrm-j5jPXvXHmfMhaElaKRz4pdsVzSs/s320/WhatIsSpringBoot1-450x56.png

    164) Difference between Procedure and Function
                      Procedure
                                   Function
    1) Used mainly to a execute certain process. 
    2) Cannot call in SELECT statement.
      
    3 Use OUT parameter to return the value
    4) It is not mandatory to return the value.
    5) RETURN will simply exit the control from subprogram.
    6) Return datatype will not be specified at the time of creation. 
    1) Used mainly to perform some calculation.
    2) A Function that contains no DML statements
     can be called in SELECT statement.
    3) Use RETURN to return the value 
    4) It is mandatory to return the value.
    5) RETURN will exit the control from 
    subprogram and also returns the value.
    6) Return datatype is mandatory at the time .

    165)   Explain the JSP life-cycle methods?
    1. Page translation: The page is parsed & a Java file containing the corresponding servlet is
                                        created.
    2. Page compilation:   The Java file is compiled.
    3. Load class:         The compiled class is loaded.
    4 .Create instance:     An instance of the servlet is created.
    5. Call jspInit():       This method is called before any other
                                  method to allow initialization.
    6. Call _jspService(): This method is called for each request. (can’t be overridden)
    7. Call jspDestroy(): The container calls this when it decides take the instance out of service.
                              It is the last method called n the servlet instance.                
    166)   What are differences b/w Servlets & Jsp?
               Servlets:
      i)   Servlets  requires Recompilation and  Reloading when we do modifications in a Servlet.
    (some servers)
     ii)   Every Servlet must be configured in “web.xml”.
    iii)   Servlets is providing less amount of implicit objects support.
    iv)   Since it consists both HTML & bussiness logic hence modification in one logic may disturbs
           the other logic.
    v)    No implicit Exception Handling support.
    vi)   Since Servlets requires strong Java knowledge hence non-java programmers shows no interest.
    vii)  Keeping HTML code in Servlets is quite complex.

            JSP:
       i)   No need of Recompilation & Reloading when we do modifications in a JSP page.
      ii)   We need not to Configure a JSP in a “web.xml”.
     iii)   Jsp is providing huge amount of Implicit Objects support.
     iv)   Since Html & Java code are separated hence no disturbance while changing logic.
      v)   Jsp is providing implicit XML Exception Handling support.
     vi)   Jsp is easy to learn & implement since it is tags based.
    vii)   Jsp allows to develop custom tags.
    viii)  Jsp gives JSTL support.
     (JSP Standard Tag Library--> It provides more tags that will help to develop a JSP
                                                   without using Java code).
    ix)   Jsp gives all benefits of Servlets.

    167) What are the functions of service()?
         
    protected void service(HttpServletRequest request,HttpServletResponse response)
                                       throws ServletException, java.io.IOException
    Receives standard HTTP requests from the public service method and dispatches them to the doXXX methods defined in this class. This method is an HTTP-specific version of the

       public void service(ServletRequest req, ServletResponse res)
                                          throws ServletException, java.io.IOException
    Dispatches client requests to the protected service method.
        There's no need to override this method.

    168)  How do we get the container related information?
          By using “ServletContext” object. we can create ServletContext object in two ways.

    First way :

    public class TestServlet extends HttpServlet
    {
      public void service(HttpServletRequest req ,HttpServletResponse response) throws
     ServletException, IOException

         {
                      ServletConfig  cg=getServletConfig();
                      ServletContext sc=cg.getServletContext();
                       ====== usage of ServletContext object here ====
           }
    }



    Second way :


    public class TestServlet extends HttpServlet
    {
            public void service(HttpServletRequest request,HttpServletResponse response) throws    ServletException ,IOException
         {
                      ServletConfig  sc=getServletContext();
                          ====== usage of ServletContext object here ====
          }
     }
    169) What are the functions of a FilterServlet?
           FilterServlet traps all the requests & responses.
           Container creates the Filter object when the web application is deployed.
    170) Which JSP tag is  used to display error validation?
         In Source page:  
        <%@page  errorPage=”error-page-name.jsp”>
        In  Error page:
        <%@page  isErrorPage=”true”>
       


    171)  How to compile a JSP page?
       The maven jspc plugin ( http://mojo.codehaus.org/jspc-maven-plugin/ ) can be used to precompile 
    your jsps. It does this by compiling the jsps in a project and inserting servlet and servlet mapping
     entries into the final web.xml file, which gets packaged into the project's war  file.

    To use it, you need references to jspc-maven-plugin and maven-war-plugin in your project's pom.xml.
     The precompiling takes place during the "compile" phase of the maven build (default) lifecycle. 
    The jspc maven plugin writes the servlet and servlet mappings to a target/jspweb.xml file, and the
     maven war plugin copies this file and uses it in the war file that it builds.

                                               <!-- begin - precompiling jsps -->
                                                    <plugin>
                                                                    <groupId>org.codehaus.mojo</groupId>
                                                                    <artifactId>jspc-maven-plugin</artifactId>
                                                                    <executions>
                                                                                    <execution>
                                                                                                    <id>jspc</id>
                                                                                                    <goals>
                                                                                                                    <goal>compile</goal>
                                                                                                    </goals>
                                                                                    </execution>
                                                                    </executions>
                                                    </plugin>
                                                    <plugin>
                                                                    <groupId>org.apache.maven.plugins</groupId>
                                                                    <artifactId>maven-war-plugin</artifactId>
                                                                    <configuration>
                                                                   <webXml>${basedir}/target/jspweb.xml</webXml>                                                                               </configuration>
                                                    </plugin>
                                                    <!-- end - precompiling jsps -->
    172) How do you forward Servlet1 request to Servlet2?
           ServletContext sc=getServletContext();
              RequestDispatcher rd =sc.getRequestDispatcher(“/s2url”);  //” or html file name”
               rd.forward(req,resp);   (or) rd.include(req,resp);
    173)   How do you make the variables applicable to the whole application in JSP?
         
             JSP declarations are used to declare class variables and methods (both instance and static) in a JSP page. These  declations will be placed directly at class level in the generated servlet and these are available to the entire JSP.
    174)    What are ServletListeners?
         
    Source obj
    Event
    Listener
    EventHandling methods (public void 
    ServletRequest


    ServletContext


    HttpSession
    ServletRequestEvent(sre)


    ServletContextEvent(sce)


    HttpSessionEvent (hse)
    ServletRequestListener


    ServletContextListener


    HttpSessionListener
    requestInitialized(sre)
    requestDestroyed(sre)

    contextInitialized(sce)
    contextDestroyed(sce)

    sessionCreated(hse)
    sessionDestroyed(hse)
           
      From  Servlet 2.4 onwards,  EventHandling is allowed on special objects of  webapplication
              like  ServletContext, ServletRequest, HttpSession objects.
                           
               ServletRequest: 
                       By doing EventHandling on ServletRequest object, we can keep track of
                          each  “request” object creation time & destruction time.   Based on this, we can
                       find out “request processing time”.
                  
                HttpSession:
                        By performing EventHandling on HttpSession object, we can find out
                           “session” object creation time & destruction time.   Based on this, we can
                        know the time taken by the each  user to work with “session”.

                Procedure to configure Listeners with webapplication
                  
                    1)    Develop a Java class implementing appropriate “Listener”
                            & place it in WEB-INF/classes folder.

                    2)    Configure that Listener class name in web.xml by using <listener-class>
    175)   What is a Session?
           Session:  It is a set of  related & continuous  requests given by a client to a web application.
                            Ex:  SignIn to SignOut in any Mail Systems Application like Gmail, Ymail etc…

    176)   How do you maintain client data at client side?
                Cookies
    177)    Difference b/w GET and POST methods?
                    
                GET
    POST
    1) It is a default Http request method

    2)  Query string is visible in Browser
        address bar hence no data Secrecy.

    3) It allows to send limited amount of  
          data(1kb)

    4)   It is not suitable for File uploading.

    5)  It is not suitable for sending  Enscripted  data.

    6) It  shows Idempotent behaviour.

    7) Use either doGet(-,-) or service(-,-)
        to process this.
        Not a default method.

        It gives data Secrecy.


       Unlimited amount of data.


        Suitable for File uploading.

         Suitable.


        Non-Idempotent.

       Use either doPost(-,-) or service(-,-)    
    178)   What is Idempotent behavior?
               It is the behavior like processing  the multiple same requests from the same web page.

    179)  How the POST is not having Idempotent behavoiur?
    180)   What are the different Scopes in JSP?
              request, page, session, application

    181)   How to disable “Cache” ?
          <% resp.setHeader(“cache-control”, ”no-cache”);%>
                                   
         (<meta http-equiv=”cache-control” content=”no-cache”>

                 <%resp.setHeader(“pragma”,”no-cache”);%> //http1.0
                                   OR
               <meta http-equiv=”pragma” content=”no-cache”>)

    182)  What is default Scope in JSP?
                page
    183)  How to configure a JavaBean in JSP?
                 <jsp:useBean>

    184)   How the JSP code is converting into Servlet code?
              JSP parser/Engine/compiler
     185)  What is “useBean”?
                JSP standard tag to configure a Java Bean in JSP.

    186)  What is Servlet Chaining?
           Servlet Chaining is a method of processing the request using multiple servlets as a chain.
    187)   What is Servlet life-cycle?
    1. If an instance of the servlet does not exist, the Web container
    a. Loads the servlet class.
    b. Creates an instance of the servlet class.
    c. Initializes the servlet instance by calling the init method.
         2.  Invokes the service method, passing a request and response object.
         3.  If the container needs to remove the servlet, it finalizes the servlet by calling
               the servlet's  destroy method.

     188)  What are the differences b/w Servlet and JSP?
           For every time we modifing the servlet , we should re-deploy the servlet.
            Its very big  headache.
           Manually written servlets are somewhat faster than JSPs.
              JSP:
       i)   No need of Recompilation & Reloading when we do modifications in a JSP page.
      ii)   We need not to Configure a JSP in a “web.xml”.
     iii)   It is providing huge amount of Implicit Objects support.
     iv)   Since Html & Java code are separated hence no disturbance while changing logic.
      v)   It is providing implicit XML Exception Handling support.

     189)   What is “isThreadSafe=true” in JSP?
             It makes the equivalent servlet as thread safe.
             The “JSP equivalent Servlet”  will implement SingleTreadModel(I) implicitely.
    190)   What is custom Servlet?
                 The servlet that extending pre-defined Servlet (ie HttpServlet/GenericServlet/Servlet)
    191) What Is a Custom Tag?
    A custom tag is a user-defined JSP language element. When a JSP page containing a custom tag
     is translated into a servlet, the tag is converted to operations on a tag handler. The web container
     then invokes those operations when the JSP page’s servlet is executed.
    Custom tags have a rich set of features. They can
    • Be customized by means of attributes passed from the calling page.
    • Pass variables back to the calling page.
    • Access all the objects available to JSP pages.
    • Communicate with each other. You can create and initialize a JavaBeans component, create a public EL(Expression Language) variable that refers to that bean in one tag, and then use the bean in 
    another tag.
    • Be nested within one another and communicate by means of private variables.
       Table 9-2 Tag Handler Methods
    Tag Type
    Interface
    Methods
    Basic
    Tag
    doStartTag, doEndTag
    Attributes
    Tag
    doStartTag, doEndTag, setAttribute1,...,N, release
    Body
    Tag
    doStartTag, doEndTag, release
    Body, iterative evaluation
    IterationTag
    doStartTag, doAfterBody, doEndTag, release
    Body, manipulation
    BodyTag
    doStartTag, doEndTag, release, doInitBody, doAfterBody
    192) Is the Servlet thread-Safe by default?
            No,  the servlet by default  is not Thread safe. To achieve this, the servlet must implements
                    SingleThreadModel interface OR synchronize the service().
    193) Which JSP methods can be overridden?
              jspInit() & jspDestroy().

    194) What are the common files when 5 or more projects are developed using  Hibernate ?
           Hibernate-configuration file
    195)  Can I call a procedure from a HB? How?
      Yes.
    1)In hibernate main file, we have to set getNamedQuery("-") after openSession() method.
     Query query = session.getNamedQuery("callStockStoreProcedure");
     query .setParameter("stockCode", "7277");
    List result = query.list();
    for(int i=0; i<result.size(); i++){
        Stock stock = (Stock)result.get(i);
        System.out.println(stock.getStockCode());
    }
    2) In hibernate mapping file we have to set <sql-query> after </class>

    <sql-query name="callStockStoreProcedure" callable="true">
        <return alias="emp" class="Stock "/>
        { call get_stockdetails() }
    </sql-query>

    196)   Can I use a big query in HB?
     Yes.

    197)   Tell me few Hibernate interfaces?
                   i) Configuration(c),
                  ii) SessionFactory,
                 iii) Session,
                 iv) Transaction,
                  v) Query
    198) How do you create “Criteria”?(to do select operations.)
         
             Criteria criteria=session.createCriteria(EmpBean.class);
                     
       // select * from Employee where eid between 100 and 200 and firstname in (“raja”,”ramana”));
         
                   Condition: 1
           criteria=criteria.add(Expression.between(“no”,new Integer(100)),new Integer(200));
               
                  Condition: 2
           criteria=criteria.add(Expression.in(“fname”,new String []{“raja”,”ramana”} )));
             
                            List l=ct.list();                // retrieves more selected records
                for(int x=0;x<l.size();x++){
                  EmpBean emp=(EmpBean) l.get(x);
                                   
         S.o.p(emp.getNo()+”\t”+emp.getFname()+”\t”+emp.getLname()+”\t”+emp.getEmail());
               
     199)   What is Hibernate configuration file?
              HB dialect, DB  Driver class, Driver class URL, Username, Password.
         
    200)  Why the people using frameworks?

    201)   What is POJO & POJI model programming?
             The programming with no api dependent classes/interfaces

    202)    What is “Caching “ mechanism?
       Hibernate has caching mechanism.It means
             To minimize n/w round trips.
                 “Session” is default and
                  “SessionFactory’ explicitly configured.

    203)  Do you know “restriction” and “expression”?
            Expression.between()
                 Expression.in()
    204)   What is Java?
             Java is a high-level, object - oriented, platform independent programming language designed for developing
    wide range of applications such as web applications, mobile applications, enterprise applications, desktop applications.
      It was introduced by sun microsystems in 1995 (now owned by Oracle)
      Jave uses a combination of compiler & interpreter to convert code into byte code which can run on any
    device with a Java Virtual Machine (JVM), making it as high portable.

    205)   How do you configure “one to many” association in Hibernate?
             
    Example:
      ==========
    Step1) In Parent POJO class,we need a collection property for representing/storing a group of 
    child objects associated.

    //User.java (Parent POJO class)

    import java.util.*;

    public class User {

    private long userId ;
    private String firstName ;
    private Set phones; // phones is a collection property

         // wrtie setXxx(-), getXxx() methods
      public String getFirstName() {
       return firstName;
      }
      public void setFirstName(String firstName) {
        this.firstName = firstName;
      }
      public long getUserId() {
       return userId;
      }
      public void setUserId(long userId) {
       this.userId = userId;
      }

      public  Set getPhones() {
       return phones;
      }
      public void setPhones(Set phones) {
       this.phones=phones;
      }
    }//class

    //PhoneNumber.java (Child POJO class)

    public class PhoneNumber
    {
    private String numberType;
    private long phone ;
    private long id;

            // write setXxx(-) and getXxx() methods
    }

    Step 2) In the Parent class mapping the collection property with the collection element
    (i.e., set,list,map)


    <?xml version="1.0"?>
      <!DOCTYPE hibernate-mapping PUBLIC
      "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
      "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

      <hibernate-mapping>
          <class name="User" table="USER_TABLE" >

              <id name="userId" column="USER_ID"/>
              <property name="firstName"  column="FIRST_NAME"/>

              <set name="phones"   table="PHONE_NUMBERS" cascade="all" lazy="true">
                                  //set ---àcollecton element
                <key column="UNID"/>        //UNID -àforeign key
                <one-to-many class="PhoneNumber"  />
             </set>
          </class>
      </hibernate-mapping>

    Step 3)In main java file
         i)add the group of child objects to the collection object
                              Set s=new HashSet();  //s--àcollection object
            s.add(ph1);
            s.add(ph2);
         ii)Add the collection object to parent object
             
             u1.setPhones(s); //u1 --àparent object

    For complete main java file code
     ==============================
    //TestClient (ClentApp)
    import org.hibernate.*;
    import org.hibernate.cfg.*;
    import java.util.*;

    public class TestClient {

    public static void main(String[] args)
    {
     try
     {
                  Session ses=new Configuration().configure().buildSessionFactory().openSession();

        Transaction tx = ses.beginTransaction();

        User u1=new User();
        u1.setUserId(105);
       u1.setFirstName("raja1");
               
                 PhoneNumber ph1=new PhoneNumber();
           ph1.setNumberType("residence");
           ph1.setPhone(65538968);

           PhoneNumber ph2=new PhoneNumber();
           ph2.setNumberType("office");
           ph2.setPhone(65538958);

           Set s=new HashSet();
            s.add(ph1);
            s.add(ph2);
                        // setting  PhoneNumber class objs to phones property of User obj
                 u1.setPhones(s);

          //To Insert record
          ses.save(u1);         
          tx.commit();
          ses.close();
      
       }//try
      catch(Exception e)
          {
      e.printStackTrace();
      }
      }//main

    }//class
    206)  What are the uses with Hibernate?
            i) It allows to develop DB independent query language like HQL.
           ii) It supports POJO/POJI model programming.
          iii) Any Java/J2EE can access HB persistence logic.
          iv) It supports to call all Procedures & Functions of PL/SQL programming.
           v)  The result after “SELECT”  operation, by default, is “Serializable”.

         
    207)  How to connect with DB?
           Class.forName(“oracle.jdbc.driver.OracleDriver”);
               Connection con=DriverManager.getConnection(“jdbc:oracle:thin:@<IPadress>:1521”,
                                                                                           ”orcl”,”scott”,”tiger”);
                 Statement st=con.createStatement();
                  // ResultSet rs=st.execute(“select query”);  (or)
                      //   int x=st.executeUpdate(“Non-select query”);
    208)   What is dialect?
             Using dialect, Hibernate knows the type of DB & its version to which it will connected.

    209)  How do you map HB Pojo class with Table?
           
         <hibernate-mapping default-cascade="none" default-access="property" default-lazy="true"
           auto-import="true">
        <class name="CustomerOrder" table="CustomerOrder" mutable="true" polymorphism="implicit" dynamic-update="false" dynamic-insert="false" select-before-update="false" 
    optimistic-lock="version">
    <composite-id name="orderId" class="OrderId" mapped="false" unsaved-value="undefined">
        <key-property name="customerId" column="customer_id" />
      <key-property name="orderTime" column="order_time" />
      </composite-id>
      <property name="orderDescription" unique="false" optimistic-lock="true" lazy="false" 
    generated="never" />
      </class>

      </hibernate-mapping>

    210)Spring annotations:

    For spring to process annotations, add the following lines in your application-context.xml file.<context:annotation-config />
    <context:component-scan base-package="...specify your package name..." />

    @Service

    Annotate all your service classes with @Service. All your business logic should be in Service classes.
    @Service
    public class CompanyServiceImpl implements CompanyService {
    ...
    }
    

    @Repository

    Annotate all your DAO classes with @Repository. All your database access logic should be in DAO classes.
    @Repository
    public class CompanyDAOImpl implements CompanyDAO {
    ...
    }
    

    @Component

    Annotate your other components (for example REST resource classes) with @Component.
    @Component
    public class ContactResource {
    ......
    }
    
    @Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases, for example, in the persistence, service, and presentation layers, respectively.

    @Component
    Other class-level annotations may be considered as identifying a component as well, typically a special kind of component: e.g. the @Repository annotation or AspectJ's @Aspect annotation.

    211)org.springframework.context.annotation.ComponentScan

    Configures component scanning directives for use with @Configuration classes. Provides support parallel with Spring XML's <context:component-scan> element.

    Either basePackageClasses or basePackages (or its alias value) may be specified to define specific packages to scan. If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.

    Note that the <context:component-scan> element has an annotation-config attribute; however, this annotation does not. This is because in almost all cases when using @ComponentScan, default annotation config processing (e.g. processing @Autowired and friends) is assumed. Furthermore, when using AnnotationConfigApplicationContext, annotation config processors are always registered, meaning that any attempt to disable them at the @ComponentScan level would be ignored. 

    212)org.springframework.context.annotation.Scope

    When used as a type-level annotation in conjunction with @Component, @Scope indicates the name of a scope to use for instances of the annotated type.

    When used as a method-level annotation in conjunction with @Bean, @Scope indicates the name of a scope to use for the instance returned from the method.

    NOTE: @Scope annotations are only introspected on the concrete bean class (for annotated components) or the factory method (for @Bean methods). In contrast to XML bean definitions, there is no notion of bean definition inheritance, and inheritance hierarchies at the class level are irrelevant for metadata purposes.

    In this context, scope means the lifecycle of an instance, such as singleton, prototype, and so forth. Scopes provided out of the box in Spring may be referred to using the SCOPE_* constants available in the ConfigurableBeanFactory and WebApplicationContext interfaces.

    @Scope is a Spring-managed components in general, the default and most common scope for autodetected components is singleton. To change this default behavior, use @Scope spring annotation.

    @Component
    @Scope("request")
    public class ContactResource {
    ...
    }
    
    
    Similarly, you can annotate your component with @Scope("prototype") for beans with prototype scopes.

    To register additional custom scopes, see CustomScopeConfigurer.

    213)Spring MVC Annotations

    @Controller

    Annotate your controller classes with @Controller.

    @Controller
    public class CompanyController {
    ...
    }
    

    @RequestMapping

    @RequestMapping spring annotation is used to map URLs onto an entire class or a particular handler method. Typically the class-level annotation maps a specific request path (or path pattern) onto a form controller, with additional method-level annotations narrowing the primary mapping.

    org.springframework.web.bind.annotation.RequestMapping

    @Target(value={METHOD, TYPE})

    Annotation for mapping web requests onto methods in request-handling classes with flexible method signatures.

    Both Spring MVC and Spring WebFlux support this annotation through a RequestMappingHandlerMapping and RequestMappingHandlerAdapter in their respective modules and package structure. For the exact list of supported handler method arguments and return types in each, please use the reference documentation links below:

    @Controller
    @RequestMapping("/company")
    public class CompanyController {
    
      @Autowired
      private CompanyService companyService;
    ...
    }
    

    @PathVariable

    @PathVariable spring annotation is used on a method argument to bind it to the value of a URI template variable. In our example below, a request path of /company/sample will bind companyName variable with 'sample' value.

    @Controller
    @RequestMapping("/company")
    public class CompanyController {
    
      @Autowired
      private CompanyService companyService;
    
      @RequestMapping("{companyName}")
      public String getCompany(Map<String, Object> map, 
      			@PathVariable String companyName) {
        Company company = companyService.findByName(companyName);
        map.put("company", company);
        return "company";
      }
    ...
    }
    

    @RequestParam

    @RequestParam annotation is used to bind request parameters to method variables.

    @Controller
    @RequestMapping("/company")
    public class CompanyController {
    
      @Autowired
      private CompanyService companyService;
    
      @RequestMapping("/companyList")
      public String listCompanies(Map<String, Object> map, 
      			@RequestParam int pageNum) {
        map.put("pageNum", pageNum);
        map.put("companyList", companyService.listCompanies(pageNum));
        return "companyList";
      }
    ...
    }
    

    Similarly, you can use spring annotation @RequestHeader to bind request headers.

    @ModelAttribute

    An @ModelAttribute on a method argument indicates the argument should be retrieved from the model. If not present in the model, the argument should be instantiated first and then added to the model. Once present in the model, the argument's fields should be populated from all request parameters that have matching names. This is known as data binding in Spring MVC, a very useful mechanism that saves you from having to parse each form field individually.

    @Controller
    @RequestMapping("/company")
    public class CompanyController {
    
      @Autowired
      private CompanyService companyService;
    
      @RequestMapping("/add")
      public String saveNewCompany(@ModelAttribute Company company) {
        companyService.add(company);
        return "redirect:" + company.getName();
      }
    ...
    }
    

    @SessionAttributes

    @SessionAttributes spring annotation declares session attributes. This will typically list the names of model attributes which should be transparently stored in the session, serving as form-backing beans between subsequent requests.

    @Controller
    @RequestMapping("/company")
    @SessionAttributes("company")
    public class CompanyController {
    
      @Autowired
      private CompanyService companyService;
    ...
    }
    

    @SessionAttribute works as follows:

    • @SessionAttribute is initialized when you put the corresponding attribute into model (either explicitly or using @ModelAttribute-annotated method).
    • @SessionAttribute is updated by the data from HTTP parameters when controller method with the corresponding model attribute in its signature is invoked.
    • @SessionAttributes are cleared when you call setComplete() on SessionStatus object passed into controller method as an argument.

    The following listing illustrate these concepts. It is also an example for pre-populating Model objects.

    @Controller
    @RequestMapping("/owners/{ownerId}/pets/{petId}/edit")
    @SessionAttributes("pet")
    public class EditPetForm {
    
    	@ModelAttribute("types")
    	
    	public Collection<PetType> populatePetTypes() {
    		return this.clinic.getPetTypes();
    	}
    	
    	@RequestMapping(method = RequestMethod.POST)
    	public String processSubmit(@ModelAttribute("pet") Pet pet, 
    			BindingResult result, SessionStatus status) {
    		new PetValidator().validate(pet, result);
    		if (result.hasErrors()) {
    			return "petForm";
    		}else {
    			this.clinic.storePet(pet);
    			status.setComplete();
    			return "redirect:owner.do?ownerId=" 
    				+ pet.getOwner().getId();
    		}
    	}
    }
    

    Spring Security Annotations

    @PreAuthorize

    @PreAuthorize annotation is used to authorize or deny a functionality in Spring Security . In our example below, only a user with Admin role has the access to delete a contact.

      @Transactional
      @PreAuthorize("hasRole('ROLE_ADMIN')")
      public void removeContact(Integer id) {
        contactDAO.removeContact(id);
      }
    

    A convenience annotation that is itself annotated with @Controller and @ResponseBody.

    Types that carry this annotation are treated as controllers where @RequestMapping methods assume @ResponseBody semantics by default.

    NOTE: @RestController is processed if an appropriate HandlerMapping-HandlerAdapter pair is configured such as the RequestMappingHandlerMapping-RequestMappingHandlerAdapter pair which are the default in the MVC Java config and the MVC namespace.

    216)org.springframework.stereotype.Controller

    Indicates that an annotated class is a "Controller" (e.g. a web controller).

    This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning. It is typically used in combination with annotated handler methods based on the org.springframework.web.bind.annotation.RequestMapping annotation.

    217)org.springframework.boot.autoconfigure.SpringBootApplication

    Indicates a configuration class that declares one or more @Bean methods and also triggers auto-configuration and component scanning. It's a combination of three annotations: 
    @Configuration, @EnableAutoConfiguration and @ComponentScan.

    218)org.springframework.boot.autoconfigure.domain.EntityScan

    Configures the base packages used by auto-configuration when scanning for entity classes.

    Using @EntityScan will cause auto-configuration to:

    One of basePackageClasses(), basePackages() or its alias value() may be specified to define specific packages to scan. If specific packages are not defined scanning will occur from the package of the class with this annotation.

    219)org.springframework.boot.autoconfigure.EnableAutoConfiguration

    Enable auto-configuration of the Spring Application Context, attempting to guess and configure beans that you are likely to need. Auto-configuration classes are usually applied based on your classpath and what beans you have defined. For example, if you have tomcat-embedded.jar on your classpath you are likely to want a TomcatServletWebServerFactory (unless you have defined your own ServletWebServerFactory bean).

    When using SpringBootApplication, the auto-configuration of the context is automatically enabled and adding this annotation has therefore no additional effect.

    Auto-configuration tries to be as intelligent as possible and will back-away as you define more of your own configuration. You can always manually exclude() any configuration that you never want to apply (use excludeName() if you don't have access to them). You can also exclude them via the spring.autoconfigure.exclude property. Auto-configuration is always applied after user-defined beans have been registered.

    The package of the class that is annotated with @EnableAutoConfiguration, usually via @SpringBootApplication, has specific significance and is often used as a 'default'. For example, it will be used when scanning for @Entity classes. It is generally recommended that you place @EnableAutoConfiguration (if you're not using @SpringBootApplication) in a root package so that all sub-packages and classes can be searched.

    Auto-configuration classes are regular Spring Configuration beans. They are located using the SpringFactoriesLoader mechanism (keyed against this class). Generally auto-configuration beans are @Conditional beans (most often using @ConditionalOnClass and @ConditionalOnMissingBean annotations).

    220)org.springframework.web.bind.annotation.CrossOrigin

    Annotation for permitting cross-origin requests on specific handler classes and/or handler methods. Processed if an appropriate HandlerMapping is configured.

    Both Spring Web MVC and Spring WebFlux support this annotation through the RequestMappingHandlerMapping in their respective modules. The values from each type and method level pair of annotations are added to a CorsConfiguration and then default values are applied via CorsConfiguration.applyPermitDefaultValues().

    The rules for combining global and local configuration are generally additive -- e.g. all global and all local origins. For those attributes where only a single value can be accepted such as allowCredentials and maxAge, the local overrides the global value. See CorsConfiguration.combine(CorsConfiguration) for more details.

    221)How to reverse a String in Java?

    import java.util.Scanner;

    public class ReverseString1 {

    public static void main(String[] args) {

    Scanner sc =new Scanner(System.in);

    System.out.println("Enter any string:");

    String s = sc.next();

    sc.close();

    //String s = "swamy raju";

    String str = new StringBuilder(s).reverse().toString();

    System.out.println("reverse string is:"+str);

    String rs ="";

    for(int i =s.length()-1;i>=0;i--)

    {

    rs = rs+s.charAt(i);

    }

    System.out.println("The reverse string is:"+rs);

    }

    } 222)How to swap two numbers without using a third variable?

    public class swap {

    public static void main(String[] args) {

    int a = 10, b = 20;

    a = a+b;

    b =a-b;

    a = a-b;

    System.out.println(a);

    System.out.println(b);

    }

    } 223)Separate vowels and consonants from given string


    import java.util.Arrays;

    import java.util.List;

    import java.util.Set;

    import java.util.stream.Collectors;


    public class SepVowCon {


    public static void main(String[] args) {

    String str = "Hi this is swamy, separating vowels and consonants";

    List<Character> vowels = Arrays.asList('a','e','i','o','u');

    Set<Character> charSet = str.chars().mapToObj(e->(char)e).collect(Collectors.toSet());

    List<Character> listVowels = charSet.stream().filter(ch->vowels.contains(ch.toLowerCase(ch))).collect(Collectors.toList());

    List<Character> listConsonants = charSet.stream().filter(ch->!vowels.contains(ch.toLowerCase(ch))).collect(Collectors.toList());

    System.out.println("The listVowels"+listVowels);

    System.out.println("The listConsonants"+listConsonants);

    }

    }

    224)Java program to check if the given number is Prime


    import java.util.Scanner;


    public class PrimeNumberOrNot {

    public static void main(String args[]) {

    int i, m = 0, flag = 0;

    Scanner sc = new Scanner(System.in);

    System.out.println("Enter the integer:");

    int number = sc.nextInt();

    m = number / 2;

    if (number == 0 || number == 1) {

    System.out.println(number + " is not prime number");

    } else {

    for (i = 2; i <= m; i++) {

    if (number % i == 0) {

    System.out.println(number + " is not prime number");

    flag = 1;

    break;

    }

    }

    if (flag == 0) {

    System.out.println(number + " is prime number");

    }

    } // end of else

    }

    }

    225a)Check given string is palindrome or not


    public class StringPalindrome {

    public static void main(String args[]) {


    // Scanner sc=new Scanner(System.in);

    // System.out.println("Please enter string: ");

    // String str=sc.nextLine();

    String str = "strts";

    String revstr = "";

    int strlength = str.length();

    for (int i = strlength - 1; i >= 0; i--)

    revstr = revstr + str.charAt(i);

    if (str.equals(revstr))

    System.out.println(str + " is a palindrome.");

    else

    System.out.println(str + " is not a palindrome.");

    }

    }



    225b)Check given number is palindrome or not


    import java.util.Scanner;


    public class PalindromeNumberOrNot {

    public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.println("Enter any number:");

    int n = sc.nextInt();

    sc.close();


    if (isPalindrome(n)) {

    System.out.println("Palindrome");

    } else {

    System.out.println("Not a palindrome");

    }

    }


    private static boolean isPalindrome(int n) {

    int original = n;

    int reversed = reverseNumber(n);

    return original == reversed;

    }


    private static int reverseNumber(int n) {

    int reversed = 0;

    while (n > 0) {

    reversed = reversed * 10 + n % 10;

    n /= 10;

    }

    return reversed;

    }

    }


    226)Print number of largest polindrome in a string

    import java.util.Scanner;


    public class LargestPalindromeInString {

    public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.println("Enter a string:");

    String input = sc.nextLine();

    sc.close();


    String largestPalindrome = findLargestPalindrome(input);

    System.out.println("The largest palindrome in the string is: " + largestPalindrome);

    }


    // Method to find the largest palindrome

    private static String findLargestPalindrome(String str) {

    String largestPalindrome = "";


    for (int i = 0; i < str.length(); i++) {

    // Odd-length palindromes

    String oddPalindrome = expandAroundCenter(str, i, i);

    if (oddPalindrome.length() > largestPalindrome.length()) {

    largestPalindrome = oddPalindrome;

    }


    // Even-length palindromes

    String evenPalindrome = expandAroundCenter(str, i, i + 1);

    if (evenPalindrome.length() > largestPalindrome.length()) {

    largestPalindrome = evenPalindrome;

    }

    }


    return largestPalindrome;

    }


    // Helper method to expand around center and check for palindrome

    private static String expandAroundCenter(String str, int left, int right) {

    while (left >= 0 && right < str.length() && str.charAt(left) == str.charAt(right)) {

    left--;

    right++;

    }

    return str.substring(left + 1, right);

    }

    }


    227)Fibonacci Series


    import java.util.Scanner;

    public class NonRecursiveFibonacci {


    public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.println("Enter the number of Fibonacci numbers to generate:");

    int n = sc.nextInt();

    sc.close();

    int firstFibonacci = 1;

    int secondFibonacci = 1;

    System.out.println(firstFibonacci);

    System.out.println(secondFibonacci);

    for (int i = 2; i < n; i++) {

    int currentFibonacci = firstFibonacci + secondFibonacci;

    System.out.println(currentFibonacci);

    firstFibonacci = secondFibonacci;

    secondFibonacci = currentFibonacci;

    }

    }

    }

    228) How to remove Whitespaces from String


    //need to add below deppendency in pom.xml file

    <dependency>

    <groupId>org.apache.commons</groupId>

    <artifactId>commons-lang3</artifactId>

    <version>3.12.0</version>

    </dependency>


    import org.apache.commons.lang3.StringUtils

    public class RemoveWhitespaces {

    public static void main(String[] args) {

    // String input = " Hello World ! ";

    // String result = StringUtils.deleteWhitespace(input);

    // System.out.println("String without whitespaces: \"" + result + "\"");

    String input = " Hello world ! ";

    String result =StringUtils.deleteWhitespace(input);

    System.out.println("String without whitespaces:"+result);

    }

    }


    229) Sorting an array


    import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class ArraySort { public static void main(String[] args) { // Integer Array Integer[] arr = {5, 3, 9, 4, 6, 99}; System.out.println("Original Array: " + Arrays.toString(arr)); // Ascending using Stream List<Integer> ascSorted = Arrays.stream(arr) .sorted() .collect(Collectors.toList()); System.out.println("Sorted (Ascending): " + ascSorted); // Descending using Stream List<Integer> descSorted = Arrays.stream(arr) .sorted(Comparator.reverseOrder()) .collect(Collectors.toList()); System.out.println("Sorted (Descending): " + descSorted); // Bubble sort remains as an algorithm example (not stream-based) Integer[] bubble = {5, 3, 9, 4, 6, 99}; for (int i = 0; i < bubble.length - 1; i++) { for (int j = 0; j < bubble.length - i - 1; j++) { if (bubble[j] > bubble[j + 1]) { int temp = bubble[j]; bubble[j] = bubble[j + 1]; bubble[j + 1] = temp; } } } System.out.println("Bubble Sorted: " + Arrays.toString(bubble)); // String Array String[] strArr = {"banana", "apple", "cherry", "date"}; System.out.println("Original String Array: " + Arrays.toString(strArr)); // Alphabetical sort List<String> sortedStrings = Arrays.stream(strArr) .sorted() .collect(Collectors.toList()); System.out.println("Sorted Strings (Alphabetical): " + sortedStrings); // Sort by length List<String> sortedByLength = Arrays.stream(strArr) .sorted(Comparator.comparingInt(String::length)) .collect(Collectors.toList()); System.out.println("Sorted by Length: " + sortedByLength); // List sorting with streams List<Integer> list = new ArrayList<>(Arrays.asList(5, 2, 8, 1, 3)); System.out.println("Original List: " + list); // Sort ascending using streams List<Integer> sortedListAsc = list.stream() .sorted() .collect(Collectors.toList()); System.out.println("List Sorted (Ascending): " + sortedListAsc); // Sort descending using streams List<Integer> sortedListDesc = list.stream() .sorted(Comparator.reverseOrder()) .collect(Collectors.toList()); System.out.println("List Sorted (Descending): " + sortedListDesc); // Custom sort with stream (Even first, then odd) List<Integer> evenFirst = list.stream() .sorted((a, b) -> { if (a % 2 == 0 && b % 2 != 0) return -1; if (a % 2 != 0 && b % 2 == 0) return 1; return a - b; }) .collect(Collectors.toList()); System.out.println("List Sorted (Even First): " + evenFirst); } }


    230) Find factorial of an integer?


    public class Factorial {

    public static void main(String[] args) {

    int number = 5; // Input number

    long factorial = 1;


    for (int i = 1; i <= number; i++) {

    factorial *= i;

    }


    System.out.println("Factorial of " + number + " is: " + factorial);

    }

    }


    231) Find common elements from 2 arrays


    import java.util.Arrays;

    import java.util.List;

    import java.util.stream.Collectors;


    public class CommonElementsin2Arrays {

    public static void main(String[] args) {

    Integer[] array1 = {1, 2, 3, 4, 5};

    Integer[] array2 = {3, 4, 5, 6, 7};


    List<Integer> common = Arrays.stream(array1)

    .filter(num -> Arrays.asList(array2).contains(num))

    .distinct()

    .collect(Collectors.toList());


    System.out.println("Common Elements: " + common);

    }

    }


    232) How to get distinct characters and their count in a String?


    import java.util.Map;

    import java.util.function.Function;

    import java.util.stream.Collectors;


    public class DistinctCharacters_imp {

    public static void main(String[] args) {

    String input = "programming";


    Map<Character, Long> charCountMap = input.chars().mapToObj(c -> (char) c)

    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));


    System.out.println("Distinct Characters and Counts: " + charCountMap);

    }

    }


    233) Difference between Java8 filter, groupby


    The filter and groupBy operations in Java 8 serve different purposes in the Stream API.

    1. Filter:


    Filter is used to filter the elements from a stream based on a condition (predicate). and it returns only those elements that match the predicate.


    Method Signature: Stream<T> filter(Predicate<? super T> predicate);


    Use Case: Filter is used to retrieve a subset of elements from a collection or stream.


    Example: import java.util.Arrays;

    import java.util.List;

    import java.util.stream.Collectors;


    public class FilterExample {

    public static void main(String[] args) {

    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);


    // Filter even numbers

    List<Integer> evenNumbers = numbers.stream()

    .filter(num -> num % 2 == 0)

    .collect(Collectors.toList());


    System.out.println("Even Numbers: " + evenNumbers);

    }

    }


    2. groupBy:


    groupBy is used to the group elements of a stream into a Map based on a classifier function.

    and it returns a Map<K, List<T>> where K is the key generated by the classifier and List<T> is the list of items sharing the same key


    Method: It is not directly part of the Stream API but is achieved using Collectors.groupingBy().


    Use case: groupBy is used to categorize elements of a stream based on a specific property.


    Example:

    import java.util.Arrays;

    import java.util.List;

    import java.util.Map;

    import java.util.stream.Collectors;


    public class GroupByExample {

    public static void main(String[] args) {

    List<String> words = Arrays.asList("apple", "banana", "apricot", "blueberry", "cherry", "avocado");


    // Group words by their first letter

    Map<Character, List<String>> groupedByFirstLetter = words.stream()

    .collect(Collectors.groupingBy(word -> word.charAt(0)));


    System.out.println("Grouped Words: " + groupedByFirstLetter);

    }

    }


    Key Differences:

    FeatureFilterGroupBy
    PurposeFilters elements based on a condition.Groups elements based on a classifier function.
    ResultA Stream or collection with filtered elements.A Map with grouped elements.
    Return TypeStream<T>Map<K, List<T>>
    Example UseGet even numbers from a list.Group words by their starting letter.


    234) Java map() and to toMap() Programs


    1. map():


    map() is used to transform elements in a stream into another form. It operates on each element and produces a new stream with transformed elements.

    and it returns a Stream<R>, where R is the transformed type.


    Use Case: map() is used to data transformation or mapping from one type to another (e.g., from String to Integer or from lowercase to uppercase).


    Example:

    import java.util.Arrays;

    import java.util.List;

    import java.util.stream.Collectors;


    public class MapExample {

    public static void main(String[] args) {

    List<String> names = Arrays.asList("Swamy", "Pranu", "Srihan");


    // Convert names to uppercase using map()

    List<String> upperCaseNames = names.stream()

    .map(String::toUpperCase)

    .collect(Collectors.toList());


    System.out.println("Uppercase Names: " + upperCaseNames);

    }

    }


    2. toMap():


    toMap() is used to collect stream elements into a Map by applying key and value mapping functions.

    and it returns a Map<K, U>, where K is the key and U is the value.


    Use case: toMap() is used to create mappings (e.g., name to length, product to price).


    Example:

    import java.util.Arrays;

    import java.util.List;

    import java.util.Map;

    import java.util.stream.Collectors;


    public class ToMapExample {

    public static void main(String[] args) {

    List<String> names = Arrays.asList("Swamy", "Pranu", "Srihan");


    // Create a map where key is the name and value is the length of the name

    Map<String, Integer> nameLengthMap = names.stream()

    .collect(Collectors.toMap(

    name -> name, // Key mapper

    name -> name.length() // Value mapper

    ));


    System.out.println("Name Length Map: " + nameLengthMap);

    }

    }


    Key Differences:

    Featuremap()toMap()
    PurposeTransforms elements in a stream.Collects elements into a Map.
    ResultProduces a transformed Stream<R>.Produces a Map<K, U> with custom key-value pairs.
    Return TypeA Stream with transformed elements.A Map with keys and values derived from the stream.
    Use CaseData transformation (e.g., convert to uppercase).Create a mapping (e.g., name to length).


    CombinedExample: import java.util.Arrays;

    import java.util.List;

    import java.util.Map;

    import java.util.stream.Collectors;


    public class CombinedExample {

    public static void main(String[] args) {

    List<String> names = Arrays.asList("Swamy", "Pranu", "Srihan");


    // Convert names to uppercase and collect them into a map

    Map<String, Integer> upperCaseNameLengthMap = names.stream()

    .map(String::toUpperCase) // Transform names to uppercase

    .collect(Collectors.toMap(

    name -> name, // Key mapper

    name -> name.length() // Value mapper

    ));


    System.out.println("Uppercase Name Length Map: " + upperCaseNameLengthMap);

    }

    }


    235) Java 8 convert list into map


    Converting a List to a Map in Java 8 involves using the Stream API and the Collectors.toMap() method.

    The process can vary depending on the requirements, such as defining the keys and values, handling duplicate keys,

    and customizing the map's behavior.


    1. Basic Conversion

    • Purpose: Convert a list to a map by defining how the keys and values are derived from the list elements.

    import java.util.Arrays;

    import java.util.List;

    import java.util.Map;

    import java.util.stream.Collectors;


    public class ListToMapBasicExample {

    public static void main(String[] args) {

    List<String> names = Arrays.asList("Swamy", "Pranu", "Srihan");


    // Convert list to map where key is the name and value is the length of the name

    Map<String, Integer> nameLengthMap = names.stream()

    .collect(Collectors.toMap(

    name -> name, // Key mapper

    name -> name.length() // Value mapper

    ));


    System.out.println("Name Length Map: " + nameLengthMap);

    }

    }


    2. Handling Duplicate Keys

    • If there are duplicate keys (e.g., two elements that map to the same key), toMap() will throw an IllegalStateException.
    • To handle this, you can provide a merge function to resolve conflicts.

    3. Custom Map Implementation

    • By default, toMap() creates a HashMap. You can specify a custom Map implementation, such as TreeMap or LinkedHashMap.

    Example

    import java.util.Arrays;

    import java.util.List;

    import java.util.Map;

    import java.util.stream.Collectors;

    import java.util.TreeMap;


    public class ListToMapCustomMap {

    public static void main(String[] args) {

    List<String> names = Arrays.asList("Swamy", "Pranu", "Srihan");


    // Use a TreeMap for sorted keys

    Map<String, Integer> nameLengthMap = names.stream()

    .collect(Collectors.toMap(

    name -> name, // Key mapper

    name -> name.length(), // Value mapper

    (existing, replacement) -> existing, // Merge function

    TreeMap::new // Custom map supplier

    ));


    System.out.println("Name Length Map: " + nameLengthMap);

    }

    }

    4. Complex Object Conversion

    • Convert a list of custom objects into a map by specifying a property for the key and another property (or the object itself) for the value.

    Example

    import java.util.Arrays;

    import java.util.List;

    import java.util.Map;

    import java.util.stream.Collectors;


    class Employee {

    private int id;

    private String name;


    // Constructor

    public Employee(int id, String name) {

    this.id = id;

    this.name = name;

    }


    // Getters

    public int getId() {

    return id;

    }


    public String getName() {

    return name;

    }


    @Override

    public String toString() {

    return "Employee{id=" + id + ", name='" + name + "'}";

    }

    }


    public class ListToMapComplexExample {

    public static void main(String[] args) {

    List<Employee> employees = Arrays.asList(

    new Employee(1, "Swamy"),

    new Employee(2, "Pranu"),

    new Employee(3, "Srihan")

    );


    // Convert list to map where key is employee ID and value is the employee object

    Map<Integer, Employee> employeeMap = employees.stream()

    .collect(Collectors.toMap(

    Employee::getId, // Key mapper

    employee -> employee // Value mapper

    ));


    System.out.println("Employee Map: " + employeeMap);

    }

    }

    236) Functional interface in java 8


    In Java, a functional interface is an interface that contains exactly one abstract method.

    Functional interfaces can have any number of default and static methods, but only one abstract method.

    They are primarily used as the target for lambda expressions and method references, enabling functional programming in Java.


    Key Points About Functional Interfaces

    1. Marked with the @FunctionalInterface annotation (optional but recommended to indicate intent).
    2. Can contain default and static methods.
    3. Used with lambda expressions for concise code.

    The java.util.function package provides several built-in functional interfaces, such as Predicate, Consumer, Supplier, etc.

    Example: Custom Functional Interface

    @FunctionalInterface interface MyFunctionalInterface { void displayMessage(String message); // Single abstract method }

    public class FunctionalInterfaceExample { public static void main(String[] args) { // Implementing the functional interface using a lambda expression MyFunctionalInterface messagePrinter = (message) -> { System.out.println("Message: " + message); }; // Using the implemented method messagePrinter.displayMessage("Hello, Functional Interface!"); } }

    Example: Using Built-in Functional Interface (Predicate)

    The Predicate<T> functional interface takes a single input and returns a boolean result.

    import java.util.function.Predicate; public class PredicateExample { public static void main(String[] args) { // Predicate to check if a number is greater than 10 Predicate<Integer> isGreaterThanTen = (num) -> num > 10; // Test the predicate System.out.println(isGreaterThanTen.test(15)); // Output: true System.out.println(isGreaterThanTen.test(8)); // Output: false } }

    237) Lambda Expressions in Java 8

    A lambda expression is a concise way to represent an anonymous function in Java.
    It simplifies the implementation of functional interfaces, making the code more readable and concise.

    Syntax of a Lambda Expression:

    (parameters) -> expression (parameters) -> { statements; }

    Key Points:

    lambda expression is used to implement functional interfaces (interfaces with a single abstract method).
    And it eliminates the need for anonymous inner classes.

    Example 1: Basic Lambda Expression

    @FunctionalInterface interface Greeting { void sayHello(String name); } public class LambdaExample { public static void main(String[] args) { // Using a lambda expression to implement the functional interface Greeting greet = (name) -> System.out.println("Hello, " + name + "!"); greet.sayHello("Alice"); } }

    Example 2: Using Lambda Expression with Runnable

    public class LambdaRunnableExample { public static void main(String[] args) { // Without lambda: Anonymous inner class Thread thread1 = new Thread(new Runnable() { @Override public void run() { System.out.println("Thread 1 is running"); } }); thread1.start(); // With lambda expression Thread thread2 = new Thread(() -> System.out.println("Thread 2 is running")); thread2.start(); } }

    Example 3: Using Lambda with a Built-in Functional Interface (Consumer)

    The Consumer<T> functional interface takes an input and performs some action, without returning a result.

    import java.util.function.Consumer; public class LambdaConsumerExample { public static void main(String[] args) { Consumer<String> printMessage = message -> System.out.println("Message: " + message); // Using the lambda expression printMessage.accept("Lambda Expressions are powerful!"); } }

    Example 4: Using Lambda with Streams

    import java.util.Arrays; import java.util.List; public class LambdaStreamExample { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); // Using a lambda expression with forEach numbers.forEach(number -> System.out.println(number * 2)); } }


    Benefits of Lambda Expressions

    1. Conciseness: Reduces boilerplate code.
    2. Readability: Simplifies the implementation of single-method interfaces.
    3. Improved Efficiency: Especially with collections and streams, lambda expressions make code easier to write and maintain.

    238) Method References in Java 8 Method references are a shorthand notation of a lambda expression that executes a specific method.
    They improve readability by directly referencing existing methods instead of defining a lambda that calls the method.

    Types of Method References:
  • Static Method Reference: ClassName::staticMethodName
  • Instance Method Reference: instance::instanceMethodName
  • Reference to an Instance Method of an Arbitrary Object: ClassName::instanceMethodName
  • Constructor Reference: ClassName::new
  • Examples of Method References

    Example 1: Static Method Reference:

    import java.util.function.Consumer; public class StaticMethodReferenceExample { public static void printMessage(String message) { System.out.println("Static Method: " + message); } public static void main(String[] args) { Consumer<String> consumer = StaticMethodReferenceExample::printMessage; consumer.accept("Hello from static method!"); } }

    Example 2: Instance Method Reference:
    import java.util.function.Consumer; public class InstanceMethodReferenceExample { public void showMessage(String message) { System.out.println("Instance Method: " + message); } public static void main(String[] args) { InstanceMethodReferenceExample example = new InstanceMethodReferenceExample(); // Reference to an instance method of a particular object Consumer<String> consumer = example::showMessage; consumer.accept("Hello from instance method!"); } }

    Example 3: Reference to an Instance Method of an Arbitrary Object

    import java.util.Arrays; import java.util.List; public class ArbitraryObjectMethodReference { public static void main(String[] args) { List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); // Reference to the instance method 'toUpperCase' of String class names.stream() .map(String::toUpperCase) .forEach(System.out::println); } }

    Example 4: Constructor Reference

    import java.util.function.Supplier; class Person { private String name; public Person() { this.name = "Default Name"; } public String getName() { return name; } } public class ConstructorReferenceExample { public static void main(String[] args) { // Constructor reference Supplier<Person> personSupplier = Person::new; // Creating a new Person instance Person person = personSupplier.get(); System.out.println("Person Name: " + person.getName()); } }

    Benefits of Method References

    1. Improves Readability: More concise than lambda expressions.
    2. Reusable Code: Directly we can pass references in existing methods.
    3. Integration with Functional Interfaces: Works seamlessly with Java's built-in functional interfaces.

    Use Cases

    • Simplifying lambda expressions when the method already exists.
    • Processing collections using Streams API.
    • Implementing functional interfaces in a clean and readable way.
    239) Internal working of Hash Map, Hashset, concurrent hashmap.

    1. HashMap

    A HashMap is a collection that stores data in key-value pairs and provides

    constant-time performance (O(1)) for basic operations like insert, delete, and lookup, assuming the hash function

    disperses elements properly among the buckets.

    Internal Structure of HashMap:

    1.Hashing Mechanism:

    a)HashMap uses a hash function to map keys to an index (bucket) in an internal array called a bucket array.

    b)Each bucket stores a linked list (or tree in case of high collision) of Node objects containing the key, value, hash, and a reference to the next node.

    2.Node Structure:

    static class Node<K, V> { final int hash; final K key; V value; Node<K, V> next; }

    3.Collision Handling:

    Hash collisions are handled using chaining. Multiple keys with the same hash index

    are stored in a linked list or binary tree.

    4.Load Factor and Rehashing:

    • Load factor (default: 0.75) determines when the HashMap should resize.
    • When the number of elements exceeds capacity * load factor, the HashMap doubles its size and rehashes all elements.
    import java.util.HashMap; public class HashMapExample { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<>(); map.put("Alice", 30); map.put("Bob", 25); map.put("Charlie", 35); System.out.println(map.get("Alice")); // Output: 30 } }

    2. HashSet

    A HashSet is a collection that uses a HashMap internally to store elements. It allows no duplicates

    and provides constant-time performance (O(1)) for basic operations like add, remove, and contains.

    Internal Structure of HashSet:

    a)HashSet uses a HashMap to store elements.

    b)Each element in the HashSet is stored as a key in the HashMap, with a constant dummy value (PRESENT).

    import java.util.HashSet; public class HashSetExample { public static void main(String[] args) { HashSet<String> set = new HashSet<>(); set.add("Apple"); set.add("Banana"); set.add("Apple"); // Duplicate, won't be added System.out.println(set); // Output: [Apple, Banana] } }

    3. ConcurrentHashMap

    A ConcurrentHashMap is a thread-safe version of a HashMap that allows multiple threads

    to access it concurrently without compromising performance.

    Internal Structure of ConcurrentHashMap:

    a)Segmentation:

    i)Before Java 8: Used a segmented locking mechanism (separate locks for different buckets).

    ii)From Java 8: Replaced segmentation with a bucket-level locking mechanism and improved performance

    using a ConcurrentLinkedQueue or binary trees for collision handling.

    b)Thread Safety:

    i)Multiple threads can operate on different buckets concurrently.

    ii)Locks are applied at the bucket level, not the entire map.

    c)No Null Values:

    ConcurrentHashMap does not allow null keys or null values to avoid ambiguity during concurrent access.

    Example:

    import java.util.concurrent.ConcurrentHashMap; public class ConcurrentHashMapExample { public static void main(String[] args) { ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); map.put("John", 50); map.put("Jane", 60); // Accessing elements concurrently System.out.println(map.get("John")); // Output: 50 } }

    Comparison Table

    FeatureHashMapHashSetConcurrentHashMap
    Thread SafetyNot thread-safeNot thread-safeThread-safe
    Null Keys/Values1 null key, many null valuesAllows null elementsDoes not allow null keys or values
    PerformanceFast (single thread)Fast (single thread)Good (multithreaded access)
    Collision HandlingLinked List / TreeSame as HashMapConcurrent buckets


    240) Difference Between HashMap and ConcurrentHashMap



    FeatureHashMapConcurrentHashMap
    Thread SafetyNot thread-safe.Thread-safe, supports concurrent access.
    Null Keys/ValuesAllows one null key and multiple null values.Does not allow null keys or null values.
    ConcurrencyFails under concurrent modifications without external synchronization.Optimized for multi-threaded environments using bucket-level locking.
    Locking MechanismNo locking; requires explicit synchronization for thread safety.Uses bucket-level locking for better concurrency.
    PerformanceFast for single-threaded applications.Performs well under multi-threaded scenarios.
    IterationMay throw a ConcurrentModificationException during concurrent modifications.No ConcurrentModificationException during iteration.
    Read and Write OperationsReads and writes are not atomic.Reads are lock-free; writes lock buckets instead of the whole map.
    Use CaseSuitable for single-threaded or low-concurrency applications.Suitable for high-concurrency applications.


    HashMap Example (Not Thread-Safe):

    import java.util.HashMap; public class HashMapExample { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<>(); map.put("Swamy", 25); map.put("Srihan", 30); // Single-threaded access System.out.println("Swamy's age: " + map.get("Swamy")); // Output: 25 // Multi-threaded access (may cause issues) Thread writer = new Thread(() -> map.put("Raju", 35)); Thread reader = new Thread(() -> System.out.println("Raju's age: " + map.get("Raju"))); writer.start(); reader.start(); } }

    Potential Issues with HashMap in Multi-threaded Scenarios:

    1. Data Corruption: Simultaneous writes may lead to inconsistent state.
    2. ConcurrentModificationException: Iteration during modification may fail.

    ConcurrentHashMap Example (Thread-Safe):

    import java.util.concurrent.ConcurrentHashMap; public class ConcurrentHashMapExample { public static void main(String[] args) { ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); map.put("Swamy", 25); map.put("Srihan", 30); // Multi-threaded access Thread writer = new Thread(() -> map.put("Raju", 35)); Thread reader = new Thread(() -> System.out.println("Raju's age: " + map.get("Raju"))); writer.start(); reader.start(); // Concurrent iteration map.forEach((key, value) -> System.out.println(key + ": " + value)); } }

    Features of ConcurrentHashMap:

    1. Thread Safety: Operations like put(), get(), and remove() are thread-safe.
    2. Fine-Grained Locking: Only the bucket being modified is locked, allowing other threads to access different buckets.
    3. No Blocking for Reads: Read operations do not block even if writes are occurring on other buckets.

    Key Points

    1. Use HashMap when thread-safety is not required, and the application is single-threaded or has minimal concurrency.
    2. Use ConcurrentHashMap in multi-threaded environments to avoid data corruption and improve performance with concurrent access.
    241) Difference between SynchronizedMap and ConcurrentHashMap

    Difference Between SynchronizedMap and ConcurrentHashMap

    FeatureSynchronizedMap (via Collections.synchronizedMap)ConcurrentHashMap
    Thread SafetyThread-safe using a single lock on the entire map.Thread-safe using bucket-level locking (lock striping).
    Locking MechanismEntire map is locked during all operations, including reads and writes.Locks individual buckets, allowing higher concurrency.
    Concurrency LevelOnly one thread can access the map at a time.Multiple threads can operate on different buckets simultaneously.
    PerformanceSlower due to single lock for the entire map.Faster due to fine-grained locking.
    IterationMust explicitly synchronize during iteration to avoid ConcurrentModificationException.No explicit synchronization required during iteration.
    Null Keys/ValuesAllows one null key and multiple null values.Does not allow null keys or null values.
    Use CaseSuitable for applications with low concurrency requirements.Ideal for high-concurrency applications.

    SynchronizedMap Example:

    import java.util.Collections; import java.util.HashMap; import java.util.Map; public class SynchronizedMapExample { public static void main(String[] args) { Map<String, Integer> synchronizedMap = Collections.synchronizedMap(new HashMap<>()); // Adding data synchronizedMap.put("Swamy", 25); synchronizedMap.put("Srihan", 30); // Multi-threaded access Thread writer = new Thread(() -> synchronizedMap.put("Raju", 35)); Thread reader = new Thread(() -> System.out.println(synchronizedMap.get("Raju"))); writer.start(); reader.start(); // Iterating (explicit synchronization required) synchronized (synchronizedMap) { synchronizedMap.forEach((key, value) -> System.out.println(key + ": " + value)); } } }

    Key Notes:

    1. Must explicitly synchronize the map during iteration.
    2. A single lock reduces throughput in multi-threaded environments.
    ConcurrentHashMap Example:

    import java.util.concurrent.ConcurrentHashMap; public class ConcurrentHashMapExample { public static void main(String[] args) { ConcurrentHashMap<String, Integer> concurrentMap = new ConcurrentHashMap<>(); // Adding data concurrentMap.put("Swamy", 25); concurrentMap.put("Srihan", 30); // Multi-threaded access Thread writer = new Thread(() -> concurrentMap.put("Raju", 35)); Thread reader = new Thread(() -> System.out.println(concurrentMap.get("Raju"))); writer.start(); reader.start(); // Iterating (no explicit synchronization required) concurrentMap.forEach((key, value) -> System.out.println(key + ": " + value)); } }

    Key Features:

    1. No need for explicit synchronization during iteration.
    2. Supports higher concurrency with bucket-level locking.

    When to Use

    1. SynchronizedMap:

      • Use when the application is single-threaded or has low concurrency.
      • Preferable when minimal synchronization overhead is acceptable.
    2. ConcurrentHashMap:

      • Use in high-concurrency applications to ensure better performance.
      • Ideal when frequent reads and writes are required.
    242. java 8 -> count occurrences of the characters in given string

    Example1 : Countcharacters using Function

    import java.util.Map;

    import java.util.function.Function;

    import java.util.stream.Collectors;


    public class CountCharacters1 {


    public static void main(String[] args) {

    String word = "AAABBB";

    Map<String, Long> charCount = word.codePoints().mapToObj(Character::toString)

    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

    System.out.println(charCount);


    }


    }


    Example2 : Countcharacters using getOrDefault method
    import java.util.HashMap; import java.util.Map; public class CountCharacters2 { public static void main(String[] args) { String word = "AAABBBcccc"; Map<Character, Integer> charCount = new HashMap<>(); for (Character ch : word.toCharArray()) { charCount.put(ch, charCount.getOrDefault(ch, 0) + 1); // Increment count or initialize to 1 } System.out.println(charCount); } } 243: the sum of the squares of all odd numbers in a given list using Java 8's Streams API with parallel execution
    Given : List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); The code should generate the following result. 1²+3²+5²=35

    import java.util.Arrays; import java.util.List; public class SquaresOfOdd{ public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); int sum = numbers.parallelStream() .filter(n -> n % 2 == 1) .map(n -> n * n) .reduce(0, Integer::sum); System.out.println(sum); } } 244: Write the program for reverses the order of words
          String str= this is a string
          Output: string a is this

    Example with Collections.reverse(), String.join():

    import java.util.Collections;

    import java.util.List;

    import java.util.Arrays;


    class ReverseOrderOfWords1 {

    public static void main(String[] args) {

    String input = "this is a string";

    List<String> words = Arrays.asList(input.split(" "));

    Collections.reverse(words);

    String result = String.join(" ", words);

    System.out.println(result);

    }

    }


    Example with StringBuilder:

    class ReverseOrderOfWords2 {

    public static void main(String[] args) {

    String input = "this is a string";

    String[] words = input.split(" ");

    StringBuilder result = new StringBuilder();


    for (int i = words.length - 1; i >= 0; i--) {

    result.append(words[i]).append(" ");

    }


    System.out.println(result.toString().trim());

    }

    }


    245: Write a program to find unique value between two arrays
    originalarr={1, 2,3,4,5,6,7,8,9}
    Duparray={1,2,3,4,5,7,8,9}

    Example with Streams:

    import java.util.Arrays;

    import java.util.Set;

    import java.util.stream.Collectors;


    public class UniqueValueFinder1 {

    public static void main(String[] args) {

    int[] originalArr = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    int[] dupArray = {1, 2, 3, 4, 5, 7, 8, 9};


    Set<Integer> dupSet = Arrays.stream(dupArray).boxed().collect(Collectors.toSet());


    int uniqueValue = Arrays.stream(originalArr)

    .filter(num -> !dupSet.contains(num))

    .findFirst()

    .orElseThrow(() -> new RuntimeException("No unique value found"));


    System.out.println("Unique value: " + uniqueValue);

    }

    }


    Example without Streams:

    import java.util.HashSet;

    import java.util.Set;


    public class UniqueValueFinder2 {

    public static void main(String[] args) {

    int[] originalArr = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    int[] dupArray = {1, 2, 3, 4, 5, 7, 8, 9};


    // Add elements of dupArray to a Set

    Set<Integer> dupSet = new HashSet<>();

    for (int num : dupArray) {

    dupSet.add(num);

    }


    // Find the unique value from originalArr

    for (int num : originalArr) {

    if (!dupSet.contains(num)) {

    System.out.println("Unique value: " + num);

    break; // Exit loop once unique value is found

    }

    }

    }

    }


    246: Write a program to find employeename Groupby doj 


    import java.time.LocalDate;

    import java.util.Arrays;

    import java.util.List;

    import java.util.Map;

    import java.util.stream.Collectors;


    class Employee1 {

    private String name;

    private LocalDate doj;


    public Employee1(String name, LocalDate doj) {

    this.name = name;

    this.doj = doj;

    }


    public String getName() {

    return name;

    }


    public LocalDate getDoj() {

    return doj;

    }


    @Override

    public String toString() {

    return name;

    }

    }


    public class GroupByDOJ {

    public static void main(String[] args) {

    // Sample employee data

    List<Employee1> employees = Arrays.asList(

    new Employee1("swamy", LocalDate.of(2021, 5, 15)),

    new Employee1("Pranu", LocalDate.of(2020, 3, 20)),

    new Employee1("Vaisu", LocalDate.of(2021, 5, 15)),

    new Employee1("Srihan", LocalDate.of(2020, 3, 20)),

    new Employee1("Raju", LocalDate.of(2019, 8, 10))

    );


    // Group employee names by DOJ

    Map<LocalDate, List<String>> groupedByDOJ = employees.stream()

    .collect(Collectors.groupingBy(

    Employee1::getDoj, // Group by DOJ

    Collectors.mapping(Employee1::getName, // Collect names

    Collectors.toList()) // Collect into a list

    ));


    // Print the grouped data

    groupedByDOJ.forEach((doj, names) -> {

    System.out.println("DOJ: " + doj + " -> Employees: " + names);

    });

    }

    }


    247: Write a program to remove the symbol [ from the string in Java

    Srting str=This[Is[A[String


    Using String.replace():


    public class RemoveSymbol1 {

    public static void main(String[] args) {

    String str = "This[Is[A[String";

    // Remove all occurrences of '['

    String result = str.replace("[", "");

    System.out.println(result);

    }

    }


    Using String.replaceAll():


    public class RemoveSymbol2 {

    public static void main(String[] args) {

    String str = "This[Is[A[String";

    // Remove all occurrences of '[' using regex

    String result = str.replaceAll("\\[", "");

    System.out.println(result);

    }

    }


    248: Write a program to add the symbol [ before every uppercase letter in the string

    Srting str=ThisIsAString


    public class AddSymbolBeforeCaps {

    public static void main(String[] args) {

    String str = "ThisIsAString";


    // Add "[" before each uppercase letter

    String result = str.replaceAll("([A-Z])", "[$1");


    System.out.println(result);

    }

    } 249: What are associations in hibernate


    In Hibernate, associations define relationships between entities (tables in a relational database).

    They are used to map object relationships in Java to database relationships efficiently.

    Hibernate supports different types of associations based on cardinality.


    Types of Associations in Hibernate

    1. One-to-One Association (@OneToOne)

    • Each entity has exactly one related entity.
    • Example: A User has one Address.

    Example:

    @Entity
    public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "address_id", referencedColumnName = "id") private Address address; }

    @Entity public class Address { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String street; }

    2. One-to-Many Association (@OneToMany)

    • One entity is related to multiple instances of another entity.
    • Example: A Department has many Employees.

    Example:

    @Entity public class Department { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @OneToMany(mappedBy = "department", cascade = CascadeType.ALL) private List<Employee> employees; }

    @Entity public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @ManyToOne @JoinColumn(name = "department_id") private Department department; }

    3. Many-to-One Association (@ManyToOne)

    • Many entities are associated with a single entity.

    • Example: Many Employees belong to one Department (same as above).

    • The @ManyToOne annotation is always used on the child side of a relationship.


    4. Many-to-Many Association (@ManyToMany)

    • Many entities are related to many other entities.
    • Example: A Student can enroll in multiple Courses, and a Course can have multiple Students.

    Example:

    @Entity public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @ManyToMany @JoinTable( name = "student_course", joinColumns = @JoinColumn(name = "student_id"), inverseJoinColumns = @JoinColumn(name = "course_id") ) private List<Course> courses; }

    @Entity public class Course { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; @ManyToMany(mappedBy = "courses") private List<Student> students; }

    Association Fetching in Hibernate

    When loading related entities, Hibernate provides two fetching strategies:

    1. Lazy Loading (FetchType.LAZY) (Default for OneToMany & ManyToMany)

      • Loads the related entity only when accessed.
      • Example:
        @OneToMany(mappedBy = "department", fetch = FetchType.LAZY) private List<Employee> employees;
    2. Eager Loading (FetchType.EAGER)

      • Loads the related entity immediately when the parent is loaded.
      • Example:
        @OneToOne(fetch = FetchType.EAGER) private Address address;

    Cascade Types

    Cascade operations define how changes in one entity affect the related entity.

    • CascadeType.ALL: Propagates all operations (INSERT, UPDATE, DELETE).
    • CascadeType.PERSIST: Saves child when parent is saved.
    • CascadeType.MERGE: Merges child when parent is merged.
    • CascadeType.REMOVE: Deletes child when parent is deleted.
    • CascadeType.REFRESH: Refreshes child when parent is refreshed.
    • CascadeType.DETACH: Detaches child when parent is detached.

    Example:

    @OneToMany(mappedBy = "department", cascade = CascadeType.ALL) private List<Employee> employees;

    Conclusion

    Hibernate associations help define relationships between entities effectively.

    Choosing the right association type and fetching strategy is crucial for performance and proper data management in a Spring Boot application.


    250. What is the output for given code? String s = "test"; s.concat("java"); System.out.println(s);


    Output: test

    Because String is immutable in Java.


    251. Can i extends FI1 with FT2?

    @FunctionalInterface interface I2 { void show(); } @FunctionalInterface interface I1 extends I2 { void display(); // ❌ Now I1 has two abstract methods: show() + display() }

    Ans: No


    251. What is the output for given code?

    class A {

    void show() {

    System.out.println("Inside A: show()");

    }

    }


    class B extends Main {

    void display() {

    System.out.println("Inside B: display()");

    }

    }


    class Main {

    public static void main(String[] args) {

    B a = new B();

    }

    }


    Output: (no output)