Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
184 views

Array Programs

The document discusses several ways to check equality between two arrays in Java. The first method uses a for loop to iterate through the arrays and check if each element is equal. The second method uses the Arrays.equals() method to directly compare the arrays. The document also provides examples of finding duplicate elements in an array using nested for loops and the HashSet data structure, and algorithms to find the second largest element or all pairs of elements whose sum is equal to a given number.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
184 views

Array Programs

The document discusses several ways to check equality between two arrays in Java. The first method uses a for loop to iterate through the arrays and check if each element is equal. The second method uses the Arrays.equals() method to directly compare the arrays. The document also provides examples of finding duplicate elements in an array using nested for loops and the HashSet data structure, and algorithms to find the second largest element or all pairs of elements whose sum is equal to a given number.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 58

1) Write a java program to find duplicate elements in an array?

First Method : Using Brute Force Method

public class MainClass


{
public static void main(String[] args)
{
String[] strArray = {"Java", "JSP", "Servlets", "Java", "Struts", "JSP",
"JDBC"};

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]);
}
}
}
}
}

Output :

Duplicate Element is : Java


Duplicate Element is : JSP

Second Method : Using HashSet

import java.util.HashSet;

public class MainClass


{
public static void main(String[] args)
{
String[] strArray = {"Java", "JSP", "Servlets", "Java", "Struts", "JSP",
"JDBC"};

HashSet<String> set = new HashSet<String>();

for (String arrayElement : strArray)


{
if(!set.add(arrayElement))
{
System.out.println("Duplicate Element is : "+arrayElement);
}
}
}
}
Output :

Duplicate Element is : Java


Duplicate Element is : JSP

Program to print the duplicate elements of an array


In this program, we need to print the duplicate elements present in the array. This
can be done through two loops. The first loop will select an element and the second
loop will iteration through the array by comparing the selected element with other
elements. If a match is found, print the duplicate element.

Program to print the duplicate elements of an array


In the above array, the first duplicate will be found at the index 4 which is the
duplicate of the element (2) present at index 1. So, duplicate elements in the
above array are 2, 3 and 8.

public class DuplicateElement {


public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3};
System.out.println("Duplicate elements in given array: ");
//Searches for duplicate element
for(int i = 0; i < arr.length; i++) {
for(int j = i + 1; j < arr.length; j++) {
if(arr[i] == arr[j])
System.out.println(arr[j]);
}
}
}
}

Duplicate elements in given array:


2
3
8

---------------------------------

2) Write a java program to find second largest element in an array of integers?

import java.util.Arrays;

public class MainClass


{
static void secondLargest(int[] input)
{
int firstLargest, secondLargest;

//Checking first two elements of input array

if(input[0] > input[1])


{
//If first element is greater than second element

firstLargest = input[0];

secondLargest = input[1];
}
else
{
//If second element is greater than first element

firstLargest = input[1];
secondLargest = input[0];
}

//Checking remaining elements of input array

for (int i = 2; i < input.length; i++)


{
if(input[i] > firstLargest)
{
//If element at 'i' is greater than 'firstLargest'

secondLargest = firstLargest;

firstLargest = input[i];
}
else if (input[i] < firstLargest && input[i] > secondLargest)
{
//If element at 'i' is smaller than 'firstLargest' and greater than
'secondLargest'

secondLargest = input[i];
}
}

System.out.println("Input Array :");

System.out.println(Arrays.toString(input));

System.out.println("Second Largest Element : ");

System.out.println(secondLargest);
}

public static void main(String[] args)


{
secondLargest(new int[] {47498, 14526, 74562, 42681, 75283, 45796});
}
}
Output :

Input Array :
[47498, 14526, 74562, 42681, 75283, 45796]
Second Largest Element :
74562

Java program to find second largest number in an array

Step 1:
Iterate the given array
Step 2 (first if condition arr[i] > largest):
If current array value is greater than largest value then
Move the largest value to secondLargest and make
current value as largest
Step 3 (second if condition arr[i] > secondLargest )
If the current value is smaller than largest and greater than secondLargest then
the current value becomes secondLargest

package com.candidjava;

public class SecondLargest {

public static void main(String[] args) {

int arr[] = { 14, 46, 47, 86, 92, 52, 48, 36, 66, 85 };
int largest = arr[0];
int secondLargest = arr[0];

System.out.println("The given array is:" );


for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+"\t");
}
for (int i = 0; i < arr.length; i++) {

if (arr[i] > largest) {


secondLargest = largest;
largest = arr[i];

} else if (arr[i] > secondLargest) {


secondLargest = arr[i];

}
}

System.out.println("\nSecond largest number is:" + secondLargest);

}
}

Java program to find largest and second largest in an array

public class LargestAndSecondLargest


{
public static void main(String[] args)
{

int nums[] = { 5, 34, 78, 2, 45, 1, 99, 23 };


int maxOne = 0;
int maxTwo = 0;
for (int i=0;i<nums.length; i++)
{
if (maxOne < nums[i])
{
maxTwo = maxOne;
maxOne = nums[i];
}
else if (maxTwo < nums[i])
{
maxTwo = nums[i];
}
}
System.out.println("Largest Number: " + maxOne);
System.out.println("Second Largest Number: " + maxTwo);
}
}

Output
Largest Number: 99
Second Largest Number: 78

To find the second largest element of the given array, first of all, sort the
array.

Sorting an array
Compare the first two elements of the array
If the first element is greater than the second swap them.
Then, compare 2nd and 3rd elements if the second element is greater than the 3rd
swap them.
Repeat this till the end of the array.
After sorting an array print the second element from the end of the array.

Program
Live Demo

public class ThirdLargestNumberInAnArray {


public static void main(String args[]){
int temp, size;
int array[] = {10, 20, 25, 63, 96, 57};
size = array.length;

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


for(int j = i+1; j<size; j++){

if(array[i]>array[j]){
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
System.out.println("Third second largest number is:: "+array[size-2]);
}
}
Output
Third second largest number is:: 63

Another solution
You can also sort the elements of the given array using the sort method of the
java.util.Arrays class then, print the second element from the end of the array.

import java.util.Arrays;
public class LargestNumberSample {
public static void main(String args[]){
int array[] = {10, 20, 25, 63, 96, 57};
int size = array.length;
Arrays.sort(array);
System.out.println("sorted Array ::"+Arrays.toString(array));
int res = array[size-2];
System.out.println("2nd largest element is ::"+res);
}
}
Output
sorted Array ::[10, 20, 25, 57, 63, 96]
2nd largest element is ::63
---------------------------------

3) Write a java program to check the equality of two arrays?

First Method : Using Iterative Method

import java.util.Arrays;

public class MainClass


{
public static void main(String[] args)
{
int[] arrayOne = {21, 57, 11, 37, 24};

int[] arrayTwo = {21, 57, 11, 37, 24};

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;
}

System.out.println("Input Arrays :");

System.out.println("First Array : "+Arrays.toString(arrayOne));

System.out.println("Second Array : "+Arrays.toString(arrayTwo));

if (equalOrNot)
{
System.out.println("Two Arrays Are Equal");
}
else
{
System.out.println("Two Arrays Are Not equal");
}
}
}
Output :

Input Arrays :
First Array : [21, 57, 11, 37, 24]
Second Array : [21, 57, 11, 37, 24]
Two Arrays Are Equal

Second Method : Using Arrays.equals() Method

import java.util.Arrays;

public class MainClass


{
public static void main(String[] args)
{
int[] arrayOne = {21, 57, 11, 37, 24};

int[] arrayTwo = {21, 57, 11, 37, 24};

boolean equalOrNot = Arrays.equals(arrayOne, arrayTwo);

System.out.println("Input Arrays :");

System.out.println("First Array : "+Arrays.toString(arrayOne));

System.out.println("Second Array : "+Arrays.toString(arrayTwo));

if (equalOrNot)
{
System.out.println("Two Arrays Are Equal");
}
else
{
System.out.println("Two Arrays Are Not equal");
}
}
}
Output :

Input Arrays :
First Array : [21, 57, 11, 37, 24]
Second Array : [21, 57, 11, 37, 24]
Two Arrays Are Equal

--------------------

4) Write a java program to find all pairs of elements in an integer array whose sum
is equal to a given number?

import java.util.Arrays;

public class MainClass


{
static void findThePairs(int inputArray[], int inputNumber)
{
System.out.println("Input Array : "+Arrays.toString(inputArray));

System.out.println("Input Number : "+inputNumber);

System.out.println("Pairs of elements whose sum is "+inputNumber+" are :


");
for (int i = 0; i < inputArray.length; i++)
{
for (int j = i+1; j < inputArray.length; j++)
{
if(inputArray[i]+inputArray[j] == inputNumber)
{
System.out.println(inputArray[i]+" + "+inputArray[j]+" =
"+inputNumber);
}
}
}

System.out.println("======================================");
}

public static void main(String[] args)


{
findThePairs(new int[] {4, 6, 5, -10, 8, 5, 20}, 10);

findThePairs(new int[] {4, -5, 9, 11, 25, 13, 12, 8}, 20);

findThePairs(new int[] {12, 13, 40, 15, 8, 10, -15}, 25);

findThePairs(new int[] {12, 23, 125, 41, -75, 38, 27, 11}, 50);
}
}

Output :

Input Array : [4, 6, 5, -10, 8, 5, 20]


Input Number : 10
Pairs of elements whose sum is 10 are :
4 + 6 = 10
5 + 5 = 10
-10 + 20 = 10
======================================
Input Array : [4, -5, 9, 11, 25, 13, 12, 8]
Input Number : 20
Pairs of elements whose sum is 20 are :
-5 + 25 = 20
9 + 11 = 20
12 + 8 = 20
======================================
Input Array : [12, 13, 40, 15, 8, 10, -15]
Input Number : 25
Pairs of elements whose sum is 25 are :
12 + 13 = 25
40 + -15 = 25
15 + 10 = 25
======================================
Input Array : [12, 23, 125, 41, -75, 38, 27, 11]
Input Number : 50
Pairs of elements whose sum is 50 are :
12 + 38 = 50
23 + 27 = 50
125 + -75 = 50

--------------------
5) Write a java program to find continuous sub array whose sum is equal to a given
number?

import java.util.Arrays;

public class MainClass


{
static void findSubArray(int[] inputArray, int inputNumber)
{
//Initializing sum with the first element of the inputArray

int sum = inputArray[0];

//Initializing starting point with 0

int start = 0;

//Iterating through inputArray starting from second element

for (int i = 1; i < inputArray.length; i++) { //Adding inputArray[i] to the


current 'sum' sum = sum + inputArray[i]; //If sum is greater than inputNumber then
following loop is executed until sum becomes either smaller than or equal to
inputNumber while(sum > inputNumber && start <= i-1)
{
//Removing starting elements from the 'sum'

sum = sum - inputArray[start];

//Incrementing start by 1

start++;
}

//If 'sum' is equal to 'inputNumber' then printing the sub array

if(sum == inputNumber)
{
System.out.println("Input Array : "+Arrays.toString(inputArray));

System.out.println("Input Number : "+inputNumber);

System.out.print("Continuous Sub Array : ");

for (int j = start; j <= i; j++)


{
System.out.print(inputArray[j]+" ");
}

System.out.println();
}
}

System.out.println("=================================");
}

public static void main(String[] args)


{
findSubArray(new int[]{42, 15, 12, 8, 6, 32}, 26);
findSubArray(new int[]{12, 5, 31, 13, 21, 8}, 49);

findSubArray(new int[]{15, 51, 7, 81, 5, 11, 25}, 41);


}
}
Output :

Input Array : [42, 15, 12, 8, 6, 32]


Input Number : 26
Continuous Sub Array : 12 8 6
=================================
Input Array : [12, 5, 31, 13, 21, 8]
Input Number : 49
Continuous Sub Array : 5 31 13
=================================
Input Array : [15, 51, 7, 81, 5, 11, 25]
Input Number : 41
Continuous Sub Array : 5 11 25

--------------

6) Write a java program to find the intersection of two arrays?

First Method : Using Iterative Method

import java.util.Arrays;
import java.util.HashSet;

class MainClass
{
public static void main(String[] args)
{
String[] inputArray1 = {"ONE", "TWO", "THREE", "FOUR", "FIVE", "FOUR"};

String[] inputArray2 = {"THREE", "FOUR", "FIVE", "SIX", "SEVEN", "FOUR"};

HashSet<String> set = new HashSet<String>();

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


{
for (int j = 0; j < inputArray2.length; j++)
{
if(inputArray1[i].equals(inputArray2[j]))
{
set.add(inputArray1[i]);
}
}
}

System.out.println("First Array : "+Arrays.toString(inputArray1));

System.out.println("Second Array : "+Arrays.toString(inputArray2));

System.out.println("Common Elements : "+set);


}
}
Output :

First Array : [ONE, TWO, THREE, FOUR, FIVE, FOUR]


Second Array : [THREE, FOUR, FIVE, SIX, SEVEN, FOUR]
Common Elements : [FIVE, FOUR, THREE]

Second Method : Using retainAll() Method

import java.util.Arrays;
import java.util.HashSet;

class MainClass
{
public static void main(String[] args)
{
String[] inputArray1 = {"ONE", "TWO", "THREE", "FOUR", "FIVE", "FOUR"};

String[] inputArray2 = {"THREE", "FOUR", "FIVE", "SIX", "SEVEN", "FOUR"};

HashSet<String> set1 = new HashSet<String>(Arrays.asList(inputArray1));

HashSet<String> set2 = new HashSet<String>(Arrays.asList(inputArray2));

set1.retainAll(set2);

System.out.println("First Array : "+Arrays.toString(inputArray1));

System.out.println("Second Array : "+Arrays.toString(inputArray2));

System.out.println("Common Elements : "+set1);


}
}
Output :
First Array : [ONE, TWO, THREE, FOUR, FIVE, FOUR]
Second Array : [THREE, FOUR, FIVE, SIX, SEVEN, FOUR]
Common Elements : [FIVE, FOUR, THREE]

-------------------

7) Write a java program to separate zeros from non-zeros in an integer array?

Moving Zeros To End Of An Array :

import java.util.Arrays;

public class MainClass


{
static void moveZerosToEnd(int inputArray[])
{
System.out.println("Input Array : "+Arrays.toString(inputArray));

//Initializing counter to 0

int counter = 0;

//Traversing inputArray from left to right

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


{
//If inputArray[i] is non-zero

if(inputArray[i] != 0)
{
//Assigning inputArray[i] to inputArray[counter]

inputArray[counter] = inputArray[i];

//Incrementing the counter by 1

counter++;
}
}

//Assigning zero to remaining elements

while (counter < inputArray.length)


{
inputArray[counter] = 0;

counter++;
}

System.out.println("Input Array After moving zeros to end :");

System.out.println(Arrays.toString(inputArray));

System.out.println("======================================");
}

public static void main(String[] args)


{
moveZerosToEnd(new int[] {12, 0, 7, 0, 8, 0, 3});

moveZerosToEnd(new int[] {1, -5, 0, 0, 8, 0, 1});

moveZerosToEnd(new int[] {0, 1, 0, 1, -5, 0, 4});

moveZerosToEnd(new int[] {-4, 1, 0, 0, 2, 21, 4});


}
}
Output :

Input Array : [12, 0, 7, 0, 8, 0, 3]


Input Array After moving zeros to end :
[12, 7, 8, 3, 0, 0, 0]
======================================
Input Array : [1, -5, 0, 0, 8, 0, 1]
Input Array After moving zeros to end :
[1, -5, 8, 1, 0, 0, 0]
======================================
Input Array : [0, 1, 0, 1, -5, 0, 4]
Input Array After moving zeros to end :
[1, 1, -5, 4, 0, 0, 0]
======================================
Input Array : [-4, 1, 0, 0, 2, 21, 4]
Input Array After moving zeros to end :
[-4, 1, 2, 21, 4, 0, 0]
======================================

Moving Zeros To The Front Of An Array :

import java.util.Arrays;

public class MainClass


{
static void moveZerosToFront(int inputArray[])
{
System.out.println("Input Array :"+Arrays.toString(inputArray));

//Initializing counter to position of last element

int counter = inputArray.length-1;

//Traversing the inputArray from right to left

for (int i = inputArray.length-1; i >= 0; i--)


{
//If inputArray[i] is non-zero

if(inputArray[i] != 0)
{
//Assigning inputArray[i] to inputArray[counter]

inputArray[counter] = inputArray[i];

//Decrementing the counter by 1


counter--;
}
}

//Assigning 0 to remaining elements

while (counter >= 0)


{
inputArray[counter] = 0;

counter--;
}

System.out.println("Input Array After Moving Zeros To The Front :");

System.out.println(Arrays.toString(inputArray));

System.out.println("====================================");
}

public static void main(String[] args)


{
moveZerosToFront(new int[] {12, 0, 7, 0, 8, 0, 3});

moveZerosToFront(new int[] {1, -5, 0, 0, 8, 0, 1});

moveZerosToFront(new int[] {0, 1, 0, 1, -5, 0, 4});

moveZerosToFront(new int[] {-4, 1, 0, 0, 2, 21, 4});


}
}
Output :

Input Array :[12, 0, 7, 0, 8, 0, 3]


Input Array After Moving Zeros To The Front :
[0, 0, 0, 12, 7, 8, 3]
====================================
Input Array :[1, -5, 0, 0, 8, 0, 1]
Input Array After Moving Zeros To The Front :
[0, 0, 0, 1, -5, 8, 1]
====================================
Input Array :[0, 1, 0, 1, -5, 0, 4]
Input Array After Moving Zeros To The Front :
[0, 0, 0, 1, 1, -5, 4]
====================================
Input Array :[-4, 1, 0, 0, 2, 21, 4]
Input Array After Moving Zeros To The Front :
[0, 0, -4, 1, 2, 21, 4]

------------------

https://javaconceptoftheday.com/how-to-find-all-the-leaders-in-an-integer-array/

8) Write a java program to find all the leaders in an integer array?

Given an integer array, you have to find all the leader elements in this array. An
element is said to be leader if all the elements on it’s right side are smaller
than it. Rightmost element is always a leader. For example, if {14, 9, 11, 7, 8, 5,
3} is the given array then {14, 11, 8, 5, 3} are the leaders in this array.

Logic Used To Find All The Leaders In An Integer Array :


We go on traversing the given array from right to left. Initially, we assume the
last element as highest and we store it in a variable called ‘max‘. We print the
last element as it is always a leader. If we find any element greater than ‘max‘,
we print that element and update the ‘max‘ variable. We continue this until we
traverse all the elements in the given array.

public class LeadersInArray


{
static void findTheLeaders(int inputArray[])
{
//Getting the length of input array

int inputArrayLength = inputArray.length;

//Assuming the last element as max

int max = inputArray[inputArrayLength-1];

System.out.println("The leaders in "+Arrays.toString(inputArray)+" are :


");

//Printing the last element as it is always a leader

System.out.println(inputArray[inputArrayLength-1]);

//Traversing the remaining elements from right to left

for (int i = inputArray.length-2; i >= 0; i--)


{
//If the element is greater than max

if(inputArray[i] > max)


{
//Printing the element

System.out.println(inputArray[i]);

//Updating the max

max = inputArray[i];
}
}
}

public static void main(String[] args)


{
findTheLeaders(new int[] {12, 9, 7, 14, 8, 6, 3});

findTheLeaders(new int[] {8, 23, 19, 21, 15, 6, 11});

findTheLeaders(new int[] {55, 67, 71, 57, 51, 63, 38});

findTheLeaders(new int[] {21, 58, 44, 14, 51, 36, 23});


}
}

Output :

The leaders in [12, 9, 7, 14, 8, 6, 3] are :


3
6
8
14
The leaders in [8, 23, 19, 21, 15, 6, 11] are :
11
15
21
23
The leaders in [55, 67, 71, 57, 51, 63, 38] are :
38
63
71
The leaders in [21, 58, 44, 14, 51, 36, 23] are :
23
36
51
58

Another Method To Find All The Leaders In An Integer Array :

public class LeadersInArray


{
static void findTheLeaders(int inputArray[])
{
System.out.println("The leaders in "+Arrays.toString(inputArray)+" are :");

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


{
boolean flag = true;

for (int j = i+1; j < inputArray.length; j++)


{
if (inputArray[j] > inputArray[i])
{
flag = false;

break;
}
}

if (flag)
{
System.out.println(inputArray[i]);
}
}
}

public static void main(String[] args)


{
findTheLeaders(new int[] {12, 9, 7, 14, 8, 6, 3});

findTheLeaders(new int[] {8, 23, 19, 21, 15, 6, 11});

findTheLeaders(new int[] {55, 67, 71, 57, 51, 63, 38});

findTheLeaders(new int[] {21, 58, 44, 14, 51, 36, 23});


}
}
Output :

The leaders in [12, 9, 7, 14, 8, 6, 3] are :


14
8
6
3
The leaders in [8, 23, 19, 21, 15, 6, 11] are :
23
21
15
11
The leaders in [55, 67, 71, 57, 51, 63, 38] are :
71
63
38
The leaders in [21, 58, 44, 14, 51, 36, 23] are :
58
51
36
23

------------
9) Write a java program to find a missing number in an integer array?

import java.util.Arrays;

public class MainClass


{
//Method to calculate sum of 'n' numbers

static int sumOfNnumbers(int n)


{
int sum = (n * (n+1))/ 2;

return sum;
}

//Method to calculate sum of all elements of array

static int sumOfElements(int[] array)


{
int sum = 0;

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


{
sum = sum + array[i];
}
return sum;
}

public static void main(String[] args)


{
int n = 8;

int[] a = {1, 4, 5, 3, 2, 8, 6};

int sumOfNnumbers = sumOfNnumbers(n);

int sumOfElements = sumOfElements(a);

int missingNumber = sumOfNnumbers - sumOfElements;

System.out.println("Input Array : "+Arrays.toString(a));

System.out.println("Missing Number is = "+missingNumber);


}
}
Output :

Input Array : [1, 4, 5, 3, 2, 8, 6]


Missing Number is = 7

--------
10) Write a java program to convert an array to ArrayList and an ArrayList to
array?

Array To ArrayList :

import java.util.ArrayList;
import java.util.Arrays;

public class MainClass


{
public static void main(String[] args)
{
String[] array = new String[] {"ANDROID", "JSP", "JAVA", "STRUTS",
"HADOOP", "JSF"};

ArrayList<String> list = new ArrayList<String>(Arrays.asList(array));

System.out.println(list);
}
}

ArrayList To Array :

import java.util.ArrayList;

public class MainClass


{
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();

list.add("JAVA");
list.add("JSP");

list.add("ANDROID");

list.add("STRUTS");

list.add("HADOOP");

list.add("JSF");

String[] array = new String[list.size()];

list.toArray(array);

for (String string : array)


{
System.out.println(string);
}
}
}

11) Write a java program to count occurrences of each element in an array?

import java.util.Arrays;
import java.util.HashMap;

public class MainClass


{
static void arrayElementCount(int inputArray[])
{
//Creating a HashMap object with elements of inputArray as keys and their
count as values

HashMap<Integer, Integer> elementCountMap = new HashMap<Integer,


Integer>();

//checking every element of the inputArray

for (int i : inputArray)


{
if(elementCountMap.containsKey(i))
{
//If element is present in elementCountMap, incrementing it's count by 1

elementCountMap.put(i, elementCountMap.get(i)+1);
}
else
{
//If element is not present in elementCountMap,
//adding this element to elementCountMap with 1 as it's value

elementCountMap.put(i, 1);
}
}

System.out.println("Input Array : "+Arrays.toString(inputArray));

System.out.println("Element Count : "+elementCountMap);


System.out.println("=======================================");
}

public static void main(String[] args)


{
arrayElementCount(new int[]{4, 5, 4, 5, 4, 6});

arrayElementCount(new int[]{12, 9, 12, 9, 10, 9, 10, 11});

arrayElementCount(new int[]{891, 187, 891, 187, 891, 476, 555, 741});


}
}
Output :

Input Array : [4, 5, 4, 5, 4, 6]


Element Count : {4=3, 5=2, 6=1}
=======================================
Input Array : [12, 9, 12, 9, 10, 9, 10, 11]
Element Count : {9=3, 10=2, 11=1, 12=2}
=======================================
Input Array : [891, 187, 891, 187, 891, 476, 555, 741]
Element Count : {741=1, 891=3, 187=2, 555=1, 476=1}

-----------

12) Write a java program to reverse an array without using an additional array?

import java.util.Arrays;

public class MainClass


{
static void reverseArray(int inputArray[])
{
System.out.println("Array Before Reverse : "+Arrays.toString(inputArray));

int temp;

for (int i = 0; i < inputArray.length/2; i++)


{
temp = inputArray[i];

inputArray[i] = inputArray[inputArray.length-1-i];

inputArray[inputArray.length-1-i] = temp;
}

System.out.println("Array After Reverse : "+Arrays.toString(inputArray));

System.out.println("=========================================");
}

public static void main(String[] args)


{
reverseArray(new int[]{4, 5, 8, 9, 10});
reverseArray(new int[]{12, 9, 21, 17, 33, 7});

reverseArray(new int[]{891, 569, 921, 187, 343, 476, 555});


}
}

Output :

Array Before Reverse : [4, 5, 8, 9, 10]


Array After Reverse : [10, 9, 8, 5, 4]
=========================================
Array Before Reverse : [12, 9, 21, 17, 33, 7]
Array After Reverse : [7, 33, 17, 21, 9, 12]
=========================================
Array Before Reverse : [891, 569, 921, 187, 343, 476, 555]
Array After Reverse : [555, 476, 343, 187, 921, 569, 891]

Program to print the elements of an array in reverse order

public class ReverseArray {


public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
System.out.println("Original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("Array in reverse order: ");
//Loop through the array in reverse order
for (int i = arr.length-1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
}
}

o/p:
Original array:
1 2 3 4 5
Array in reverse order:
5 4 3 2 1

---------------

13) Write a java program to remove duplicate elements from an array?

Remove duplicates from unsorted array

Given an unsorted array of integers, print the array after removing the duplicate
elements from it. We need to print distinct array elements according to their first
occurrence.
Examples:
Input: arr[] = { 1, 2, 5, 1, 7, 2, 4, 2}
Output: 1 2 5 7 4
Explanation: {1, 2} appear more than one time.
Input: arr[] = { 3, 3, 4, 1, 1}
Output: 3 4 1
• Take a Set
• Insert all array element in the Set. Set does not allow duplicates and sets
like LinkedHashSet maintains the order of insertion so it will remove duplicates
and elements will be printed in the same order in which it is inserted.
• Convert the formed set into array.
• Print elements of Set.

// Java program to remove duplicates


// from unsorted array

import java.util.*;

class GFG {

// Function to remove duplicate from array


public static void removeDuplicates(int[] arr)
{
LinkedHashSet<Integer> set
= new LinkedHashSet<Integer>();

// adding elements to LinkedHashSet


for (int i = 0; i < arr.length; i++)
set.add(arr[i]);

// Print the elements of LinkedHashSet


System.out.print(set);
}

// Driver code
public static void main(String[] args)
{
int arr[] = { 1, 2, 5, 1, 7, 2, 4, 2 };
removeDuplicates(arr);
}
}

Remove Duplicate Elements in Unsorted Array

import java.util.Arrays;
public class RemoveDuplicateInArrayExample3{
public static int removeDuplicateElements(int arr[], int n){
if (n==0 || n==1){
return n;
}
int[] temp = new int[n];
int j = 0;
for (int i=0; i<n-1; i++){
if (arr[i] != arr[i+1]){
temp[j++] = arr[i];
}
}
temp[j++] = arr[n-1];
// Changing original array
for (int i=0; i<j; i++){
arr[i] = temp[i];
}
return j;
}

public static void main (String[] args) {


int arr[] = {10,70,30,90,20,20,30,40,70,50};//unsorted array
Arrays.sort(arr);//sorting array
int length = arr.length;
length = removeDuplicateElements(arr, length);
//printing array elements
for (int i=0; i<length; i++)
System.out.print(arr[i]+" ");
}
}

o/p:

10 20 30 40 50 70 90

--------------

14) Write a java program to find union and intersection of multiple arrays?

Union Of Multiple Arrays :

import java.util.Arrays;
import java.util.HashSet;

public class MainClass


{
static void union(int[] ... inputArrays)
{
HashSet<Integer> unionSet = new HashSet<Integer>();

System.out.println("Input Arrays :");

System.out.println("======================");

for (int[] inputArray : inputArrays)


{
System.out.println(Arrays.toString(inputArray));

for (int i : inputArray)


{
unionSet.add(i);
}
}

System.out.println("===========================");

System.out.println("Union Of All Input Arrays :");

System.out.println("===========================");
System.out.println(unionSet);
}

public static void main(String[] args)


{
int[] inputArray1 = {2, 3, 4, 7, 1};

int[] inputArray2 = {4, 1, 3, 5};

int[] inputArray3 = {8, 4, 6, 2, 1};

int[] inputArray4 = {7, 9, 4, 1};

union(inputArray1, inputArray2, inputArray3, inputArray4);


}
}

Output :

Input Arrays :
======================
[2, 3, 4, 7, 1]
[4, 1, 3, 5]
[8, 4, 6, 2, 1]
[7, 9, 4, 1]
===========================
Union Of All Input Arrays :
===========================
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Intersection Of Multiple Arrays :

import java.util.Arrays;
import java.util.HashSet;

public class MainClass


{
static void intersection(Integer[] ... inputArrays)
{
//Printing input arrays

System.out.println("Input Arrays :");

System.out.println("======================");

for (Integer[] inputArray : inputArrays)


{
System.out.println(Arrays.toString(inputArray));
}

//Creating HashSet object for first input array

HashSet<Integer> intersectionSet = new


HashSet<>(Arrays.asList(inputArrays[0]));

//Calling retainAll() method of first object by passing 2nd, 3rd, 4th...


objects

for (int i = 1; i < inputArrays.length; i++)


{
HashSet<Integer> set = new HashSet<>(Arrays.asList(inputArrays[i]));

intersectionSet.retainAll(set);
}

System.out.println("===========================");

System.out.println("Intersection Of All Input Arrays :");

System.out.println("===========================");

System.out.println(intersectionSet);
}

public static void main(String[] args)


{
Integer[] inputArray1 = {2, 3, 4, 7, 1};

Integer[] inputArray2 = {4, 1, 3, 5};

Integer[] inputArray3 = {8, 4, 6, 2, 1};

Integer[] inputArray4 = {7, 9, 4, 1};

intersection(inputArray1, inputArray2, inputArray3, inputArray4);


}
}

Output :

Input Arrays :
======================
[2, 3, 4, 7, 1]
[4, 1, 3, 5]
[8, 4, 6, 2, 1]
[7, 9, 4, 1]
===========================
Intersection Of All Input Arrays :
===========================
[1, 4]

-----------

15) Write a java program to find the most frequent element in an array?

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

public class MainClass


{
static void getMostFrequentElement(int inputArray[])
{
//Creating HashMap object with elements as keys and their occurrences as
values

HashMap<Integer, Integer> elementCountMap = new HashMap<Integer,


Integer>();

//Inserting all the elements of inputArray into elementCountMap

for (int i : inputArray)


{
if (elementCountMap.containsKey(i))
{
//If an element is present, incrementing its count by 1

elementCountMap.put(i, elementCountMap.get(i)+1);
}
else
{
//If an element is not present, put that element with 1 as its
value

elementCountMap.put(i, 1);
}
}

int element = 0;

int frequency = 1;

//Iterating through elementCountMap to get the most frequent element and


its frequency

Set<Entry<Integer, Integer>> entrySet = elementCountMap.entrySet();

for (Entry<Integer, Integer> entry : entrySet)


{
if(entry.getValue() > frequency)
{
element = entry.getKey();

frequency = entry.getValue();
}
}

//Printing the most frequent element in array and its frequency

if(frequency > 1)
{
System.out.println("Input Array : "+Arrays.toString(inputArray));

System.out.println("The most frequent element : "+element);

System.out.println("Its frequency : "+frequency);

System.out.println("========================");
}
else
{
System.out.println("Input Array : "+Arrays.toString(inputArray));

System.out.println("No frequent element. All elements are unique.");

System.out.println("=========================");
}
}

public static void main(String[] args)


{
getMostFrequentElement(new int[]{4, 5, 8, 7, 4, 7, 6,7});

getMostFrequentElement(new int[]{1, 2, 7, 5, 3, 6});


}
}

Output :

Input Array : [4, 5, 8, 7, 4, 7, 6, 7]


The most frequent element : 7
Its frequency : 3
========================
Input Array : [1, 2, 7, 5, 3, 6]
No frequent element. All elements are unique.

Program to find the frequency of each element in the array


In this program, we have an array of elements to count the occurrence of its each
element. One of the approaches to resolve this problem is to maintain one array to
store the counts of each element of the array. Loop through the array and count the
occurrence of each element as frequency and store it in another array fr.

1 2 8 3 2 2 2 5 1
In the given array, 1 has appeared two times so its frequency be 2 and 2 has
appeared four times so have frequency 4 and so on.

public class Frequency {


public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 8, 3, 2, 2, 2, 5, 1};
//Array fr will store frequencies of element
int [] fr = new int [arr.length];
int visited = -1;
for(int i = 0; i < arr.length; i++){
int count = 1;
for(int j = i+1; j < arr.length; j++){
if(arr[i] == arr[j]){
count++;
//To avoid counting same element again
fr[j] = visited;
}
}
if(fr[i] != visited)
fr[i] = count;
}

//Displays the frequency of each element present in array


System.out.println("---------------------------------------");
System.out.println(" Element | Frequency");
System.out.println("---------------------------------------");
for(int i = 0; i < fr.length; i++){
if(fr[i] != visited)
System.out.println(" " + arr[i] + " | " + fr[i]);
}
System.out.println("----------------------------------------");
}}

output:
----------------------------------------
Element | Frequency
----------------------------------------
1 | 2
2 | 4
8 | 1
3 | 1
5 | 1
----------------------------------------

-----------------------------------------------

16. Find Maximum and minimum from an array

import java.util.Arrays;

public class MinMaxValues{

public static void main (String args[]){


int numbers[]= {1,5,-9,12,-3,89, 18,23,4,-6};
//Find minimum (lowest) value in array using loop
System.out.println("Minimum Value = " + getMinValue(numbers));
//Find maximum (largest) value in array using loop
System.out.println("Maximum Value = " + getMaxValue(numbers));

//Find minimum (lowest) value in array by sorting array


System.out.println("Minimum Value = " + minValue(numbers));
//Find maximum (largest) value in array by sorting array
System.out.println("Maximum Value = " + maxValue(numbers));

//Find minimum (lowest) value in array using recursion


System.out.println("Minimum Value = " +
getMinimumValueUsingRecursion(numbers,0,numbers[0]));

//Find maximum (largest) value in array using recursion


System.out.println("Maximum Value = " +
getMaximumValueUsingRecursion(numbers,0,numbers[0]));

//Find maximum (largest) value in array using loop


public static int getMaxValue(int[] numbers){
int maxValue = numbers[0];
for(int i=1;i<numbers.length;i++){
if(numbers[i] > maxValue){
maxValue = numbers[i];
}
}
return maxValue;
}

//Find minimum (lowest) value in array using loop


public static int getMinValue(int[] numbers){
int minValue = numbers[0];
for(int i=1;i<numbers.length;i++){
if(numbers[i] < minValue){
minValue = numbers[i];
}
}
return minValue;
}

//Find minimum (lowest) value in array using array sort


public static int minValue(int[] numbers){
Arrays.sort(numbers);
return numbers[0];
}

find largest and smallest number in an array in java

public class LargestSmallest


{
public static void main(String[] args)
{
int a[] = new int[] { 23, 34, 13, 64, 72, 90, 10, 15, 9, 27 };

int min = a[0]; // assume first elements as smallest number


int max = a[0]; // assume first elements as largest number

for (int i = 1; i < a.length; i++) // iterate for loop from arrays 1st
index (second element)
{
if (a[i] > max)
{
max = a[i];
}
if (a[i] < min)
{
min = a[i];
}
}

System.out.println("Largest Number in a given array is : " + max);


System.out.println("Smallest Number in a given array is : " + min);
}

--------------------------------

17.Sorting char array in Java example

In this example we are sorting a char array. We have demonstrated two types of
sorting in the program 1) Complete sorting using sort(char[] a) method 2) Sorting
specified range of characters only using sort(char[] a, int fromIndex, int toIndex)
method.
import java.util.Arrays;

class SortCharArray {

public static void main(String[] args) {

// Creating a Char Array


char[] charArray = new char[] { 'A', 'Q', 'S', 'Z', 'P' };

// Displaying Array before Sorting


System.out.println("**Char Array Before Sorting**");
for (char ch: charArray){
System.out.println(ch);
}

// Sorting the Array


Arrays.sort(charArray);
System.out.println("**Char Array After Sorting**");
for (char ch: charArray){
System.out.println(ch);
}

// Another Char Array


char[] charArray2 =
new char[] { 'D', 'F', 'V', 'J', 'U', 'M', 'C' };

// Selective Sorting
/* public static void sort(char[] a, int fromIndex,
* int toIndex): Sorts the specified range of the
* array into ascending order. The range to be sorted
* extends from the index fromIndex, inclusive, to the
* index toIndex, exclusive. If fromIndex == toIndex,
* the range to be sorted is empty.
*/
Arrays.sort(charArray2, 2, 5);

// Displaying array after selective sorting


System.out.println("**Selective Sorting**");
for (char ch: charArray2){
System.out.println(ch);
}
}
}

Output:
**Char Array Before Sorting**
A
Q
S
Z
P
**Char Array After Sorting**
A
P
Q
S
Z
**Selective Sorting**
D
F
J
U
V
M
C

--------------

18.Find the index of the smallest number in an array

public class SmallestNumberIndex


{
public static void main(String[] args) {
int a[] = new int[]{12,44,23,56,9,23,78,13};

int min = a[0];


int index=0;

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


{
if(min > a[i])
{
min = a[i];
index=i;
}
}

System.out.println("Index position of Smallest value in a given array


is : "+index);
}

}
Output
Index position of Smallest value in a given array is : 4

---------

19.Find the index of the largest number in an array


This simple example shows you how to find the index of largest number in an array
using simple for loop
public class LargestNumberIndex
{
public static void main(String[] args)
{

int a[] = new int[] { 12, 44, 23, 56, 23, 78, 13 };

int max = a[0];


int index = 0;

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


{
if (max < a[i])
{
max = a[i];
index = i;
}
}

System.out.println("Index position of Maximum value in an array is :


" + index);
} }

Output

Index position of Maximum value in an array is : 5

--------------

20. Java program to print odd and even numbers from an array

1. package com.candidjava;
2.
3. public class OddEvenArray
4. {
5. public static void main(String args[])
6. {
7. int s, i;
8.
9. int[] a = { 33, 2, 4, 71, 88, 92, 9, 1 };
10.
11. for (i = 0; i < a.length; i++)
12. {
13. for (int j = i + 1; j < a.length; j++)
14.
15. {
16. if (a[i] > a[j])
17. {
18. s = a[i];
19. a[i] = a[j];
20. a[j] = s;
21.
22. }
23.
24. }
25.
26. }
27.
28. System.out.print("Input numbers :");
29.
30. for (i = 0; i < a.length; i++)
31.
32. {
33.
34. System.out.print(" " + a[i]);
35.
36. }
37.
38. System.out.print("\nOdd numbers :");
39.
40. for (i = 0; i <= a.length - 1; i++)
41. {
42.
43. if (a[i] % 2 != 0)
44. {
45.
46. System.out.print(" " + a[i]);
47. }
48.
49. }
50.
51. System.out.print("\nEven numbers :");
52.
53. for (i = 0; i < a.length; i++)
54.
55. {
56. if (a[i] % 2 == 0)
57. {
58.
59. System.out.print(" " + a[i]);
60.
61. }
62.
63. }
64.
65. }
66.
67. }
68.

Output
Input numbers : 1 2 4 9 33 71 88 92
Odd numbers : 1 9 33 71
Even numbers : 2 4 88 92

Java Program to print Odd and Even Numbers from an Array

We can print odd and even numbers from an array in java by getting remainder of
each element and checking if it is divided by 2 or not. If it is divided by 2, it
is even number otherwise it is odd number.

public class OddEvenInArrayExample{


public static void main(String args[]){
int a[]={1,2,5,6,3,2};
System.out.println("Odd Numbers:");
for(int i=0;i<a.length;i++){
if(a[i]%2!=0){
System.out.println(a[i]);
}
}
System.out.println("Even Numbers:");
for(int i=0;i<a.length;i++){
if(a[i]%2==0){
System.out.println(a[i]);
}
}
}}

Odd Numbers:
1
5
3
Even Numbers:
2
6
2

Program to print the elements of an array present on even position

In this program, we need to print the element which is present on even position.
Even positioned element can be found by traversing the array and incrementing the
value of i by 2.

public class EvenPosition {


public static void main(String[] args) {

//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};

System.out.println("Elements of given array present on even position: ");


//Loop through the array by incrementing value of i by 2
//Here, i will start from 1 as first even positioned element is present at
position 1.
for (int i = 1; i < arr.length; i = i+2) {
System.out.println(arr[i]);
}
}
}

o/p:
Elements of given array present on even position:
2
4

Program to print the elements of an array present on odd position

In this program, we need to print the elements of the array which are present in
odd positions. This can be accomplished by looping through the array and printing
the elements of an array by incrementing i by 2 till the end of the array is
reached.

public class OddPosition {


public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
System.out.println("Elements of given array present on odd position: ");
//Loop through the array by incrementing value of i by 2
for (int i = 0; i < arr.length; i = i+2) {
System.out.println(arr[i]);
}
}
}
o/p:

Elements of given array present on odd position:


1
3
5

--------------------

21. Java program to add two matrix

package com.candidjava;

class MatrixAddition
{
public static void main(String args[])
{
int[][] a = new int[][] { { 1, 2, 3},{ 4, 5, 6},{ 7, 8, 9} };
int[][] b = new int[][] { { 10, 11, 12},{ 13, 14, 15},{ 16, 17, 18} };
int[][] c = new int[3][3];

if(a.length == b.length && a[0].length == b[0].length)


{
for(int i = 0;i < a.length;i++)
{
for(int j = 0;j < a[i].length;j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
}
else
{
System.out.println("'A' and 'B' Matrix are not SAME");
return;
}

System.out.println("The Matrix 'A' Value:");


for(int i = 0;i < a.length;i++)
{
for(int j = 0;j < a[i].length;j++)
{
System.out.print(a[i][j] + " ");
}
System.out.println();
}

System.out.println("The Matrix 'B' Value:");


for(int i = 0;i < a.length;i++)
{
for(int j = 0;j < a[i].length;j++)
{
System.out.print(b[i][j]+ " ");
}
System.out.println();
}
System.out.println("The Addition Matrix of 'A' and 'B' Value:");
for(int i = 0;i < a.length;i++)
{
for(int j = 0;j < a[i].length;j++)
{
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}

Output

The Matrix 'A' Value:


1 2 3
4 5 6
7 8 9
The Matrix 'B' Value:
10 11 12
13 14 15
16 17 18
The Addition Matrix of 'A' and 'B' Value:
11 13 15
17 19 21
23 25 27

Java Program to add two matrices

public class MatrixAdditionExample{


public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{2,4,3},{3,4,5}};
int b[][]={{1,3,4},{2,4,3},{1,2,4}};

//creating another matrix to store the sum of two matrices


int c[][]=new int[3][3]; //3 rows and 3 columns

//adding and printing addition of 2 matrices


for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j]; //use - for subtraction To subtract two matrices, use
- operator. Let's see a simple example to add two matrices of 3 rows and 3 columns.
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}}

o/p:

2 6 8
4 8 6
4 6 9
---------------
22. Java program to check given matrix is null matrix

package com.candidjava;

class NullMatrix
{
public static void main(String args[])
{
int[][] a = new int[][] { { 0, 0, 0},{ 0, 0, 1},{ 0, 0, 0} };
boolean setValue = true;

abc: for(int i = 0;i < a.length;i++)


{
for(int j = 0;j < a[i].length;j++)
{
if(a[i][j] != 0)
{
setValue = false;
break abc;
}
}
}

System.out.println("The Given Matrix Value:");


for(int i = 0;i < a.length;i++)
{
for(int j = 0;j < a[i].length;j++)
{
System.out.print(a[i][j] + " ");
}
System.out.println();
}

if(setValue == true)
{
System.out.println("The Given Matrix is a Null Matrix");
}
else
{
System.out.println("The Given Matrix is not a Null Matrix");
}
}
}

Output
The Given Matrix Value:
0 0 0
0 0 1
0 0 0
The Given Matrix is not a Null Matrix

----------

23. Java program to check given matrix is diagonal matrix


class DiagonalMatrix
{
public static void main(String args[])
{
int[][] a = new int[][] { { 1, 0, 1},{ 0, 3, 0},{ 0, 0, 3} };
boolean setValue = true;
abc: for(int i = 0;i < a.length;i++)
{
for(int j = 0;j < a[i].length;j++)
{
if(i == j)
{
if(a[i][j] == 0)
{
setValue = false;
break abc;
}
}
else if(a[i][j] != 0)
{
setValue = false;
break abc;
}
}
}

System.out.println("The Given Matrix Value:");


for(int i = 0;i < a.length;i++)
{
for(int j = 0;j < a[i].length;j++)
{
System.out.print(a[i][j] + " ");
}
System.out.println();
}

if(setValue == true)
{
System.out.println("The Given Matrix is a Diagonal Matrix");
}
else
{
System.out.println("The Given Matrix is not a Diagonal Matrix");
}
}
}

Output
The Given Matrix Value:
1 0 0
0 3 0
0 0 3
The Given Matrix is a Diagonal Matrix

-------------

24. Find the largest three elements in an array


Given an array with all distinct elements, find the largest three elements.
Expected time complexity is O(n) and extra space is O(1).
Examples :
Input: arr[] = {10, 4, 3, 50, 23, 90}
Output: 90, 50, 23
1) Initialize the largest three elements as minus infinite.
first = second = third = -∞

2) Iterate through all elements of array.


a) Let current array element be x.
b) If (x > first)
{
// This order of assignment is important
third = second
second = first
first = x
}
c) Else if (x > second)
{
third = second
second = x
}
d) Else if (x > third)
{
third = x
}

3) Print first, second and third.

// Java code to find largest three elements


// in an array

class PrintLargest
{
/* Function to print three largest elements */
static void print3largest(int arr[], int arr_size)
{
int i, first, second, third;

/* There should be atleast three elements */


if (arr_size < 3)
{
System.out.print(" Invalid Input ");
return;
}

third = first = second = Integer.MIN_VALUE;


for (i = 0; i < arr_size ; i ++)
{
/* If current element is greater than
first*/
if (arr[i] > first)
{
third = second;
second = first;
first = arr[i];
}
/* If arr[i] is in between first and
second then update second */
else if (arr[i] > second)
{
third = second;
second = arr[i];
}

else if (arr[i] > third)


third = arr[i];
}

System.out.println("Three largest elements are " +


first + " " + second + " " + third);
}

/* Driver program to test above function*/


public static void main (String[] args)
{
int arr[] = {12, 13, 1, 10, 34, 1};
int n = arr.length;
print3largest(arr, n);
}
}

Output :
Three largest elements are 34 13 12

Another approach:An efficient way to solve this problem is to use any O(nLogn)
sorting algorithm & simply returning the last 3 largest elements .

// Java code to find largest


// three elements in an array

import java.io.*;
import java.util.Arrays;

class GFG {
void find3largest(int[] arr)
{
Arrays.sort(arr); //It uses Tuned Quicksort with
//avg. case Time complexity = O(nLogn)
int n = arr.length;
int check = 0, count = 1;

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

if(count<4){
if(check!=arr[n-i])
{
// to handle duplicate values
System.out.print(arr[n-i]+" ");
check = arr[n-i];
count++;
}
}
else
break;
}

// Driver code
public static void main(String[] args)
{
GFG obj = new GFG();
int[] arr={12,45,1,-1,45,54,23,5,0,-10};
obj.find3largest(arr);
}

Output :
54 45 23

Program to print the largest element in an array

In this program, we need to find out the largest element present in the array and
display it. This can be accomplished by looping through the array from start to end
by comparing max with all the elements of an array. If any of element is greater
than max, then store a value of the element in max. Initially, max will hold the
value of the first element. At the end of the loop, max represents the largest
element in the array.

Program to print the largest element in an array


In the above array, initially, max will hold the value 25. In the 1st iteration,
max will be compared with 11, since 11 is less than max. Max will retain its value.
In the next iteration, it will be compared to 7, 7 is also less than max, no change
will be made to the max. Now, max will be compared to 75. 75 is greater than max so
that max will hold the value of 75. Continue this process until the end of the
array is reached. At the end of the loop, max will hold the largest element in the
array.

public class LargestElement_array {


public static void main(String[] args) {

//Initialize array
int [] arr = new int [] {25, 11, 7, 75, 56};
//Initialize max with first element of array.
int max = arr[0];
//Loop through the array
for (int i = 0; i < arr.length; i++) {
//Compare elements of array with max
if(arr[i] > max)
max = arr[i];
}
System.out.println("Largest element present in given array: " + max);
}
}
Largest element present in given array: 75

Program to print the smallest element in an array

In this program, we need to find out the smallest element present in the array.
This can be achieved by maintaining a variable min which initially will hold the
value of the first element. Loop through the array by comparing the value of min
with elements of the array. If any of the element's value is less than min, store
the value of the element in min.

Program to print the smallest element in an array


Consider above array. Initially, min will hold the value 25. In the 1st iteration,
min will be compared with 11. Since 11 is less than 25. Min will hold the value 11.
In a 2nd iteration, 11 will be compared with 7. Now, 7 is less than 11. So, min
will take the value 7. Continue this process until the end of the array is reached.
At last, min will hold the smallest value element in the array.

public class SmallestElement_array {


public static void main(String[] args) {

//Initialize array
int [] arr = new int [] {25, 11, 7, 75, 56};
//Initialize min with first element of array.
int min = arr[0];
//Loop through the array
for (int i = 0; i < arr.length; i++) {
//Compare elements of array with min
if(arr[i] <min)
min = arr[i];
}
System.out.println("Smallest element present in given array: " + min);
}
}

o/p:

Smallest element present in given array: 7

---------

25. Program to copy all elements of one array into another array

In this program, we need to copy all the elements of one array into another. This
can be accomplished by looping through the first array and store the elements of
the first array into the second array at the corresponding position.

public class CopyArray {


public static void main(String[] args) {
//Initialize array
int [] arr1 = new int [] {1, 2, 3, 4, 5};
//Create another array arr2 with size of arr1
int arr2[] = new int[arr1.length];
//Copying all elements of one array into another
for (int i = 0; i < arr1.length; i++) {
arr2[i] = arr1[i];
}
//Displaying elements of array arr1
System.out.println("Elements of original array: ");
for (int i = 0; i < arr1.length; i++) {
System.out.print(arr1[i] + " ");
}

System.out.println();

//Displaying elements of array arr2


System.out.println("Elements of new array: ");
for (int i = 0; i < arr2.length; i++) {
System.out.print(arr2[i] + " ");
}
}
}
Output:

Elements of original array


1 2 3 4 5
Elements of new array:
1 2 3 4 5

-------------
26. Program to left rotate the elements of an array

In this program, we need to rotate the elements of an array towards the left by the
specified number of times. In the left rotation, each element of the array will be
shifted to its left by one position and the first element of the array will be
added to end of the list. This process will be followed for a specified number of
times.

Program to left rotate the elements of an array


Consider above array, if n is 1 then, all elements of the array will be moved to
its left by one position such that second element of the array will take the first
position, the third element will be moved to the second position and so on. The
first element of the array will be added to the last of the array.

class RotateLeft {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
//n determine the number of times an array should be rotated
int n = 3;
//Displays original array
System.out.println("Original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
//Rotate the given array by n times toward left
for(int i = 0; i < n; i++){
int j, first;
//Stores the first element of the array
first = arr[0];
for(j = 0; j < arr.length-1; j++){
//Shift element of array by one
arr[j] = arr[j+1];
}
//First element of array will be added to the end
arr[j] = first;
}
System.out.println();
//Displays resulting array after rotation
System.out.println("Array after left rotation: ");
for(int i = 0; i< arr.length; i++){
System.out.print(arr[i] + " ");
}
}
}

output:

Original Array:
1 2 3 4 5
Array after left rotation:
4 5 1 2 3

---------------

27. Program to print the elements of an array

This is a simple program to create an array and then to print it's all elements.

Now, just know about arrays.

Arrays are the special variables that store multiple values under the same name in
the contiguous memory allocation. Elements of the array can be accessed through
their indexes.

public class PrintArray {


public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
System.out.println("Elements of given array: ");
//Loop through the array by incrementing value of i
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}

o/p:
Elements of given array:
1 2 3 4 5

Java Program to print the number of elements present in an array

public class CountArray {


public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
//Number of elements present in an array can be found using the length
System.out.println("Number of elements present in given array: " +
arr.length);
}

o/p:
Number of elements present in given array: 5
---------

28. Java Program to print the sum of all the items of the array

In this program, we need to calculate the sum of all the elements of an array. This
can be solved by looping through the array and add the value of the element in each
iteration to variable sum.

Java Program to print the sum of all the items of the array
Sum of all elements of an array is 1 + 2 + 3 + 4 + 5 = 15.

public class SumOfArray {


public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
int sum = 0;
//Loop through the array to calculate sum of elements
for (int i = 0; i < arr.length; i++) {
sum = sum + arr[i];
}
System.out.println("Sum of all the elements of an array: " + sum);
}
}

