-->

Featured

DSA Interview Question

Question: Various S orting algorithms Answer: There are various sorting algorithms, each with its own advantages and disadvantages in terms ...

Java Program

Question: Java program to read Properties file.

Answer: 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: 

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: 

int largestLen(int arr[], int n)

{

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

     int max=0;

   int sum=0;

        map.put(sum,-1);

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

            sum+=arr[i];

            if(map.containsKey(sum)){

                if(max<(i-map.get(sum)))

                    max=i-map.get(sum);

            }

            else {

                map.put(sum,i);

            }

        }

        return max;

    }


Question:Write a Java program to find the factorial of a non-negative integer entered by the user.
Answer:

    // Recursive function to calculate factorial
    public static long  calculateFactorial(int n) {
        if (n == 0 || n == 1) {
            return 1;
        } else {
            return n * calculateFactorial(n-1);
        }
    }
}

Question: Write a Java program to check if a given string is a palindrome 
Answer: 

    public static boolean isPalindrome(String str) {
        str = str.toLowerCase();
        int left = 0;
        int right = str.length() - 1;

        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}

Question: Write a Java program to find the sum of all even numbers from 1 to a given positive integer n
Answer: 

    public void sumOfEvens(int n)

    if (n <= 0){
            System.out.println("Please enter a positive integer.");
           else {
            int sum = 0;
            for(int i = 2; i <= n; i += 2){
                sum += i;
            }
            System.out.println("The sum of even numbers from 1 to " + n + " is: " + sum);
        }
    }


Question: Write a Java program to find the Fibonacci sequence up to a given number
Answer: 

    public void fibonacci(int n) {

        int  first = 0, second = 1;
        System.out.print("Fibonacci sequence up to " + n + ": ");

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

            System.out.print(first + " ");

            int next = first + second;

            first = second;

            second = next;
        }

    }


Question: Java Program to reverse a string without using String inbuilt function reverse()
Answer: 
public static String reverseString(String str) {

    char[] charArray = str.toCharArray();

    int left = 0;

    int right = charArray.length - 1;

    while (left < right) {

        // Swap characters at the left and right positions

        char temp = charArray[left];

        charArray[left] = charArray[right];

        charArray[right] = temp;

        // Move the left and right pointers inward

        left++;

        right--;

    }

    return new String(charArray);

}

Question: Java Program to read an excel
Answer: 
public class ExcelReader {
public static void main(String[] args) {

    try {

   // Specify the path to the Excel file

    String filePath = "path_to_your_excel_file.xlsx";

    // Create a FileInputStream to read the Excel file

    FileInputStream fis = new FileInputStream(filePath);

    // Create a workbook object from the Excel file

    Workbook workbook = new XSSFWorkbook(fis);

// Get the first sheet of the workbook (index 0)

    Sheet sheet = workbook.getSheetAt(0);

// Iterate through rows and columns to read data

    for (Row row : sheet) {

        for (Cell cell : row) {

  // Check the cell type and print its value

        if (cell.getCellType() == CellType.STRING) 

        {

        System.out.print(cell.getStringCellValue() + "\t");

        

        else if (cell.getCellType() == CellType.NUMERIC) 

        {

            System.out.print(cell.getNumericCellValue() + "\t");

        }

    }

    System.out.println(); // Move to the next row

    }

// Close the FileInputStream and the workbook

    fis.close();

    workbook.close();

    } catch (IOException e) {

    e.printStackTrace();

}}}

Question: Java Program to write an excel
Answer: import org.apache.poi.ss.usermodel.*;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;

import java.io.IOException;

public class ExcelWriter {

public static void main(String[] args) {

// Create a new workbook

    Workbook workbook = new XSSFWorkbook();

// Create a new sheet in the workbook

    Sheet sheet = workbook.createSheet("SampleSheet");

// Create some sample data

    String[] data = {"Name", "Age", "City"};

    Object[][] values = {

        {"John", 30, "New York"},

        {"Alice", 25, "Los Angeles"},

        {"Bob", 35, "Chicago"}

    };

// Create the header row

    Row headerRow = sheet.createRow(0);

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

        Cell cell = headerRow.createCell(i);

        cell.setCellValue(data[i]);

    }

// Populate the data rows

    for (int rowNum = 1; rowNum <= values.length; rowNum++) {

        Row dataRow = sheet.createRow(rowNum);

        for (int colNum = 0; colNum < values[0].length; colNum++) {

            Cell cell = dataRow.createCell(colNum);

            if (values[rowNum - 1][colNum] instanceof String) {

            cell.setCellValue((String) values[rowNum - 1][colNum]);

        

        else if (values[rowNum - 1][colNum] instanceof Integer) {

            cell.setCellValue((Integer) values[rowNum - 1][colNum]);

        }

    }

}

// Write the workbook to an Excel file

    try (FileOutputStream fos = new FileOutputStream("SampleExcel.xlsx")) {

    workbook.write(fos);

    System.out.println("Excel file created successfully.");

    } catch (IOException e) {

        e.printStackTrace();

    }

// Close the workbook

    try {

        workbook.close();

    } catch (IOException e) {

        e.printStackTrace();

    }}}

Question: Java Program to check Armstrong number
Answer: 
public boolean isArmstrongNumber(int num) {

    int originalNum = num;

    int sum = 0;

    int numDigits = String.valueOf(num).length();

    while (num > 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: 
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: 
public void duplicateCharactersFinder (String input) {

    Map<Character, Integer> 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<Character, Integer> entry : charCountMap.entrySet()) {

        if (entry.getValue() > 1) {

        System.out.println(entry.getKey() + ": " + entry.getValue() + " times");

    }

}}

Question: Java Program for the Fibonacci series
Answer: 
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:

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:

public static LinkedHashMap<String, Integer> sortHashMapByValue(HashMap<String, Integer> map) {

// Convert the HashMap to a List of Map.Entry objects

    List<Map.Entry<String, Integer>> entryList = new LinkedList<>(map.entrySet());

    // Define a custom comparator to sort by values in ascending order

    Comparator<Map.Entry<String, Integer>> 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<String, Integer> sortedMap = new LinkedHashMap<>();

    // Iterate through the sorted list and put each entry into the new LinkedHashMap

    for (Map.Entry<String, Integer> entry : entryList) {

        sortedMap.put(entry.getKey(), entry.getValue());

    }

    return sortedMap;

}


Question: Java program that checks if two arrays contain the same elements.
Answer:

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: 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] + " ");

    }

}   



No comments:

Post a Comment

popular posts