{"id":2216,"date":"2024-08-07T17:00:09","date_gmt":"2024-08-07T17:00:09","guid":{"rendered":"https:\/\/itnotes.apjsoftwares.in\/?p=2216"},"modified":"2024-08-07T17:46:55","modified_gmt":"2024-08-07T17:46:55","slug":"java-programming-interview-questions-for-4-years","status":"publish","type":"post","link":"https:\/\/itnotes.apjsoftwares.in\/index.php\/2024\/08\/07\/java-programming-interview-questions-for-4-years\/","title":{"rendered":"Java programming interview questions for 4 years"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\">1. FizzBuzz Problem<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program that prints the numbers from 1 to 100. But for multiples of three, print &#8220;Fizz&#8221; instead of the number and for the multiples of five, print &#8220;Buzz&#8221;. For numbers which are multiples of both three and five, print &#8220;FizzBuzz&#8221;.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class FizzBuzz {\n    public static void main(String&#91;] args) {\n        for (int i = 1; i &lt;= 100; i++) {\n            if (i % 3 == 0 &amp;&amp; i % 5 == 0) {\n                System.out.println(\"FizzBuzz\");\n            } else if (i % 3 == 0) {\n                System.out.println(\"Fizz\");\n            } else if (i % 5 == 0) {\n                System.out.println(\"Buzz\");\n            } else {\n                System.out.println(i);\n            }\n        }\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">2. Reverse a String<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to reverse a string without using the built-in reverse method.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class ReverseString {\n    public static void main(String&#91;] args) {\n        String str = \"Hello, World!\";\n        String reversed = reverse(str);\n        System.out.println(reversed);\n    }\n\n    public static String reverse(String str) {\n        if (str == null || str.length() == 0) {\n            return str;\n        }\n        StringBuilder sb = new StringBuilder();\n        for (int i = str.length() - 1; i &gt;= 0; i--) {\n            sb.append(str.charAt(i));\n        }\n        return sb.toString();\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">3. Check for Palindrome<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to check if a given string is a palindrome.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class Palindrome {\n    public static void main(String&#91;] args) {\n        String str = \"madam\";\n        boolean isPalindrome = isPalindrome(str);\n        System.out.println(str + \" is palindrome? \" + isPalindrome);\n    }\n\n    public static boolean isPalindrome(String str) {\n        int left = 0;\n        int right = str.length() - 1;\n        while (left &lt; right) {\n            if (str.charAt(left) != str.charAt(right)) {\n                return false;\n            }\n            left++;\n            right--;\n        }\n        return true;\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">4. Find the Missing Number<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to find the missing number in an array of size <code>n<\/code> containing numbers from 1 to <code>n<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class MissingNumber {\n    public static void main(String&#91;] args) {\n        int&#91;] arr = {1, 2, 4, 5, 6};\n        int missingNumber = findMissingNumber(arr);\n        System.out.println(\"Missing number is: \" + missingNumber);\n    }\n\n    public static int findMissingNumber(int&#91;] arr) {\n        int n = arr.length + 1;\n        int sum = (n * (n + 1)) \/ 2;\n        int arrSum = 0;\n        for (int num : arr) {\n            arrSum += num;\n        }\n        return sum - arrSum;\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">5. Fibonacci Series<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to print the first <code>n<\/code> Fibonacci numbers.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class Fibonacci {\n    public static void main(String&#91;] args) {\n        int n = 10;\n        printFibonacci(n);\n    }\n\n    public static void printFibonacci(int n) {\n        int a = 0, b = 1;\n        System.out.print(a + \" \" + b);\n        for (int i = 2; i &lt; n; i++) {\n            int next = a + b;\n            System.out.print(\" \" + next);\n            a = b;\n            b = next;\n        }\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">6. Anagram Check<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to check if two strings are anagrams of each other.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.Arrays;\n\npublic class AnagramCheck {\n    public static void main(String&#91;] args) {\n        String str1 = \"listen\";\n        String str2 = \"silent\";\n        boolean isAnagram = areAnagrams(str1, str2);\n        System.out.println(str1 + \" and \" + str2 + \" are anagrams? \" + isAnagram);\n    }\n\n    public static boolean areAnagrams(String str1, String str2) {\n        if (str1.length() != str2.length()) {\n            return false;\n        }\n        char&#91;] charArray1 = str1.toCharArray();\n        char&#91;] charArray2 = str2.toCharArray();\n        Arrays.sort(charArray1);\n        Arrays.sort(charArray2);\n        return Arrays.equals(charArray1, charArray2);\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">7. Factorial Calculation<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to calculate the factorial of a number using recursion.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class Factorial {\n    public static void main(String&#91;] args) {\n        int number = 5;\n        int result = factorial(number);\n        System.out.println(\"Factorial of \" + number + \" is: \" + result);\n    }\n\n    public static int factorial(int n) {\n        if (n == 0) {\n            return 1;\n        }\n        return n * factorial(n - 1);\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">8. Find the Second Largest Number in an Array<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to find the second largest number in an array.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class SecondLargest {\n    public static void main(String&#91;] args) {\n        int&#91;] arr = {10, 5, 20, 8, 12};\n        int secondLargest = findSecondLargest(arr);\n        System.out.println(\"Second largest number is: \" + secondLargest);\n    }\n\n    public static int findSecondLargest(int&#91;] arr) {\n        int firstLargest = Integer.MIN_VALUE;\n        int secondLargest = Integer.MIN_VALUE;\n        for (int num : arr) {\n            if (num &gt; firstLargest) {\n                secondLargest = firstLargest;\n                firstLargest = num;\n            } else if (num &gt; secondLargest &amp;&amp; num != firstLargest) {\n                secondLargest = num;\n            }\n        }\n        return secondLargest;\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">9. Sum of Digits in a Number<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to find the sum of the digits of a given number.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class SumOfDigits {\n    public static void main(String&#91;] args) {\n        int number = 12345;\n        int sum = sumOfDigits(number);\n        System.out.println(\"Sum of digits of \" + number + \" is: \" + sum);\n    }\n\n    public static int sumOfDigits(int number) {\n        int sum = 0;\n        while (number != 0) {\n            sum += number % 10;\n            number \/= 10;\n        }\n        return sum;\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">10. Print All Permutations of a String<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to print all permutations of a given string.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class Permutations {\n    public static void main(String&#91;] args) {\n        String str = \"ABC\";\n        permute(str, 0, str.length() - 1);\n    }\n\n    public static void permute(String str, int l, int r) {\n        if (l == r) {\n            System.out.println(str);\n        } else {\n            for (int i = l; i &lt;= r; i++) {\n                str = swap(str, l, i);\n                permute(str, l + 1, r);\n                str = swap(str, l, i); \/\/ backtrack\n            }\n        }\n    }\n\n    public static String swap(String str, int i, int j) {\n        char&#91;] charArray = str.toCharArray();\n        char temp = charArray&#91;i];\n        charArray&#91;i] = charArray&#91;j];\n        charArray&#91;j] = temp;\n        return String.valueOf(charArray);\n    }\n}\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Collection Programs<\/h2>\n\n\n\n<p><strong>1. Write a Java program to demonstrate the use of <code>ArrayList<\/code>.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.ArrayList;\nimport java.util.List;\n\npublic class ArrayListExample {\n    public static void main(String&#91;] args) {\n        List&lt;String&gt; fruits = new ArrayList&lt;&gt;();\n\n        \/\/ Adding elements\n        fruits.add(\"Apple\");\n        fruits.add(\"Banana\");\n        fruits.add(\"Orange\");\n\n        \/\/ Iterating through the list\n        for (String fruit : fruits) {\n            System.out.println(fruit);\n        }\n\n        \/\/ Getting an element\n        System.out.println(\"First fruit: \" + fruits.get(0));\n\n        \/\/ Removing an element\n        fruits.remove(\"Banana\");\n        System.out.println(\"After removing Banana: \" + fruits);\n\n        \/\/ Checking size\n        System.out.println(\"Size of the list: \" + fruits.size());\n    }\n}\n<\/code><\/pre>\n\n\n\n<p><strong>2. Write a Java program to demonstrate the use of <code>LinkedList<\/code>.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.LinkedList;\n\npublic class LinkedListExample {\n    public static void main(String&#91;] args) {\n        LinkedList&lt;String&gt; animals = new LinkedList&lt;&gt;();\n\n        \/\/ Adding elements\n        animals.add(\"Dog\");\n        animals.add(\"Cat\");\n        animals.add(\"Horse\");\n\n        \/\/ Iterating through the list\n        for (String animal : animals) {\n            System.out.println(animal);\n        }\n\n        \/\/ Adding elements at the beginning and end\n        animals.addFirst(\"Elephant\");\n        animals.addLast(\"Zebra\");\n        System.out.println(\"After adding elements at beginning and end: \" + animals);\n\n        \/\/ Removing first and last elements\n        animals.removeFirst();\n        animals.removeLast();\n        System.out.println(\"After removing first and last elements: \" + animals);\n\n        \/\/ Checking size\n        System.out.println(\"Size of the list: \" + animals.size());\n    }\n}\n<\/code><\/pre>\n\n\n\n<p><strong>3. Write a Java program to demonstrate the use of <code>HashSet<\/code>.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.HashSet;\nimport java.util.Set;\n\npublic class HashSetExample {\n    public static void main(String&#91;] args) {\n        Set&lt;String&gt; countries = new HashSet&lt;&gt;();\n\n        \/\/ Adding elements\n        countries.add(\"USA\");\n        countries.add(\"Canada\");\n        countries.add(\"Mexico\");\n\n        \/\/ Attempting to add a duplicate element\n        countries.add(\"USA\");\n\n        \/\/ Iterating through the set\n        for (String country : countries) {\n            System.out.println(country);\n        }\n\n        \/\/ Checking if an element exists\n        System.out.println(\"Contains Canada? \" + countries.contains(\"Canada\"));\n\n        \/\/ Removing an element\n        countries.remove(\"Mexico\");\n        System.out.println(\"After removing Mexico: \" + countries);\n\n        \/\/ Checking size\n        System.out.println(\"Size of the set: \" + countries.size());\n    }\n}\n<\/code><\/pre>\n\n\n\n<p><strong>4. Write a Java program to demonstrate the use of <code>TreeSet<\/code>.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.TreeSet;\n\npublic class TreeSetExample {\n    public static void main(String&#91;] args) {\n        TreeSet&lt;Integer&gt; numbers = new TreeSet&lt;&gt;();\n\n        \/\/ Adding elements\n        numbers.add(10);\n        numbers.add(5);\n        numbers.add(15);\n\n        \/\/ Iterating through the set\n        for (Integer number : numbers) {\n            System.out.println(number);\n        }\n\n        \/\/ Getting the first and last elements\n        System.out.println(\"First element: \" + numbers.first());\n        System.out.println(\"Last element: \" + numbers.last());\n\n        \/\/ Removing an element\n        numbers.remove(10);\n        System.out.println(\"After removing 10: \" + numbers);\n\n        \/\/ Checking size\n        System.out.println(\"Size of the set: \" + numbers.size());\n    }\n}\n<\/code><\/pre>\n\n\n\n<p><strong>5. Write a Java program to demonstrate the use of <code>HashMap<\/code>.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.HashMap;\nimport java.util.Map;\n\npublic class HashMapExample {\n    public static void main(String&#91;] args) {\n        Map&lt;String, Integer&gt; ages = new HashMap&lt;&gt;();\n\n        \/\/ Adding elements\n        ages.put(\"Alice\", 30);\n        ages.put(\"Bob\", 25);\n        ages.put(\"Charlie\", 35);\n\n        \/\/ Iterating through the map\n        for (Map.Entry&lt;String, Integer&gt; entry : ages.entrySet()) {\n            System.out.println(entry.getKey() + \": \" + entry.getValue());\n        }\n\n        \/\/ Getting an element\n        System.out.println(\"Alice's age: \" + ages.get(\"Alice\"));\n\n        \/\/ Removing an element\n        ages.remove(\"Bob\");\n        System.out.println(\"After removing Bob: \" + ages);\n\n        \/\/ Checking size\n        System.out.println(\"Size of the map: \" + ages.size());\n    }\n}\n<\/code><\/pre>\n\n\n\n<p><strong>6. Write a Java program to demonstrate the use of <code>TreeMap<\/code>.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.Map;\nimport java.util.TreeMap;\n\npublic class TreeMapExample {\n    public static void main(String&#91;] args) {\n        TreeMap&lt;String, Integer&gt; scores = new TreeMap&lt;&gt;();\n\n        \/\/ Adding elements\n        scores.put(\"Alice\", 85);\n        scores.put(\"Bob\", 90);\n        scores.put(\"Charlie\", 80);\n\n        \/\/ Iterating through the map\n        for (Map.Entry&lt;String, Integer&gt; entry : scores.entrySet()) {\n            System.out.println(entry.getKey() + \": \" + entry.getValue());\n        }\n\n        \/\/ Getting the first and last entries\n        System.out.println(\"First entry: \" + scores.firstEntry());\n        System.out.println(\"Last entry: \" + scores.lastEntry());\n\n        \/\/ Removing an element\n        scores.remove(\"Bob\");\n        System.out.println(\"After removing Bob: \" + scores);\n\n        \/\/ Checking size\n        System.out.println(\"Size of the map: \" + scores.size());\n    }\n}\n<\/code><\/pre>\n\n\n\n<p><strong>7. Write a Java program to demonstrate the use of <code>PriorityQueue<\/code>.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.PriorityQueue;\n\npublic class PriorityQueueExample {\n    public static void main(String&#91;] args) {\n        PriorityQueue&lt;Integer&gt; queue = new PriorityQueue&lt;&gt;();\n\n        \/\/ Adding elements\n        queue.add(10);\n        queue.add(5);\n        queue.add(15);\n\n        \/\/ Iterating through the queue\n        while (!queue.isEmpty()) {\n            System.out.println(queue.poll());\n        }\n    }\n}\n<\/code><\/pre>\n\n\n\n<p><strong>8. Write a Java program to demonstrate the use of <code>Stack<\/code><\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.Stack;\n\npublic class StackExample {\n    public static void main(String&#91;] args) {\n        Stack&lt;String&gt; stack = new Stack&lt;&gt;();\n\n        \/\/ Pushing elements onto the stack\n        stack.push(\"Apple\");\n        stack.push(\"Banana\");\n        stack.push(\"Cherry\");\n\n        \/\/ Popping elements from the stack\n        while (!stack.isEmpty()) {\n            System.out.println(stack.pop());\n        }\n    }\n}\n<\/code><\/pre>\n\n\n\n<p><strong>9. Write a Java program to demonstrate the use of <code>Queue<\/code> implemented using <code>LinkedList<\/code>.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.LinkedList;\nimport java.util.Queue;\n\npublic class QueueExample {\n    public static void main(String&#91;] args) {\n        Queue&lt;String&gt; queue = new LinkedList&lt;&gt;();\n\n        \/\/ Adding elements\n        queue.add(\"Apple\");\n        queue.add(\"Banana\");\n        queue.add(\"Cherry\");\n\n        \/\/ Polling elements from the queue\n        while (!queue.isEmpty()) {\n            System.out.println(queue.poll());\n        }\n    }\n}\n<\/code><\/pre>\n\n\n\n<p><strong>10. Write a Java program to demonstrate the use of <code>Deque<\/code> implemented using <code>ArrayDeque<\/code><\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.ArrayDeque;\nimport java.util.Deque;\n\npublic class DequeExample {\n    public static void main(String&#91;] args) {\n        Deque&lt;String&gt; deque = new ArrayDeque&lt;&gt;();\n\n        \/\/ Adding elements to both ends\n        deque.addFirst(\"Apple\");\n        deque.addLast(\"Banana\");\n        deque.addFirst(\"Cherry\");\n\n        \/\/ Iterating through the deque\n        while (!deque.isEmpty()) {\n            System.out.println(deque.pollFirst());\n        }\n    }\n}\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Java 8 Features<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">1. Lambda Expressions<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to demonstrate the use of lambda expressions.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.Arrays;\nimport java.util.List;\n\npublic class LambdaExample {\n    public static void main(String&#91;] args) {\n        List&lt;String&gt; names = Arrays.asList(\"Alice\", \"Bob\", \"Charlie\");\n\n        \/\/ Using lambda expression to iterate through the list\n        names.forEach(name -&gt; System.out.println(name));\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">2. Functional Interfaces<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to demonstrate the use of functional interfaces.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.function.Predicate;\n\npublic class FunctionalInterfaceExample {\n    public static void main(String&#91;] args) {\n        Predicate&lt;Integer&gt; isEven = number -&gt; number % 2 == 0;\n\n        System.out.println(\"Is 4 even? \" + isEven.test(4));\n        System.out.println(\"Is 5 even? \" + isEven.test(5));\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">3. Streams API<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to demonstrate the use of the Streams API.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\npublic class StreamsExample {\n    public static void main(String&#91;] args) {\n        List&lt;Integer&gt; numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);\n\n        \/\/ Using Streams API to filter even numbers and collect them into a list\n        List&lt;Integer&gt; evenNumbers = numbers.stream()\n                                           .filter(number -&gt; number % 2 == 0)\n                                           .collect(Collectors.toList());\n\n        System.out.println(\"Even numbers: \" + evenNumbers);\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">4. Optional Class<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to demonstrate the use of the <code>Optional<\/code> class.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.Optional;\n\npublic class OptionalExample {\n    public static void main(String&#91;] args) {\n        String&#91;] words = new String&#91;10];\n        words&#91;2] = \"hello\";\n\n        Optional&lt;String&gt; checkNull = Optional.ofNullable(words&#91;2]);\n        checkNull.ifPresent(System.out::println);\n\n        \/\/ Using Optional to handle a potential null value\n        Optional&lt;String&gt; word = Optional.ofNullable(words&#91;5]);\n        String result = word.orElse(\"Default value\");\n        System.out.println(result);\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">5. Method References<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to demonstrate the use of method references.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.Arrays;\nimport java.util.List;\n\npublic class MethodReferenceExample {\n    public static void main(String&#91;] args) {\n        List&lt;String&gt; names = Arrays.asList(\"Alice\", \"Bob\", \"Charlie\");\n\n        \/\/ Using method reference to iterate through the list\n        names.forEach(System.out::println);\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">6. Default Methods in Interfaces<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to demonstrate default methods in interfaces.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>interface Vehicle {\n    default void print() {\n        System.out.println(\"I am a vehicle.\");\n    }\n\n    static void blowHorn() {\n        System.out.println(\"Blowing horn!!!\");\n    }\n}\n\nclass Car implements Vehicle {\n    @Override\n    public void print() {\n        System.out.println(\"I am a car.\");\n    }\n}\n\npublic class DefaultMethodsExample {\n    public static void main(String&#91;] args) {\n        Vehicle car = new Car();\n        car.print(); \/\/ Calls the overridden method in Car\n        Vehicle.blowHorn(); \/\/ Calls the static method in Vehicle interface\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">7. New Date and Time API<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to demonstrate the new Date and Time API.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.time.LocalDate;\nimport java.time.LocalDateTime;\nimport java.time.LocalTime;\nimport java.time.format.DateTimeFormatter;\n\npublic class DateTimeExample {\n    public static void main(String&#91;] args) {\n        LocalDate date = LocalDate.now();\n        System.out.println(\"Current Date: \" + date);\n\n        LocalTime time = LocalTime.now();\n        System.out.println(\"Current Time: \" + time);\n\n        LocalDateTime dateTime = LocalDateTime.now();\n        System.out.println(\"Current DateTime: \" + dateTime);\n\n        \/\/ Formatting DateTime\n        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"dd-MM-yyyy HH:mm:ss\");\n        String formattedDateTime = dateTime.format(formatter);\n        System.out.println(\"Formatted DateTime: \" + formattedDateTime);\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">8. Stream Reduction<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to demonstrate stream reduction.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.Arrays;\nimport java.util.List;\n\npublic class StreamReductionExample {\n    public static void main(String&#91;] args) {\n        List&lt;Integer&gt; numbers = Arrays.asList(1, 2, 3, 4, 5);\n\n        \/\/ Using reduce() to calculate the sum of the list\n        int sum = numbers.stream()\n                         .reduce(0, (a, b) -&gt; a + b);\n\n        System.out.println(\"Sum: \" + sum);\n\n        \/\/ Using method reference with reduce()\n        int product = numbers.stream()\n                             .reduce(1, Math::multiplyExact);\n\n        System.out.println(\"Product: \" + product);\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">9. Parallel Streams<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to demonstrate parallel streams.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.Arrays;\nimport java.util.List;\n\npublic class ParallelStreamsExample {\n    public static void main(String&#91;] args) {\n        List&lt;Integer&gt; numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);\n\n        \/\/ Using parallel stream to filter even numbers\n        List&lt;Integer&gt; evenNumbers = numbers.parallelStream()\n                                           .filter(number -&gt; number % 2 == 0)\n                                           .collect(Collectors.toList());\n\n        System.out.println(\"Even numbers: \" + evenNumbers);\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">10. Collectors<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to demonstrate the use of <code>Collectors<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.Arrays;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\npublic class CollectorsExample {\n    public static void main(String&#91;] args) {\n        List&lt;String&gt; names = Arrays.asList(\"Alice\", \"Bob\", \"Charlie\", \"David\", \"Edward\");\n\n        \/\/ Using Collectors to group names by their starting letter\n        Map&lt;Character, List&lt;String&gt;&gt; groupedByFirstLetter = names.stream()\n                .collect(Collectors.groupingBy(name -&gt; name.charAt(0)));\n\n        groupedByFirstLetter.forEach((letter, group) -&gt; {\n            System.out.println(letter + \": \" + group);\n        });\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">11. Stream Operations: <code>map()<\/code><\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to demonstrate the use of the <code>map()<\/code> method in streams.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\npublic class StreamMapExample {\n    public static void main(String&#91;] args) {\n        List&lt;String&gt; names = Arrays.asList(\"alice\", \"bob\", \"charlie\");\n\n        \/\/ Using map() to convert all names to uppercase\n        List&lt;String&gt; upperCaseNames = names.stream()\n                                           .map(String::toUpperCase)\n                                           .collect(Collectors.toList());\n\n        System.out.println(upperCaseNames);\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">12. Stream Operations: <code>flatMap()<\/code><\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to demonstrate the use of the <code>flatMap()<\/code> method in streams.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\npublic class StreamFlatMapExample {\n    public static void main(String&#91;] args) {\n        List&lt;List&lt;String&gt;&gt; namesList = Arrays.asList(\n            Arrays.asList(\"Alice\", \"Bob\"),\n            Arrays.asList(\"Charlie\", \"David\"),\n            Arrays.asList(\"Edward\", \"Frank\")\n        );\n\n        \/\/ Using flatMap() to flatten the list of lists into a single list\n        List&lt;String&gt; flatList = namesList.stream()\n                                         .flatMap(List::stream)\n                                         .collect(Collectors.toList());\n\n        System.out.println(flatList);\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">13. Stream Operations: <code>sorted()<\/code><\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to demonstrate the use of the <code>sorted()<\/code> method in streams.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.Arrays;\nimport java.util.List;\n\npublic class StreamSortedExample {\n    public static void main(String&#91;] args) {\n        List&lt;Integer&gt; numbers = Arrays.asList(5, 3, 9, 1, 4, 2);\n\n        \/\/ Using sorted() to sort the list in natural order\n        List&lt;Integer&gt; sortedNumbers = numbers.stream()\n                                             .sorted()\n                                             .collect(Collectors.toList());\n\n        System.out.println(sortedNumbers);\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">14. Stream Operations: <code>distinct()<\/code><\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to demonstrate the use of the <code>distinct()<\/code> method in streams.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.Arrays;\nimport java.util.List;\n\npublic class StreamDistinctExample {\n    public static void main(String&#91;] args) {\n        List&lt;Integer&gt; numbers = Arrays.asList(1, 2, 3, 2, 4, 5, 1, 6);\n\n        \/\/ Using distinct() to remove duplicates from the list\n        List&lt;Integer&gt; distinctNumbers = numbers.stream()\n                                               .distinct()\n                                               .collect(Collectors.toList());\n\n        System.out.println(distinctNumbers);\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">15. Stream Operations: <code>peek()<\/code><\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to demonstrate the use of the <code>peek()<\/code> method in streams.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.Arrays;\nimport java.util.List;\n\npublic class StreamPeekExample {\n    public static void main(String&#91;] args) {\n        List&lt;String&gt; names = Arrays.asList(\"Alice\", \"Bob\", \"Charlie\");\n\n        \/\/ Using peek() to log the elements during the stream processing\n        List&lt;String&gt; processedNames = names.stream()\n                                           .peek(name -&gt; System.out.println(\"Processing: \" + name))\n                                           .map(String::toUpperCase)\n                                           .collect(Collectors.toList());\n\n        System.out.println(processedNames);\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">16. Stream Operations: <code>count()<\/code><\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to demonstrate the use of the <code>count()<\/code> method in streams.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.Arrays;\nimport java.util.List;\n\npublic class StreamCountExample {\n    public static void main(String&#91;] args) {\n        List&lt;String&gt; names = Arrays.asList(\"Alice\", \"Bob\", \"Charlie\", \"David\", \"Edward\");\n\n        \/\/ Using count() to count the number of elements in the stream\n        long count = names.stream()\n                          .filter(name -&gt; name.length() &gt; 3)\n                          .count();\n\n        System.out.println(\"Number of names longer than 3 characters: \" + count);\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">17. Stream Operations: <code>findFirst()<\/code><\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to demonstrate the use of the <code>findFirst()<\/code> method in streams.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.Arrays;\nimport java.util.List;\n\npublic class StreamFindFirstExample {\n    public static void main(String&#91;] args) {\n        List&lt;String&gt; names = Arrays.asList(\"Alice\", \"Bob\", \"Charlie\");\n\n        \/\/ Using findFirst() to find the first element in the stream\n        String firstElement = names.stream()\n                                   .findFirst()\n                                   .orElse(\"No elements\");\n\n        System.out.println(\"First element: \" + firstElement);\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">18. Stream Operations: <code>reduce()<\/code><\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to demonstrate the use of the <code>reduce()<\/code> method in streams.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.Arrays;\nimport java.util.List;\n\npublic class StreamReduceExample {\n    public static void main(String&#91;] args) {\n        List&lt;Integer&gt; numbers = Arrays.asList(1, 2, 3, 4, 5);\n\n        \/\/ Using reduce() to calculate the sum of all elements in the list\n        int sum = numbers.stream()\n                         .reduce(0, (a, b) -&gt; a + b);\n\n        System.out.println(\"Sum: \" + sum);\n\n        \/\/ Using method reference with reduce()\n        int product = numbers.stream()\n                             .reduce(1, Math::multiplyExact);\n\n        System.out.println(\"Product: \" + product);\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">19. Stream Operations: <code>collect()<\/code><\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to demonstrate the use of the <code>collect()<\/code> method in streams.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\npublic class StreamCollectExample {\n    public static void main(String&#91;] args) {\n        List&lt;String&gt; names = Arrays.asList(\"Alice\", \"Bob\", \"Charlie\");\n\n        \/\/ Using collect() to convert the stream into a list\n        List&lt;String&gt; upperCaseNames = names.stream()\n                                           .map(String::toUpperCase)\n                                           .collect(Collectors.toList());\n\n        System.out.println(upperCaseNames);\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">20. Stream Operations: <code>groupingBy()<\/code><\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to demonstrate the use of the <code>groupingBy()<\/code> method in streams.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.Arrays;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\npublic class StreamGroupingByExample {\n    public static void main(String&#91;] args) {\n        List&lt;String&gt; names = Arrays.asList(\"Alice\", \"Bob\", \"Charlie\", \"David\", \"Edward\");\n\n        \/\/ Using groupingBy() to group names by their starting letter\n        Map&lt;Character, List&lt;String&gt;&gt; groupedByFirstLetter = names.stream()\n                .collect(Collectors.groupingBy(name -&gt; name.charAt(0)));\n\n        groupedByFirstLetter.forEach((letter, group) -&gt; {\n            System.out.println(letter + \": \" + group);\n        });\n    }\n}\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">JDBC programs in Java<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">1. Connect to a Database<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to demonstrate connecting to a database using JDBC<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\n\npublic class JdbcConnectExample {\n    public static void main(String&#91;] args) {\n        String url = \"jdbc:mysql:\/\/localhost:3306\/mydatabase\";\n        String username = \"root\";\n        String password = \"password\";\n\n        try (Connection connection = DriverManager.getConnection(url, username, password)) {\n            if (connection != null) {\n                System.out.println(\"Connected to the database!\");\n            } else {\n                System.out.println(\"Failed to connect to the database.\");\n            }\n        } catch (SQLException e) {\n            e.printStackTrace();\n        }\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">2. Create a Table<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to create a table using JDBC.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class JdbcCreateTableExample {\n    public static void main(String&#91;] args) {\n        String url = \"jdbc:mysql:\/\/localhost:3306\/mydatabase\";\n        String username = \"root\";\n        String password = \"password\";\n\n        String createTableSQL = \"CREATE TABLE IF NOT EXISTS users (\"\n                + \"id INT AUTO_INCREMENT PRIMARY KEY, \"\n                + \"name VARCHAR(100) NOT NULL, \"\n                + \"email VARCHAR(100) NOT NULL UNIQUE, \"\n                + \"created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)\";\n\n        try (Connection connection = DriverManager.getConnection(url, username, password);\n             Statement statement = connection.createStatement()) {\n\n            statement.execute(createTableSQL);\n            System.out.println(\"Table 'users' created successfully.\");\n        } catch (SQLException e) {\n            e.printStackTrace();\n        }\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">3. Insert Data into a Table<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to insert data into a table using JDBC.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.SQLException;\n\npublic class JdbcInsertExample {\n    public static void main(String&#91;] args) {\n        String url = \"jdbc:mysql:\/\/localhost:3306\/mydatabase\";\n        String username = \"root\";\n        String password = \"password\";\n\n        String insertSQL = \"INSERT INTO users (name, email) VALUES (?, ?)\";\n\n        try (Connection connection = DriverManager.getConnection(url, username, password);\n             PreparedStatement preparedStatement = connection.prepareStatement(insertSQL)) {\n\n            preparedStatement.setString(1, \"John Doe\");\n            preparedStatement.setString(2, \"john.doe@example.com\");\n\n            int row = preparedStatement.executeUpdate();\n            System.out.println(row + \" row(s) inserted.\");\n        } catch (SQLException e) {\n            e.printStackTrace();\n        }\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">4. Retrieve Data from a Table<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to retrieve data from a table using JDBC.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class JdbcSelectExample {\n    public static void main(String&#91;] args) {\n        String url = \"jdbc:mysql:\/\/localhost:3306\/mydatabase\";\n        String username = \"root\";\n        String password = \"password\";\n\n        String selectSQL = \"SELECT * FROM users\";\n\n        try (Connection connection = DriverManager.getConnection(url, username, password);\n             Statement statement = connection.createStatement();\n             ResultSet resultSet = statement.executeQuery(selectSQL)) {\n\n            while (resultSet.next()) {\n                int id = resultSet.getInt(\"id\");\n                String name = resultSet.getString(\"name\");\n                String email = resultSet.getString(\"email\");\n                System.out.println(\"ID: \" + id + \", Name: \" + name + \", Email: \" + email);\n            }\n        } catch (SQLException e) {\n            e.printStackTrace();\n        }\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">5. Update Data in a Table<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to update data in a table using JDBC.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.SQLException;\n\npublic class JdbcUpdateExample {\n    public static void main(String&#91;] args) {\n        String url = \"jdbc:mysql:\/\/localhost:3306\/mydatabase\";\n        String username = \"root\";\n        String password = \"password\";\n\n        String updateSQL = \"UPDATE users SET email = ? WHERE name = ?\";\n\n        try (Connection connection = DriverManager.getConnection(url, username, password);\n             PreparedStatement preparedStatement = connection.prepareStatement(updateSQL)) {\n\n            preparedStatement.setString(1, \"new.email@example.com\");\n            preparedStatement.setString(2, \"John Doe\");\n\n            int row = preparedStatement.executeUpdate();\n            System.out.println(row + \" row(s) updated.\");\n        } catch (SQLException e) {\n            e.printStackTrace();\n        }\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">6. Delete Data from a Table<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to delete data from a table using JDBC.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.SQLException;\n\npublic class JdbcDeleteExample {\n    public static void main(String&#91;] args) {\n        String url = \"jdbc:mysql:\/\/localhost:3306\/mydatabase\";\n        String username = \"root\";\n        String password = \"password\";\n\n        String deleteSQL = \"DELETE FROM users WHERE name = ?\";\n\n        try (Connection connection = DriverManager.getConnection(url, username, password);\n             PreparedStatement preparedStatement = connection.prepareStatement(deleteSQL)) {\n\n            preparedStatement.setString(1, \"John Doe\");\n\n            int row = preparedStatement.executeUpdate();\n            System.out.println(row + \" row(s) deleted.\");\n        } catch (SQLException e) {\n            e.printStackTrace();\n        }\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">7. Handling Transactions<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to demonstrate transaction handling using JDBC.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.SQLException;\n\npublic class JdbcTransactionExample {\n    public static void main(String&#91;] args) {\n        String url = \"jdbc:mysql:\/\/localhost:3306\/mydatabase\";\n        String username = \"root\";\n        String password = \"password\";\n\n        String insertSQL1 = \"INSERT INTO users (name, email) VALUES (?, ?)\";\n        String insertSQL2 = \"INSERT INTO users (name, email) VALUES (?, ?)\";\n\n        try (Connection connection = DriverManager.getConnection(url, username, password)) {\n            connection.setAutoCommit(false);\n\n            try (PreparedStatement preparedStatement1 = connection.prepareStatement(insertSQL1);\n                 PreparedStatement preparedStatement2 = connection.prepareStatement(insertSQL2)) {\n\n                preparedStatement1.setString(1, \"Alice\");\n                preparedStatement1.setString(2, \"alice@example.com\");\n                preparedStatement1.executeUpdate();\n\n                preparedStatement2.setString(1, \"Bob\");\n                preparedStatement2.setString(2, \"bob@example.com\");\n                preparedStatement2.executeUpdate();\n\n                connection.commit();\n                System.out.println(\"Transaction committed successfully.\");\n            } catch (SQLException e) {\n                connection.rollback();\n                System.out.println(\"Transaction rolled back.\");\n                e.printStackTrace();\n            }\n        } catch (SQLException e) {\n            e.printStackTrace();\n        }\n    }\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">8. Batch Processing<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Java program to demonstrate batch processing using JDBC.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.SQLException;\n\npublic class JdbcBatchExample {\n    public static void main(String&#91;] args) {\n        String url = \"jdbc:mysql:\/\/localhost:3306\/mydatabase\";\n        String username = \"root\";\n        String password = \"password\";\n\n        String insertSQL = \"INSERT INTO users (name, email) VALUES (?, ?)\";\n\n        try (Connection connection = DriverManager.getConnection(url, username, password);\n             PreparedStatement preparedStatement = connection.prepareStatement(insertSQL)) {\n\n            connection.setAutoCommit(false);\n\n            preparedStatement.setString(1, \"User1\");\n            preparedStatement.setString(2, \"user1@example.com\");\n            preparedStatement.addBatch();\n\n            preparedStatement.setString(1, \"User2\");\n            preparedStatement.setString(2, \"user2@example.com\");\n            preparedStatement.addBatch();\n\n            preparedStatement.setString(1, \"User3\");\n            preparedStatement.setString(2, \"user3@example.com\");\n            preparedStatement.addBatch();\n\n            int&#91;] updateCounts = preparedStatement.executeBatch();\n            connection.commit();\n            System.out.println(\"Batch executed successfully. \" + updateCounts.length + \" rows affected.\");\n        } catch (SQLException e) {\n            e.printStackTrace();\n        }\n    }\n}\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Spring Boot MVC examples<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">1. Setting up a Spring Boot Application<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a simple Spring Boot application with an MVC controller.<\/p>\n\n\n\n<p><strong>Answer:<\/strong> <strong>Step 1:<\/strong> Create a new Spring Boot project using <a href=\"https:\/\/start.spring.io\/\">Spring Initializr<\/a>. Add dependencies for Spring Web.<\/p>\n\n\n\n<p><strong>Step 2:<\/strong> Create the main application class.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class SpringBootMvcExampleApplication {\n    public static void main(String&#91;] args) {\n        SpringApplication.run(SpringBootMvcExampleApplication.class, args);\n    }\n}\n<\/code><\/pre>\n\n\n\n<p><strong>Step 3:<\/strong> Create a simple MVC controller.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import org.springframework.stereotype.Controller;\nimport org.springframework.ui.Model;\nimport org.springframework.web.bind.annotation.GetMapping;\n\n@Controller\npublic class HelloController {\n\n    @GetMapping(\"\/hello\")\n    public String hello(Model model) {\n        model.addAttribute(\"message\", \"Hello, Spring Boot MVC!\");\n        return \"hello\";\n    }\n}\n<\/code><\/pre>\n\n\n\n<p><strong>Step 4:<\/strong> Create a Thymeleaf template (<code>hello.html<\/code>) in <code>src\/main\/resources\/templates<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;!DOCTYPE html&gt;\n&lt;html xmlns:th=\"http:\/\/www.thymeleaf.org\"&gt;\n&lt;head&gt;\n    &lt;title&gt;Hello Page&lt;\/title&gt;\n&lt;\/head&gt;\n&lt;body&gt;\n    &lt;h1 th:text=\"${message}\"&gt;&lt;\/h1&gt;\n&lt;\/body&gt;\n&lt;\/html&gt;\n<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2. Handling Form Submissions<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Spring Boot MVC application to handle form submissions.<\/p>\n\n\n\n<p><strong>Answer:<\/strong> <strong>Step 1:<\/strong> Create a form template (<code>form.html<\/code>).<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;!DOCTYPE html&gt;\n&lt;html xmlns:th=\"http:\/\/www.thymeleaf.org\"&gt;\n&lt;head&gt;\n    &lt;title&gt;Form Page&lt;\/title&gt;\n&lt;\/head&gt;\n&lt;body&gt;\n    &lt;form action=\"#\" th:action=\"@{\/submitForm}\" th:object=\"${user}\" method=\"post\"&gt;\n        &lt;label for=\"name\"&gt;Name:&lt;\/label&gt;\n        &lt;input type=\"text\" id=\"name\" th:field=\"*{name}\"\/&gt;\n        &lt;br\/&gt;\n        &lt;label for=\"email\"&gt;Email:&lt;\/label&gt;\n        &lt;input type=\"text\" id=\"email\" th:field=\"*{email}\"\/&gt;\n        &lt;br\/&gt;\n        &lt;button type=\"submit\"&gt;Submit&lt;\/button&gt;\n    &lt;\/form&gt;\n&lt;\/body&gt;\n&lt;\/html&gt;\n<\/code><\/pre>\n\n\n\n<p><strong>Step 2:<\/strong> Create a result template (<code>result.html<\/code>).<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;!DOCTYPE html&gt;\n&lt;html xmlns:th=\"http:\/\/www.thymeleaf.org\"&gt;\n&lt;head&gt;\n    &lt;title&gt;Result Page&lt;\/title&gt;\n&lt;\/head&gt;\n&lt;body&gt;\n    &lt;h1&gt;Form Submitted Successfully!&lt;\/h1&gt;\n    &lt;p&gt;Name: &lt;span th:text=\"${user.name}\"&gt;&lt;\/span&gt;&lt;\/p&gt;\n    &lt;p&gt;Email: &lt;span th:text=\"${user.email}\"&gt;&lt;\/span&gt;&lt;\/p&gt;\n&lt;\/body&gt;\n&lt;\/html&gt;\n<\/code><\/pre>\n\n\n\n<p><strong>Step 3:<\/strong> Create a <code>User<\/code> class to hold form data.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class User {\r\n    private String name;\r\n    private String email;\r\n\r\n    \/\/ Getters and setters\r\n    public String getName() {\r\n        return name;\r\n    }\r\n\r\n    public void setName(String name) {\r\n        this.name = name;\r\n    }\r\n\r\n    public String getEmail() {\r\n        return email;\r\n    }\r\n\r\n    public void setEmail(String email) {\r\n        this.email = email;\r\n    }\r\n}\r<\/code><\/pre>\n\n\n\n<p><strong>Step 4:<\/strong> Create a controller to handle form submissions.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import org.springframework.stereotype.Controller;\r\nimport org.springframework.ui.Model;\r\nimport org.springframework.web.bind.annotation.GetMapping;\r\nimport org.springframework.web.bind.annotation.ModelAttribute;\r\nimport org.springframework.web.bind.annotation.PostMapping;\r\n\r\n@Controller\r\npublic class FormController {\r\n\r\n    @GetMapping(\"\/form\")\r\n    public String showForm(Model model) {\r\n        model.addAttribute(\"user\", new User());\r\n        return \"form\";\r\n    }\r\n\r\n    @PostMapping(\"\/submitForm\")\r\n    public String submitForm(@ModelAttribute User user, Model model) {\r\n        model.addAttribute(\"user\", user);\r\n        return \"result\";\r\n    }\r\n}\r<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">3. REST API with Spring Boot<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a simple REST API with Spring Boot.<\/p>\n\n\n\n<p><strong>Answer:<\/strong> <strong>Step 1:<\/strong> Create a <code>User<\/code> model class.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class User {\r\n    private Long id;\r\n    private String name;\r\n    private String email;\r\n\r\n    \/\/ Constructors, getters, and setters\r\n    public User() {}\r\n\r\n    public User(Long id, String name, String email) {\r\n        this.id = id;\r\n        this.name = name;\r\n        this.email = email;\r\n    }\r\n\r\n    public Long getId() {\r\n        return id;\r\n    }\r\n\r\n    public void setId(Long id) {\r\n        this.id = id;\r\n    }\r\n\r\n    public String getName() {\r\n        return name;\r\n    }\r\n\r\n    public void setName(String name) {\r\n        this.name = name;\r\n    }\r\n\r\n    public String getEmail() {\r\n        return email;\r\n    }\r\n\r\n    public void setEmail(String email) {\r\n        this.email = email;\r\n    }\r\n}\r<\/code><\/pre>\n\n\n\n<p><strong>Step 2:<\/strong> Create a <code>UserController<\/code> class to handle RESTful requests.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import org.springframework.web.bind.annotation.GetMapping;\r\nimport org.springframework.web.bind.annotation.PathVariable;\r\nimport org.springframework.web.bind.annotation.PostMapping;\r\nimport org.springframework.web.bind.annotation.RequestBody;\r\nimport org.springframework.web.bind.annotation.RestController;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\n@RestController\r\npublic class UserController {\r\n\r\n    private List&lt;User> users = new ArrayList&lt;>();\r\n\r\n    @GetMapping(\"\/users\")\r\n    public List&lt;User> getUsers() {\r\n        return users;\r\n    }\r\n\r\n    @PostMapping(\"\/users\")\r\n    public User addUser(@RequestBody User user) {\r\n        user.setId((long) (users.size() + 1));\r\n        users.add(user);\r\n        return user;\r\n    }\r\n\r\n    @GetMapping(\"\/users\/{id}\")\r\n    public User getUserById(@PathVariable Long id) {\r\n        return users.stream()\r\n                    .filter(user -> user.getId().equals(id))\r\n                    .findFirst()\r\n                    .orElse(null);\r\n    }\r\n}\r<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">4. Exception Handling in Spring Boot<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Spring Boot application demonstrating exception handling with <code>@ControllerAdvice<\/code>.<\/p>\n\n\n\n<p><strong>Answer:<\/strong> <strong>Step 1:<\/strong> Create a custom exception class.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class UserNotFoundException extends RuntimeException {\r\n    public UserNotFoundException(String message) {\r\n        super(message);\r\n    }\r\n}\r<\/code><\/pre>\n\n\n\n<p><strong>Step 2:<\/strong> Modify the <code>UserController<\/code> to throw the custom exception.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import org.springframework.web.bind.annotation.*;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\n@RestController\r\npublic class UserController {\r\n\r\n    private List&lt;User> users = new ArrayList&lt;>();\r\n\r\n    @GetMapping(\"\/users\")\r\n    public List&lt;User> getUsers() {\r\n        return users;\r\n    }\r\n\r\n    @PostMapping(\"\/users\")\r\n    public User addUser(@RequestBody User user) {\r\n        user.setId((long) (users.size() + 1));\r\n        users.add(user);\r\n        return user;\r\n    }\r\n\r\n    @GetMapping(\"\/users\/{id}\")\r\n    public User getUserById(@PathVariable Long id) {\r\n        return users.stream()\r\n                    .filter(user -> user.getId().equals(id))\r\n                    .findFirst()\r\n                    .orElseThrow(() -> new UserNotFoundException(\"User not found with id: \" + id));\r\n    }\r\n}\r\n<\/code><\/pre>\n\n\n\n<p><strong>Step 3:<\/strong> Create a <code>GlobalExceptionHandler<\/code> class with <code>@ControllerAdvice<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import org.springframework.http.HttpStatus;\r\nimport org.springframework.http.ResponseEntity;\r\nimport org.springframework.web.bind.annotation.ControllerAdvice;\r\nimport org.springframework.web.bind.annotation.ExceptionHandler;\r\nimport org.springframework.web.bind.annotation.ResponseStatus;\r\n\r\n@ControllerAdvice\r\npublic class GlobalExceptionHandler {\r\n\r\n    @ExceptionHandler(UserNotFoundException.class)\r\n    @ResponseStatus(HttpStatus.NOT_FOUND)\r\n    public ResponseEntity&lt;String> handleUserNotFoundException(UserNotFoundException ex) {\r\n        return new ResponseEntity&lt;>(ex.getMessage(), HttpStatus.NOT_FOUND);\r\n    }\r\n\r\n    \/\/ Other exception handlers can be added here\r\n}\r<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">5. Using Spring Data JPA<\/h3>\n\n\n\n<p><strong>Question:<\/strong> Write a Spring Boot application using Spring Data JPA to perform CRUD operations.<\/p>\n\n\n\n<p><strong>Answer:<\/strong> <strong>Step 1:<\/strong> Add the Spring Data JPA dependency in <code>pom.xml<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;dependency>\r\n    &lt;groupId>org.springframework.boot&lt;\/groupId>\r\n    &lt;artifactId>spring-boot-starter-data-jpa&lt;\/artifactId>\r\n&lt;\/dependency>\r\n&lt;dependency>\r\n    &lt;groupId>com.h2database&lt;\/groupId>\r\n    &lt;artifactId>h2&lt;\/artifactId>\r\n    &lt;scope>runtime&lt;\/scope>\r\n&lt;\/dependency>\r<\/code><\/pre>\n\n\n\n<p><strong>Step 2:<\/strong> Create the <code>User<\/code> entity class.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import javax.persistence.Entity;\r\nimport javax.persistence.GeneratedValue;\r\nimport javax.persistence.GenerationType;\r\nimport javax.persistence.Id;\r\n\r\n@Entity\r\npublic class User {\r\n\r\n    @Id\r\n    @GeneratedValue(strategy = GenerationType.IDENTITY)\r\n    private Long id;\r\n    private String name;\r\n    private String email;\r\n\r\n    \/\/ Getters and setters\r\n    public Long getId() {\r\n        return id;\r\n    }\r\n\r\n    public void setId(Long id) {\r\n        this.id = id;\r\n    }\r\n\r\n    public String getName() {\r\n        return name;\r\n    }\r\n\r\n    public void setName(String name) {\r\n        this.name = name;\r\n    }\r\n\r\n    public String getEmail() {\r\n        return email;\r\n    }\r\n\r\n    public void setEmail(String email) {\r\n        this.email = email;\r\n    }\r\n}\r<\/code><\/pre>\n\n\n\n<p><strong>Step 3:<\/strong> Create a <code>UserRepository<\/code> interface<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import org.springframework.data.jpa.repository.JpaRepository;\r\n\r\npublic interface UserRepository extends JpaRepository&lt;User, Long> {\r\n}\r<\/code><\/pre>\n\n\n\n<p><strong>Step 4:<\/strong> Create a <code>UserService<\/code> class<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import org.springframework.beans.factory.annotation.Autowired;\r\nimport org.springframework.stereotype.Service;\r\n\r\nimport java.util.List;\r\nimport java.util.Optional;\r\n\r\n@Service\r\npublic class UserService {\r\n\r\n    @Autowired\r\n    private UserRepository userRepository;\r\n\r\n    public List&lt;User> getAllUsers() {\r\n        return userRepository.findAll();\r\n    }\r\n\r\n    public User getUserById(Long id) {\r\n        return userRepository.findById(id).orElse(null);\r\n    }\r\n\r\n    public User saveUser(User user) {\r\n        return userRepository.save(user);\r\n    }\r\n\r\n    public void deleteUser(Long id) {\r\n        userRepository.deleteById(id);\r\n    }\r\n}\r<\/code><\/pre>\n\n\n\n<p><strong>Step 5:<\/strong> Create a <code>UserController<\/code> class to handle HTTP requests.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import org.springframework.beans.factory.annotation.Autowired;\r\nimport org.springframework.http.ResponseEntity;\r\nimport org.springframework.web.bind.annotation.*;\r\n\r\nimport java.util.List;\r\n\r\n@RestController\r\n@RequestMapping(\"\/users\")\r\npublic class UserController {\r\n\r\n    @Autowired\r\n    private UserService userService;\r\n\r\n    @GetMapping\r\n    public List&lt;User> getAllUsers() {\r\n        return userService.getAllUsers();\r\n    }\r\n\r\n    @GetMapping(\"\/{id}\")\r\n    public ResponseEntity&lt;User> getUserById(@PathVariable Long id) {\r\n        User user = userService.getUserById(id);\r\n        if (user == null) {\r\n            return ResponseEntity.notFound().build();\r\n        }\r\n        return ResponseEntity.ok(user);\r\n    }\r\n\r\n    @PostMapping\r\n    public User createUser(@RequestBody User user) {\r\n        return userService.saveUser(user);\r\n    }\r\n\r\n    @PutMapping(\"\/{id}\")\r\n    public ResponseEntity&lt;User> updateUser(@PathVariable Long id, @RequestBody User user) {\r\n        User existingUser = userService.getUserById(id);\r\n        if (existingUser == null) {\r\n            return ResponseEntity.notFound().build();\r\n        }\r\n        user.setId(id);\r\n        return ResponseEntity.ok(userService.saveUser(user));\r\n    }\r\n\r\n    @DeleteMapping(\"\/{id}\")\r\n    public ResponseEntity&lt;Void> deleteUser(@PathVariable Long id) {\r\n        User existingUser = userService.getUserById(id);\r\n        if (existingUser == null) {\r\n            return ResponseEntity.notFound().build();\r\n        }\r\n        userService.deleteUser(id);\r\n        return ResponseEntity.noContent().build();\r\n    }\r\n}\r<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>1. FizzBuzz Problem Question: Write a Java program that prints the numbers from 1 to&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[18],"tags":[],"_links":{"self":[{"href":"https:\/\/itnotes.apjsoftwares.in\/index.php\/wp-json\/wp\/v2\/posts\/2216"}],"collection":[{"href":"https:\/\/itnotes.apjsoftwares.in\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/itnotes.apjsoftwares.in\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/itnotes.apjsoftwares.in\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/itnotes.apjsoftwares.in\/index.php\/wp-json\/wp\/v2\/comments?post=2216"}],"version-history":[{"count":46,"href":"https:\/\/itnotes.apjsoftwares.in\/index.php\/wp-json\/wp\/v2\/posts\/2216\/revisions"}],"predecessor-version":[{"id":2284,"href":"https:\/\/itnotes.apjsoftwares.in\/index.php\/wp-json\/wp\/v2\/posts\/2216\/revisions\/2284"}],"wp:attachment":[{"href":"https:\/\/itnotes.apjsoftwares.in\/index.php\/wp-json\/wp\/v2\/media?parent=2216"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/itnotes.apjsoftwares.in\/index.php\/wp-json\/wp\/v2\/categories?post=2216"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/itnotes.apjsoftwares.in\/index.php\/wp-json\/wp\/v2\/tags?post=2216"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}