What We Are Learn:
ToggleJava Array Programs: We will be discussing Java Array Programs. These programs are some of the most asked questions in interviews and coding exams. Practicing these Array programs in Java languages will help you understand various array concepts.
Try solving the array programs below by yourself and then check the solution. So get started with the list of array programs below now to improve your skills.
Post Type: | Java Programs For Beginners |
Published On: | www.softwaretestingo.com |
Applicable For: | Freshers & Experience |
Get Updates: | Join Our Telegram Group |
Java Array Programs
Here is the list of frequently asked Java Array Programs:
package com.java.ArrayEx; public class ArrayPGM1 { public static void main(String[] args) { int [] a=new int[3]; a[0]=10; a[1]=20; a[2]=30; System.out.println(a[0]); System.out.println(a[1]); System.out.println(a[2]); System.out.println("Array of length=" + a.length); } }
Result:
10 20 30 Array of length=3
package com.java.ArrayEx; public class ArrayPGM2 { public static void main(String[] args) { String [] s={"Software","Testing","Blog"}; System.out.println(s[0]); System.out.println(s[1]); System.out.println(s[2]); System.out.println("Array of length=" + s.length); } }
Result:
Software Testing Blog Array of length=3
package com.java.ArrayEx; public class ArrayPGM3 { public static void main(String[] args) { int[] a=new int[5]; a[0]=1; a[1]=2; a[2]=3; a[3]=4; a[4]=5; for(int i=0;i<a.length;i++) { System.out.println(a[i]); } } }
Result:
1 2 3 4 5
package com.java.Softwaretestingblog; import java.util.Arrays; public class CompareTwoArray { public static void main(String[] args) { // TODO Auto-generated method stub int arr1[] = {1, 2, 3}; int arr2[] = {1, 2, 3}; if (Arrays.equals(arr1, arr2)) System.out.println("Same"); else System.out.println("Not same"); } }
Final Results:
Same
package com.java.ArrayEx; public class Array2ndLargestvalue { public static void main(String[] args) { int numbers[] = { 47, 3, 37, 12, 46, 5, 64, 21 }; //System.out.println(numbers.length); int highest = 0; int second_highest = 0; for (int n : numbers) { if (highest < n) { second_highest = highest; highest = n; } else if (second_highest < n) { second_highest = n; } } System.out.println("First Max Number: " + highest); System.out.println("Second Max Number: " + second_highest); } }
The Final Output:
First Max Number: 64 Second Max Number: 47
package com.java.Softwaretestingblog; public class Copy_Specific_Array_Values { public static void main(String[] args) { // TODO Auto-generated method stub char ch[] = {'S','o','f','t','w','a','r','e','T','e','s','t','i','n','g','B','l','o','g'}; /** * We can copy a char array to a string by using * copyValueOf() method. */ String chStr = String.copyValueOf(ch); System.out.println("Original Array Values :- "+chStr); /** * We can also copy only range of charactors in a * char array by copyValueOf() method. */ String subStr = String.copyValueOf(ch,8,7); System.out.println("Substring From The Original String :-"+subStr); } }
Output:
Original Array Values :- SoftwareTestingBlog Substring From The Original String :-Testing
package com.java.Softwaretestingblog; public class ArrayEx1 { public static void main(String[] args) { // TODO Auto-generated method stub int i=10; for(i=10;i>0;i--) { for(int j=1;j<=10;j++) { if((i+j)==11) { int k=i*j; System.out.println(i + "*" + j+"="+k ); } } } } }
Final Result:
10*1=10 9*2=18 8*3=24 7*4=28 6*5=30 5*6=30 4*7=28 3*8=24 2*9=18 1*10=10
package com.java.Softwaretestingblog; public class DefaultArrayValue { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("String array default values:"); String str[] = new String[5]; for (String s : str) System.out.print(s + " "); System.out.println("\n\nInteger array default values:"); int num[] = new int[5]; for (int val : num) System.out.print(val + " "); System.out.println("\n\nDouble array default values:"); double dnum[] = new double[5]; for (double val : dnum) System.out.print(val + " "); System.out.println("\n\nBoolean array default values:"); boolean bnum[] = new boolean[5]; for (boolean val : bnum) System.out.print(val + " "); System.out.println("\n\nReference Array default values:"); DefaultArrayValue ademo[] = new DefaultArrayValue[5]; for (DefaultArrayValue val : ademo) System.out.print(val + " "); } }
Final Results:
String array default values: null null null null null Integer array default values: 0 0 0 0 0 Double array default values: 0.0 0.0 0.0 0.0 0.0 Boolean array default values: false false false false false Reference Array default values: null null null null null
package com.java.Softwaretestingblog; public class FindLargestSmallestNumber { public static void main(String[] args) { // TODO Auto-generated method stub //array of 10 numbers int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23}; //assign first element of an array to largest and smallest int smallest = numbers[0]; int largetst = numbers[0]; for(int i=1; i< numbers.length; i++) { if(numbers[i] > largetst) largetst = numbers[i]; else if (numbers[i] < smallest) smallest = numbers[i]; } System.out.println("Largest Number is : " + largetst); System.out.println("Smallest Number is : " + smallest); } }
Output:
Largest Number is : 98 Smallest Number is : 23
package com.java.Softwaretestingblog; public class FoundNoOfOccurance { public static void main(String[] args) { // TODO Auto-generated method stub String s="i am monoj good boy"; char c='o'; int total_size=s.length(); int replace_sie=s.replace("o", "").length(); System.out.println(total_size +"\t"+replace_sie); int count=s.length()-s.replace("o", "").length(); System.out.println("Number of occurances of 'a' is= "+ count); } }
Output:
19 14 Number of occurrence of 'a' is= 5
Array2Array Program 1:
package com.java.ArrayEx; public class ArrayCopy { public static void main(String[] args) { char a[]={'a','b','c','d','e','f'}; char [] b=new char[3]; System.arraycopy(a, 1, b, 0,3); System.out.println("New String b=" + new String(b)); } }
Let’s Execute the above Array
Execution Result:
New String b=bcd
Program 2:
package com.java.Softwaretestingblog; public class ArrayCopy { public static void main(String[] args) { // TODO Auto-generated method stub char ch[] = {'S','O','F','T','W','A','R','E','T','E','S','T','I','N','G','B','L','O','G'}; String chStr = String.copyValueOf(ch); System.out.println(chStr); String subStr = String.copyValueOf(ch,8,7); System.out.println(subStr); } }
Execution Result:
SOFTWARETESTINGBLOG TESTING
package com.softwaretestingblog.programs; public class VerifyTwoArrayWithoutFunction { public static void main(String[] args) { int[] arrayOne = {2, 5, 1, 7, 4}; int[] arrayTwo = {2, 5, 1, 7, 4}; boolean equalOrNot = true; if(arrayOne.length == arrayTwo.length) { for (int i = 0; i < arrayOne.length; i++) { if(arrayOne[i] != arrayTwo[i]) { equalOrNot = false; } } } else { equalOrNot = false; } if (equalOrNot) { System.out.println("Two Arrays Are Equal"); } else { System.out.println("Two Arrays Are Not equal"); } } }
Output:
Two Arrays Are Equal
package com.softwaretestingblog.programs; import java.util.HashSet; public class FindCommonElementFrom2Array { public static void main(String[] args) { String[] s1 = {"ONE", "TWO", "THREE", "FOUR", "FIVE", "FOUR"}; String[] s2 = {"THREE", "FOUR", "FIVE", "SIX", "SEVEN", "FOUR"}; HashSet<String> set = new HashSet<String>(); for (int i = 0; i < s1.length; i++) { for (int j = 0; j < s2.length; j++) { if(s1[i].equals(s2[j])) { set.add(s1[i]); } } } System.out.println(set); //OUTPUT : [THREE, FOUR, FIVE] } }
Output:
[FIVE, FOUR, THREE]
package com.softwaretestingblog.programs; public class FindTwoMaxNumbers { public void findTwoMaxNumbers(int[] array){ int maxOne = 0; int maxTwo = 0; for(int i:array) { if(maxOne < i) { maxTwo = maxOne; maxOne =i; } else if(maxTwo < i) { maxTwo = i; } } System.out.println("First Maximum Number: "+maxOne); System.out.println("Second Maximum Number: "+maxTwo); } public static void main(String a[]){ int num[] = {4,23,67,1,76,1,98,13}; FindTwoMaxNumbers obj = new FindTwoMaxNumbers(); obj.findTwoMaxNumbers(num); //obj.findTwoMaxNumbers(new int[]{4,5,6,90,1}); } }
Output:
First Maximum Number: 98 Second Maximum Number: 76
public class Find_Duplicate_Element_Array { public static void main(String[] args) { String[] strArray = {"abc", "def", "mno", "xyz", "pqr", "xyz", "def"}; for (int i = 0; i < strArray.length-1; i++) { for (int j = i+1; j < strArray.length; j++) { if( (strArray[i].equals(strArray[j])) && (i != j) ) { System.out.println("Duplicate Element is : "+strArray[j]); } } } } }
import java.util.HashSet; public class FindDuplicateElement { public static void main(String[] args) { String[] strArray = {"abc", "def", "mno", "xyz", "pqr", "xyz", "def"}; HashSet<String> set = new HashSet<String>(); for (String arrayElement : strArray) { if(!set.add(arrayElement)) { System.out.println("Duplicate Element is : "+arrayElement); } } } }
Here are the different methods of finding the missing and duplicate numbers between two arrays. If you want to check out more Java programs, you can follow this link.
Find the Missing and Duplicate Numbers in the Array
- UsingTemp Variable
package com.softwaretestingo.interviewprograms; public class FindMissingDuplicateNumberEX1 { static void printTwoElements(int[] arr, int n) { int[] temp = new int[n]; // Creating temp array of size n // with initial values as 0. int repeatingNumber = -1; int missingNumber = -1; for (int i = 0; i < n; i++) { temp[arr[i] - 1]++; if (temp[arr[i] - 1] > 1) { repeatingNumber = arr[i]; } } for (int i = 0; i < n; i++) { if (temp[i] == 0) { missingNumber = i + 1; break; } } System.out.println("The repeating number is " + repeatingNumber + "."); System.out.println("The missing number is " + missingNumber + "."); } public static void main(String[] args) { int[] arr = { 7, 3, 4, 5, 5, 6, 2 }; int n = arr.length; printTwoElements(arr, n); } }
2. Next Way
package com.softwaretestingo.interviewprograms; public class FindMissingDuplicateNumberEX2 { static void printTwoElements(int arr[], int size) { int i; System.out.print("The repeating element is "); for (i = 0; i < size; i++) { int abs_val = Math.abs(arr[i]); if (arr[abs_val - 1] > 0) arr[abs_val - 1] = -arr[abs_val - 1]; else System.out.println(abs_val); } System.out.print("and the missing element is "); for (i = 0; i < size; i++) { if (arr[i] > 0) System.out.println(i + 1); } } public static void main(String[] args) { int arr[] = { 7, 3, 4, 5, 5, 6, 2 }; int n = arr.length; printTwoElements(arr, n); } }
3. Using Map
package com.softwaretestingo.interviewprograms; import java.util.HashMap; import java.util.Map; public class FindMissingDuplicateNumberEX3 { public static void main(String[] args) { int[] arr = { 4, 3, 6, 2, 1, 1, 2 }; Map<Integer, Boolean> numberMap = new HashMap<>(); int max = arr.length; for (Integer i : arr) { if (numberMap.get(i) == null) { numberMap.put(i, true); } else { System.out.println("Repeating = " + i); } } for (int i = 1; i <= max; i++) { if (numberMap.get(i) == null) { System.out.println("Missing = " + i); } } } }
Now We will try to Find the missing number between two Arrays.
package com.softwaretestingo.interviewprograms; import java.util.Arrays; public class FindMissingNumberBetween2ArrayEx { private static int missingNumber(int[] arr1, int arr2[]) { int missingNumber = arr1[0]; for (int index = 1; index < arr1.length; index++) { missingNumber ^= arr1[index]; } for (int index = 0; index < arr2.length; index++) { missingNumber ^= arr2[index]; } return missingNumber; } public static void main(String[] args) { int array1[] = { 1, 2, 3, 4, 5 }; int array2[] = { 1, 2, 4, 5 }; String sArr1 = Arrays.toString(array1); String sArr2 = Arrays.toString(array2); System.out.printf("1. Missing number in array1 & array2 is:", sArr1, sArr2); int missingNumber = missingNumber(array1, array2); System.out.printf(" %d", missingNumber); array1 = new int[] { 10, 20, 30, 40 }; array2 = new int[] { 20, 30, 40, }; sArr1 = Arrays.toString(array1); sArr2 = Arrays.toString(array2); System.out.printf("\n2. Missing number in array1 & array2 is:", sArr1, sArr2); missingNumber = missingNumber(array1, array2); System.out.printf(" %d", missingNumber); } }
Conclusion:
We have compiled a list of the top Java Array Programs interview questions with answers to help freshers prepare for their interviews. The key to success in the Java interview is going through as many questions as you can.
If you encounter any other Java Array Programs during the interview, please update us in the comment section, and we will try to include those in our blog post.