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

Java Arrays Examples

Uploaded by

aaishaeduc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Java Arrays Examples

Uploaded by

aaishaeduc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Example: declare an int array, initialize it with integers and print the elements of

the array using for loop.

public class JavaExample{


public static void main(String args[]){
//array declaration, instantiation and initialization
int number[] = {11, 22, 33, 44, 55};

//print array elements


//length property return the size of the array
for(int i=0;i<number.length;i++)
System.out.println("number["+i+"]: "+number[i]);
}
}

Example 2: Java Array with String Elements

public class JavaExample{


public static void main(String args[]){
//array declaration
String names[] = new String[5];

//array initialization
names[0]="Chaitanya";
names[1]="Ajeet";
names[2]="Rahul";
names[3]="Shivam";
names[4]="Rohit";

//print array elements


for(int i=0;i<names.length;i++)
System.out.println("names["+i+"]: "+names[i]);
}
}

Example 3: Java Multidimensional Arrays


public class JavaExample{
public static void main(String args[]){
//two rows and three columns
int arr[][]={{11,22,33},{44,55,66}};

//outer loop 0 till number of rows


for(int i=0;i<2;i++){
//inner loop from 0 till number of columns
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
//new line after each row
System.out.println();
}
}
}

Example 4: Print an Array elements using for-each loop

public class JavaExample{


public static void main(String args[]){
//String array
String names[]={"Chaitanya", "Ajeet", "Rahul", "Hari"};

//print array elements using for-each loop


for(String str:names)
System.out.println(str);

//int array
int numbers[]={1, 2, 3, 4, 5};

//print array elements using for-each loop


for(int num:numbers)
System.out.println(num);
}
}

Example 5:
public class JavaExample{
public static void main(String args[]){
int number[]={1, 5, 7, 9, 11};
for(int i=0;i<=number.length;i++){
System.out.println(number[i]);
}
}
}

Solutions:
Sorting Array Elements

