Java Program


Question: Java program to read Properties file.
Answer: Program: public void readPFile() throws Exception{ FileReader reader=new FileReader("data.properties"); Properties p=new Properties(); p.load(reader); String title =p.getProperty("title")); }
Question: Java program for DB connection
Answer: Program: import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DBConnectionExample { // JDBC URL, username, and password of MySQL server String jdbc_URL = "jdbc:mysql://localhost:3306/db_name"; // "jdbc:sqlserver://localhost:1433;databaseName=db_name"; String userName = "username"; String passWord = "password"; String query = "Select * from tableName"; public static void main(String[] args) { // Establish a connection Connection con = DriverManager.getConnection(jdbc_URL, userName, passWord); System.out.println("Connected to the database"); // execute SQL query Statement st = con.createStatement(); // Execute query ResultSet rs = st.executeQuery(query); rs.next(); // Fetch name from db String name= rs.getString("name"); // close statement st.close(); // close connection con.close(); } }
Question: Largest subarray with 0 sum
Answer: Program: int largestLen(int arr[], int n) { HashMap map=new HashMap(); int max=0; int sum=0; map.put(sum,-1); for(int i=0;i 0) { int digit = num % 10; sum += Math.pow(digit, numDigits); num /= 10; } return originalNum == sum; // if true , it is Armstrong Number }
Question: find the second-highest number in an array
Answer: Program: public void secondLargestNumber (int[] numbers) { if (numbers.length < 2) { System.out.println("Array does not contain a second-largest number."); } else { int firstLargest = Integer.MIN_VALUE; int secondLargest = Integer.MIN_VALUE; for (int number : numbers) { if (number > firstLargest) { secondLargest = firstLargest; firstLargest = number; } else if (number > secondLargest && number != firstLargest) { secondLargest = number; }} if (secondLargest == Integer.MIN_VALUE) { System.out.println("There is no second-largest number."); } else { System.out.println("The second-largest number is: " + secondLargest); }} }
Question: find the duplicate characters in a string
Answer: Program: public void duplicateCharactersFinder (String input) { Map charCountMap = new HashMap<>(); // Count the frequency of each character in the string for (char c : input.toCharArray()) { charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1); } // Print duplicate characters System.out.println("Duplicate characters in the string:"); for (Map.Entry entry : charCountMap.entrySet()) { if (entry.getValue() > 1) { System.out.println(entry.getKey() + ": " + entry.getValue() + " times"); } }}
Question: Java Program for the Fibonacci series
Answer: Program: public void printfibonacci(int n) { System.out.println("Fibonacci series up to " + n + " terms:"); for (int i = 0; i < n; i++) { System.out.print(fibonacci(i) + " "); } } public int fibonacci(int n) { if (n <= 1) { return n; } int fib = 0; int prev1 = 1; int prev2 = 0; for (int i = 2; i <= n; i++) { fib = prev1 + prev2; prev2 = prev1; prev1 = fib; } return fib; }
Question: Java Program to find whether a number is prime or not
Answer: Program: public static boolean isPrime(int num) { if (num <= 1) { return false; } // Check for divisibility from 2 to the square root of the number for (int i = 2; i <= Math.sqrt(num); i++) { if (num % i == 0) { return false; // Found a divisor, not a prime } } return true; // No divisors found, it's a prime number }
Question: Java program that sorts HashMap by value.
Answer: Program: public static LinkedHashMap sortHashMapByValue(HashMap map) { // Convert the HashMap to a List of Map.Entry objects List> entryList = new LinkedList<>(map.entrySet()); // Define a custom comparator to sort by values in ascending order Comparator> valueComparator = (entry1, entry2) -> entry1.getValue().compareTo(entry2.getValue()); // Sort the List using the custom comparator entryList.sort(valueComparator); // Create a new LinkedHashMap to store the sorted entries LinkedHashMap sortedMap = new LinkedHashMap<>(); // Iterate through the sorted list and put each entry into the new LinkedHashMap for (Map.Entry entry : entryList) { sortedMap.put(entry.getKey(), entry.getValue()); } return sortedMap; }
Question: Java program that checks if two arrays contain the same elements.
Answer: Program: public static boolean arraysEqual(int[] arr1, int[] arr2) { // Check if the arrays have the same length if (arr1.length != arr2.length) { return false; } // Sort the arrays Arrays.sort(arr1); Arrays.sort(arr2); // Compare the sorted arrays element by element for (int i = 0; i < arr1.length; i++) { if (arr1[i] != arr2[i]) { return false; // elements in both array are not same } } // If all elements are equal, the arrays are equal return true; }
Question: Merge Sort Program in Java
Answer: Program: public class MergeSort { public static void main(String[] args) { int[] array = {12, 11, 13, 5, 6, 7}; System.out.println("Given Array"); printArray(array); mergeSort(array, 0, array.length - 1); System.out.println("\nSorted array"); printArray(array); } public static void mergeSort(int[] arr, int left, int right) { if (left < right) { int middle = (left + right) / 2; mergeSort(arr, left, middle); mergeSort(arr, middle + 1, right); merge(arr, left, middle, right); } } public static void merge(int[] arr, int left, int middle, int right) { int n1 = middle - left + 1; int n2 = right - middle; int[] leftArray = new int[n1]; int[] rightArray = new int[n2]; for (int i = 0; i < n1; ++i) leftArray[i] = arr[left + i]; for (int j = 0; j < n2; ++j) rightArray[j] = arr[middle + 1 + j]; int i = 0, j = 0; int k = left; while (i < n1 && j < n2) { if (leftArray[i] <= rightArray[j]) { arr[k] = leftArray[i]; i++; } else { arr[k] = rightArray[j]; j++; } k++; } while (i < n1) { arr[k] = leftArray[i]; i++; k++; } while (j < n2) { arr[k] = rightArray[j]; j++; k++; } } public static void printArray(int[] arr) { for (int i = 0; i < arr.length; ++i) System.out.print(arr[i] + " "); } }