o/p:
Sum of all the elements of an array: 15

-----------------------------

29. Java Program to right rotate the elements of an array

In this program, we need to rotate the elements of array towards its right by the
specified number of times. An array is said to be right rotated if all elements of
the array are moved to its right by one position. One approach is to loop through
the array by shifting each element of the array to its next position. The last
element of the array will become the first element of the rotated array.

Java Program to right rotate the elements of an array


Consider the above array, if n is 1 then, all elements of the array will be moved
to its right by one position that is the first element of the array will take the
second position, the second element will be moved to the third position and so on.
The last element of the array will become the first element of the array.

Algorithm
STEP 1: START
STEP 2: INITIALIZE arr[] ={1, 2, 3, 4, 5 }.
STEP 3: SET n =3
STEP 4: PRINT "Original Array"
STEP 5: REPEAT STEP 6 UNTIL i<arr.length
//for(i=0; i<arr.length; i++)
STEP 6: PRINT arr[i]
STEP 7: REPEAT STEP 8 to STEP 12 UNTIL i<n
// for(i=0; i<n; i++ )
STEP 8: DEFINE j, last.
STEP 9: last = arr[arr.length-1]
STEP 10: REPEAT STEP 11 UNTIL j>0
//for(j= arr.length-1;j>0; j--)
STEP 11: arr[j]= arr[j-1]
STEP 12: arr[0]= last
STEP 13: PRINT "Array after right rotation"
STEP 14: REPEAT STEP 15 UNTIL i<arr.length
//for(i=0; i<arr.length; i++)
STEP 15: PRINT arr[i]
STEP 16: END

class RotateRight {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
//n determine the number of times an array should be rotated.
int n = 3;

//Displays original array


System.out.println("Original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}

//Rotate the given array by n times toward right


for(int i = 0; i < n; i++){
int j, last;
//Stores the last element of array
last = arr[arr.length-1];

for(j = arr.length-1; j > 0; j--){


//Shift element of array by one
arr[j] = arr[j-1];
}
//Last element of array will be added to the start of array.
arr[0] = last;
}

System.out.println();

//Displays resulting array after rotation


System.out.println("Array after right rotation: ");
for(int i = 0; i< arr.length; i++){
System.out.print(arr[i] + " ");
}
}
}

o/p:
Original Array:
1 2 3 4 5
Array after right rotation:
3 4 5 1 2

--------------

30. Java Program to sort the elements of an array in ascending order