import java.util.Scanner;
public class JavaExample
{
public static void main(String[] args)
{
int count, temp;
//User inputs the array size
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of elements you want in the array: ");
count = scan.nextInt();

int num[] = new int[count];


System.out.println("Enter array elements:");
for (int i = 0; i < count; i++)
{
num[i] = scan.nextInt();
}
scan.close();
for (int i = 0; i < count; i++)
{
for (int j = i + 1; j < count; j++) {
if (num[i] > num[j])
{
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
System.out.print("Array Elements in Ascending Order: ");
for (int i = 0; i < count - 1; i++)
{
System.out.print(num[i] + ", ");
}
System.out.print(num[count - 1]);
}
}

Adding two 2D matrices using arrays


public class JavaExample {
public static void main(String[] args) {
int rows = 2, columns = 4;

// Declaring the two matrices as multi-dimensional arrays


int[][] MatrixA = { {1, 1, 1, 1}, {2, 3, 5, 2} };
int[][] MatrixB = { {2, 3, 4, 5}, {2, 2, 4, -4} };

/* Declaring a matrix sum, that will be the sum of MatrixA


* and MatrixB, the sum matrix will have the same rows and
* columns as the given matrices.
*/
int[][] sum = new int[rows][columns];
for(int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
sum[i][j] = MatrixA[i][j] + MatrixB[i][j];
}
}
// Displaying the sum matrix
System.out.println("Sum of the given matrices is: ");
for(int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(sum[i][j] + " ");
}
System.out.println();
}
}
}

Java Program to count the frequency of each element in array (MODE)

public class JavaExample {


public static void main(String[] args) {
//Initializing an array
int [] numbers = new int [] {2, 2, 3, 4, 5, 5, 5, 3, 2, 4};
//This array will store the frequency of each element
int [] frequency = new int [numbers.length];
int counted = -1;
for(int i = 0; i < numbers.length; i++){
int count = 1;
for(int j = i+1; j < numbers.length; j++){
if(numbers[i] == numbers[j]){
count++;
//To avoid counting the frequency of same element again
frequency[j] = counted;
}
}
if(frequency[i] != counted)
frequency[i] = count;
}

//Printing the frequency of each element


for(int i = 0; i < frequency.length; i++){
if(frequency[i] != counted)
System.out.println("Element: "+numbers[i] + " Frequency: " +
frequency[i]);
}
}}

Sorting Char Array:


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

Java program to check whether two matrices are equal

??
Program to print duplicate elements of the String array

public class JavaExample {


public static void main(String[] args) {
//Initializing an int array
String [] names = new String [] {"Tom", "Steve", "Rick", "Steve", "Rick"};
System.out.println("Duplicate elements in the given array: ");
//Comparing each element of the array with all other elements
for(int i = 0; i < names.length; i++) {
for(int j = i + 1; j < names.length; j++) {
if(names[i].equals(names[j])){
//printing duplicate elements
System.out.println(names[j]);
}
}
}
}
}

Program to print duplicate elements of the int array

public class JavaExample {


public static void main(String[] args) {
//Initializing an int array
int [] numbers = new int [] {2, 4, 6, 8, 4, 6, 10, 10};
System.out.println("Duplicate elements in given array are: ");
//Comparing each element of the array with all other elements
for(int i = 0; i < numbers.length; i++) {
for(int j = i + 1; j < numbers.length; j++) {
if(numbers[i] == numbers[j]) {
//printing duplicate elements
System.out.println(numbers[j]);
}
}
}
}
}

Program to remove duplicate elements from a sorted array

ublic class JavaExample{


public static int removeDuplicates(int arr[], int count){
if (count==0 || count==1){
return count;
}
// creating a temporary array to hold non-duplicate elements
int[] temp = new int[count];
int j = 0;
for (int i=0; i<count-1; i++){
if (arr[i] != arr[i+1]){
temp[j++] = arr[i];
}
}
temp[j++] = arr[count-1];
// copying the temp array to the original array
for (int i=0; i<j; i++){
arr[i] = temp[i];
}
return j;
}
public static void main (String[] args) {
int arr[] = {1, 2, 2, 3, 4, 5, 5, 5};
System.out.print("Original Array: ");
int length = arr.length;
for (int i=0; i<length; i++)
System.out.print(arr[i]+" ");

//getting the new array size after removing duplicates


length = removeDuplicates(arr, length);

//for new line


System.out.println("");

//Displaying array with non-duplicate elements


System.out.print("Array after removing duplicate elements: ");
for (int i=0; i<length; i++)
System.out.print(arr[i]+" ");
}
}

Program to remove duplicate elements from an unsorted array


import java.util.Arrays;
public class JavaExample{
public static int removeDuplicates(int arr[], int count){
if (count==0 || count==1){
return count;
}
// creating a temporary array to hold non-duplicate elements
int[] temp = new int[count];
int j = 0;
for (int i=0; i<count-1; i++){
if (arr[i] != arr[i+1]){
temp[j++] = arr[i];
}
}
temp[j++] = arr[count-1];
// copying the temp array to the original array
for (int i=0; i<j; i++){
arr[i] = temp[i];
}
return j;
}

public static void main (String[] args) {


int arr[] = {3, 2, 1, 2, 9, 10, 4, 10, 9};
System.out.print("Original Array: ");

//Sorting the given unsorted array


Arrays.sort(arr);
int length = arr.length;
for (int i=0; i<length; i++)
System.out.print(arr[i]+" ");

//getting the new array size after removing duplicates


length = removeDuplicates(arr, length);

//for new line


System.out.println("");

//Displaying array with non-duplicate elements


System.out.print("Array after removing duplicate elements: ");
for (int i=0; i<length; i++)
System.out.print(arr[i]+" ");
}
}

2D array with variable row length


class MultiDimArrayDemo {
public static void main(String[] args) {
String[][] names = {
{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}
};
// Mr. Smith
System.out.println(names[0][0] + names[1][0]);
// Ms. Jones
System.out.println(names[0][2] + names[1][1]);
}
}

//Java Program to demonstrate the way of passing an array to method.


class Testarray2{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];

System.out.println(min);
}

public static void main(String args[]){


int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}}
//Java Program to demonstrate the way of passing an anonymous array
//to method.
public class TestAnonymousArray{
//creating a method which receives an array as a parameter
static void printArray(int arr[]){
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}

public static void main(String args[]){


printArray(new int[]{10,22,44,66});//passing anonymous array to method
}}

//Java Program to illustrate the jagged array


class TestJaggedArray{
public static void main(String[] args){
//declaring a 2D array with odd columns
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;

//printing the data of a jagged array


for (int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();//new line
}
}
}
Calculate sum and average through arrays

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

int[] numbers = {2, -9, 0, 5, 12, -25, 22, 9, 8, 12};


int sum = 0;
Double average;

// access all elements using for each loop


// add each element in sum
for (int number: numbers) {
sum += number;
}

// get the total number of elements


int arrayLength = numbers.length;

// calculate the average


// convert the average from int to double
average = ((double)sum / (double)arrayLength);

System.out.println("Sum = " + sum);


System.out.println("Average = " + average);
}
}

You might also like