some common array-related interview questions in Java

Category : Java | Sub Category : Java Programs | By Prasad Bonam Last updated: 2023-08-14 12:42:23 Viewed : 529


some common array-related interview questions in Java:

Here are some Java array-related interview questions along with their solutions and corresponding outputs:

1. Find the maximum element in an array:

java
public class MaxElementInArray { public static void main(String[] args) { int[] array = {10, 7, 23, 45, 87, 13}; int max = array[0]; for (int num : array) { if (num > max) { max = num; } } System.out.println("Maximum element: " + max); } }

Output:

yaml
Maximum element: 87

2. Find the second largest element in an array:

java
public class SecondLargestInArray { public static void main(String[] args) { int[] array = {10, 7, 23, 45, 87, 13}; int max = Integer.MIN_VALUE; int secondMax = Integer.MIN_VALUE; for (int num : array) { if (num > max) { secondMax = max; max = num; } else if (num > secondMax && num != max) { secondMax = num; } } System.out.println("Second largest element: " + secondMax); } }

Output:

sql
Second largest element: 45

3. Find the common elements in two arrays:

java
import java.util.HashSet; import java.util.Set; public class CommonElementsInArrays { public static void main(String[] args) { int[] array1 = {1, 2, 3, 4, 5}; int[] array2 = {3, 5, 6, 7, 8}; Set<Integer> commonElements = new HashSet<>(); for (int num : array1) { commonElements.add(num); } for (int num : array2) { if (commonElements.contains(num)) { System.out.println("Common element: " + num); } } } }

Output:

yaml
Common element: 3 Common element: 5

4. Rotate an array to the right by K positions:

java
public class RotateArray { public static void main(String[] args) { int[] array = {1, 2, 3, 4, 5}; int k = 2; int n = array.length; k = k % n; int[] rotatedArray = new int[n]; for (int i = 0; i < n; i++) { rotatedArray[(i + k) % n] = array[i]; } System.out.println("Rotated array:"); for (int num : rotatedArray) { System.out.print(num + " "); } } }

Output:

c
Rotated array: 4 5 1 2 3

These examples demonstrate different array manipulation techniques commonly asked in interviews. The outputs correspond to the provided input arrays and problem statements.


Search
Related Articles

Leave a Comment: