[Go to site: main page, start]

0% found this document useful (0 votes)
3 views4 pages

Array Operations in Java Examples

Uploaded by

kaushikujjwal9
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views4 pages

Array Operations in Java Examples

Uploaded by

kaushikujjwal9
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Largest Element in an Array

public class LargestElement {

public static void main(String[] args) {

int[] arr = {10, 20, 4, 45, 99};

int max = arr[0];

for (int num : arr) {

if (num > max) {

max = num;

[Link]("Largest element is: " + max);

Output:

Largest element is: 99

Second Largest Element in an Array without Sorting

public class SecondLargest {

public static void main(String[] args) {

int[] arr = {12, 35, 1, 10, 34, 1};

int largest = Integer.MIN_VALUE, secondLargest = Integer.MIN_VALUE;

for (int num : arr) {

if (num > largest) {


secondLargest = largest;

largest = num;

} else if (num > secondLargest && num != largest) {

secondLargest = num;

[Link]("Second largest element is: " + secondLargest);

Output:

Second largest element is: 34

Check if the Array is Sorted

public class CheckSorted {

public static void main(String[] args) {

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

boolean isSorted = true;

for (int i = 1; i < [Link]; i++) {

if (arr[i] < arr[i - 1]) {

isSorted = false;

break;

[Link]("Array is sorted: " + isSorted);

}
}

Output:

Array is sorted: true

Remove Duplicates from Sorted Array

import [Link];

public class RemoveDuplicates {

public static void main(String[] args) {

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

int[] temp = new int[[Link]];

int j = 0;

for (int i = 0; i < [Link] - 1; i++) {

if (arr[i] != arr[i + 1]) {

temp[j++] = arr[i];

temp[j++] = arr[[Link] - 1];

int[] result = [Link](temp, j);

[Link]("Array after removing duplicates: " +

[Link](result));

}
Output:

Array after removing duplicates: [1, 2, 3, 4, 5]

Left Rotate an Array by One Place

import [Link];

public class LeftRotateOne {

public static void main(String[] args) {

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

int temp = arr[0];

for (int i = 0; i < [Link] - 1; i++) {

arr[i] = arr[i + 1];

arr[[Link] - 1] = temp;

[Link]("Array after left rotation by one place: " +

[Link](arr));

Output:

Array after left rotation by one place: [2, 3, 4, 5, 1]

You might also like