public class SortAsc {


public static void main(String[] args) {

//Initialize array
int [] arr = new int [] {5, 2, 8, 7, 1};
int temp = 0;

//Displaying elements of original array


System.out.println("Elements of original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}

//Sort the array in ascending order


for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

System.out.println();

//Displaying elements of array after sorting


System.out.println("Elements of array sorted in ascending order: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}

o/p:
Elements of original array:
5 2 8 7 1
Elements of array sorted in ascending order:
1 2 5 7 8

----------------

31. Java Program to sort the elements of an array in descending order


public class SortDsc {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {5, 2, 8, 7, 1};
int temp = 0;

//Displaying elements of original array


System.out.println("Elements of original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}

//Sort the array in descending order


for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if(arr[i] < arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

System.out.println();

//Displaying elements of array after sorting


System.out.println("Elements of array sorted in descending order: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}

----------------
32. Java Program to find Third Largest Number in an Array

We can find the third largest number in an array in java by sorting the array and
returning the 3nd largest number. Let's see the full example to find the third
largest number in java array.

public class ThirdLargestInArrayExample{


public static int getThirdLargest(int[] a, int total){
int temp;
for (int i = 0; i < total; i++)
{
for (int j = i + 1; j < total; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a[total-3];
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};

System.out.println("Third Largest: "+getThirdLargest(a,6));


System.out.println("Third Largest: "+getThirdLargest(b,7));
}
}

o/p:
Third Largest:3
Third Largest:66

Java Program to find Second Largest Number in an Array

public class SecondLargestInArrayExample{


public static int getSecondLargest(int[] a, int total){
int temp;
for (int i = 0; i < total; i++)
{
for (int j = i + 1; j < total; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a[total-2];
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
System.out.println("Second Largest: "+getSecondLargest(a,6));
System.out.println("Second Largest: "+getSecondLargest(b,7));
}}

o/p:
Second Largest: 5
Second Largest: 77

Find 2nd Largest Number in Array using Arrays

import java.util.Arrays;
public class SecondLargestInArrayExample1{
public static int getSecondLargest(int[] a, int total){
Arrays.sort(a);
return a[total-2];
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
System.out.println("Second Largest: "+getSecondLargest(a,6));
System.out.println("Second Largest: "+getSecondLargest(b,7));
}}

o/p:
Second Largest: 5
Second Largest: 77

Find 2nd Largest Number in Array using Collections

import java.util.*;
public class SecondLargestInArrayExample2{
public static int getSecondLargest(Integer[] a, int total){
List<Integer> list=Arrays.asList(a);
Collections.sort(list);
int element=list.get(total-2);
return element;
}
public static void main(String args[]){
Integer a[]={1,2,5,6,3,2};
Integer b[]={44,66,99,77,33,22,55};
System.out.println("Second Largest: "+getSecondLargest(a,6));
System.out.println("Second Largest: "+getSecondLargest(b,7));
}}

o/p:
Second Largest: 5
Second Largest: 77

Java Program to find Largest Number in an Array

public class LargestInArrayExample{


public static int getLargest(int[] a, int total){
int temp;
for (int i = 0; i < total; i++)
{
for (int j = i + 1; j < total; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a[total-1];
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
System.out.println("Largest: "+getLargest(a,6));
System.out.println("Largest: "+getLargest(b,7));
}}

o/p:
Largest: 6
Largest: 99

---------------

33. Java Program to find Second Smallest Number in an Array

public class SecondSmallestInArrayExample{


public static int getSecondSmallest(int[] a, int total){
int temp;
for (int i = 0; i < total; i++)
{
for (int j = i + 1; j < total; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a[1];//2nd element because index starts from 0
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
System.out.println("Second smallest: "+getSecondSmallest(a,6));
System.out.println("Second smallest: "+getSecondSmallest(b,7));
}}

o/p:

Second smallest: 2
Second smallest: 33

Find 2nd Smallest Number in Array using Arrays

import java.util.*;
public class SecondSmallestInArrayExample1{
public static int getSecondSmallest(int[] a, int total){
Arrays.sort(a);
return a[1];
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
System.out.println("Second Smallest: "+getSecondSmallest(a,6));
System.out.println("Second Smallest: "+getSecondSmallest(b,7));
}}
o/p:

Second smallest: 2
Second smallest: 33

Find 2nd Smallest Number in Array using Collections

import java.util.*;
public class SecondSmallestInArrayExample2{
public static int getSecondSmallest(Integer[] a, int total){
List<Integer> list=Arrays.asList(a);
Collections.sort(list);
int element=list.get(1);
return element;
}
public static void main(String args[]){
Integer a[]={1,2,5,6,3,2};
Integer b[]={44,66,99,77,33,22,55};
System.out.println("Second Smallest: "+getSecondSmallest(a,6));
System.out.println("Second Smallest: "+getSecondSmallest(b,7));
}}

Second smallest: 2
Second smallest: 33

Java Program to find Smallest Number in an Array


We can find the smallest element or number in an array in java by sorting the array
and returning the 1st element. Let's see the full example to find the smallest
number in java array.

public class SmallestInArrayExample{


public static int getSmallest(int[] a, int total){
int temp;
for (int i = 0; i < total; i++)
{
for (int j = i + 1; j < total; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a[0];
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
System.out.println("Smallest: "+getSmallest(a,6));
System.out.println("Smallest: "+getSmallest(b,7));
}}
o/p:
Smallest: 1
Smallest: 22

Find Smallest Number in Array using Arrays

import java.util.*;
public class SmallestInArrayExample1{
public static int getSmallest(int[] a, int total){
Arrays.sort(a);
return a[0];
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
System.out.println("Smallest: "+getSmallest(a,6));
System.out.println("Smallest: "+getSmallest(b,7));
}}

Find Smallest Number in Array using Collections

import java.util.*;
public class SmallestInArrayExample2{
public static int getSmallest(Integer[] a, int total){
List<Integer> list=Arrays.asList(a);
Collections.sort(list);
int element=list.get(0);
return element;
}
public static void main(String args[]){
Integer a[]={1,2,5,6,3,2};
Integer b[]={44,66,99,77,33,22,55};
System.out.println("Smallest: "+getSmallest(a,6));
System.out.println("Smallest: "+getSmallest(b,7));
}}

o/p:
Smallest: 1
Smallest: 22

---------------------

34.Java Program to multiply two matrices

We can multiply two matrices in java using binary * operator and executing another
loop. A matrix is also known as array of arrays. We can add, subtract and multiply
matrices.

In case of matrix multiplication, one row element of first matrix is multiplied by


all columns of second matrix.

public class MatrixMultiplicationExample{


public static void main(String args[]){
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
//creating another matrix to store the multiplication of two matrices
int c[][]=new int[3][3]; //3 rows and 3 columns

//multiplying and printing multiplication of 2 matrices


for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
}}

o/p:

6 6 6
12 12 12
18 18 18

35. Java Program to transpose matrix

Converting rows of a matrix into columns and columns of a matrix into row is called
transpose of a matrix.

Let's see a simple example to transpose a matrix of 3 rows and 3 columns.

public class MatrixTransposeExample{


public static void main(String args[]){
//creating a matrix
int original[][]={{1,3,4},{2,4,3},{3,4,5}};

//creating another matrix to store transpose of a matrix


int transpose[][]=new int[3][3]; //3 rows and 3 columns

//Code to transpose a matrix


for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
transpose[i][j]=original[j][i];
}
}

System.out.println("Printing Matrix without transpose:");


for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(original[i][j]+" ");
}
System.out.println();//new line
}
System.out.println("Printing Matrix After Transpose:");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(transpose[i][j]+" ");
}
System.out.println();//new line
}
}}

o/p:

Printing Matrix without transpose:


1 3 4
2 4 3
3 4 5
Printing Matrix After Transpose:
1 2 3
3 4 4
4 3 5

Java program to transpose matrix (Another way)

You can also use a method where values of matrix are not predefined. Here, user has
to put the values as input.

import java.util.Scanner;
public class MatrixTransposeExample2
{
public static void main(String args[])
{
int i, j;
System.out.println("Enter total rows and columns: ");
Scanner s = new Scanner(System.in);
int row = s.nextInt();
int column = s.nextInt();
int array[][] = new int[row][column];
System.out.println("Enter matrix:");
for(i = 0; i < row; i++)
{
for(j = 0; j < column; j++)
{
array[i][j] = s.nextInt();
System.out.print(" ");
}
}
System.out.println("The above matrix before Transpose is ");
for(i = 0; i < row; i++)
{
for(j = 0; j < column; j++)
{
System.out.print(array[i][j]+" ");
}
System.out.println(" ");
}
System.out.println("The above matrix after Transpose is ");
for(i = 0; i < column; i++)
{
for(j = 0; j < row; j++)
{
System.out.print(array[j][i]+" ");
}
System.out.println(" ");
}
}
}

Java 8:

String reverse:

public class StringReverse {

public static void main(String[] args) {

String str="Ganesh is a Good boy";


String reversed = str.chars()
.mapToObj(c -> (char)c)
.reduce("", (s,c) -> c+s, (s1,s2) -> s2+s1);
System.out.println(reversed);

the canonical solution is

String reversed = new StringBuilder(str).reverse().toString();

import java.util.stream.Stream;
import java.util.stream.Collectors;

public class StringReverse2 {

public static void main(String[] args) {

System.out.println(reverse("Ganesh is a Good boy"));;


}
public static String reverse(String string) {
return Stream.of(string)
.map(word->new StringBuilder(word).reverse())
.collect(Collectors.joining(" "));
}
}

o/p: yob dooG a si hsenaG


---------

Find duplicate in an array


import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class DuplicateInArray {

public static void main(String[] args) {

List<Integer> numbers = Arrays.asList(new Integer[]{1,2,1,3,4,4});


numbers.stream().filter(i -> Collections.frequency(numbers, i) >1)
.collect(Collectors.toSet()).forEach(System.out::println);
}
}

--
Integer[] numbers = new Integer[] { 1, 2, 1, 3, 4, 4 };
Set<Integer> allItems = new HashSet<>();
Set<Integer> duplicates = Arrays.stream(numbers)
.filter(n -> !allItems.add(n)) //Set.add() returns false if the item was
already in the set.
.collect(Collectors.toSet());
System.out.println(duplicates); // [1, 4]

//Method 5 : Using Java 8 Streams

private static void findDuplicatesUsingJava8(int[] inputArray)


{
Set<Integer> uniqueElements = new HashSet<>();

Set<Integer> duplicateElements = Arrays.stream(inputArray)


.filter(i -> !
uniqueElements.add(i))
.boxed()
.collect(Collectors.toSet());

System.out.println(duplicateElements);
}

--------

/**
*
* A simple Java Program to to remove duplicates from Stream in Java 8
* This example uses Stream.distinct() method to remove
* duplicates.
*/
public class Hello {

public static void main(String args[]) {

List<Integer> withDupes = Arrays.asList(10, 10, 20, 20, 30, 30, 40, 50);

System.out.println("List with duplicates: " + withDupes);


List<Integer> withoutDupes = withDupes.stream()
.distinct()
.collect(Collectors.toList());

System.out.println("List without duplicates: " + withoutDupes);

}
}

Output
List with duplicates: [10, 10, 20, 20, 30, 30, 40, 50]
List without duplicates: [10, 20, 30, 40, 50]

You might also like