Java Arrays

Java array is an object which contains elements of a similar data type.

There are two types of arrays.

  • Single Dimensional Array
  • Multidimensional Array 
Multidimensional Array are two types.
  • Two dimensional Array (2D)
  • Three dimensional Array (3D)    
          
               
Java Program to illustrate how to declare & initialize

public class Testarray {
public static void main(String[] args){
//declaration
int[] num = new int[5];
//initialization
num[0]=10;
num[1]=20;
num[2]=70;
num[3]=40;
num[4]=50;

for(int i=0;i<num.length;i++)//length is the property of array that returns the size of the array
System.out.println(num[i]);
}
}

Array ( finding sum and average )

public class SumAverage {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

double[] number = new double[5];
double sum = 0;

System.out.print("Enter 5 numbers : ");

for (int i=0; i<number.length; i++)
{
number[i] = input.nextDouble();
}

for (int i=0; i<number.length; i++)
{
sum = sum + number[i];
}

System.out.println("Sum is : "+sum);

double avg = sum/ number.length;
System.out.println("Avg is : "+avg);
}
}


Array (Finding Maximum & Minimum)

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

Scanner input = new Scanner(System.in);
double[] number = new double[5];

System.out.print("Enter 5 number : ");
for (int i = 0; i < number.length; i++) {
number[i] = input.nextDouble();
}

double max = number[0];
double min = number[0];

for (int i = 1; i < number.length; i++) {
if(max<number[i]) {
max = number[i];
}

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

System.out.println("Maximum Number : "+max);
System.out.println("Minimum Number : "+min);

}
}

For-each Loop for Java Array

We can also print the Java array using for-each loop. The Java for-each loop prints the array elements one by one. It holds an array element in a variable, then executes the body of the loop.

The syntax of the for-each loop is given below:

                                for(data_type variable:array)

                                    

                                            //body of the loop  

                                     }

public class ForEachLoop {
public static void main(String[] args) {
int[] num = {10,20,30,40,50};
int sum=0;

for(int x:num)
{
System.out.println(x);
sum+=x;
}
System.out.println("Sum is : "+sum);
}
}


This program prompts the user to enter a day number (1-7) and then prints the corresponding day name. The program will display an error message if the user enters a number outside the valid range (1-7). 

  •  Example 1:   Input -> Enter day number (1-7): 1          * Output -> Monday *
  •  Example 2:   Input -> Enter day number (1-7): 3          * Output -> Wednesday*

public class DayOfWeek {
public static void main(String[] args) {
// Declare an array of weekdays
String[] weekdays = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

// Create a Scanner object to read user input
Scanner input = new Scanner(System.in);
System.out.print("Enter day number (1-7): ");
int dayNumber = input.nextInt();

// Check if the day number is within the valid range
if (dayNumber >= 1 && dayNumber <= 7) {
System.out.println("Output-> " + weekdays[dayNumber - 1]);
} else {
// Print an error message for invalid day numbers
System.out.println("Error: Please enter a valid day number between 1 and 7.");
}
}
}

         

Two Dimensional Array



 Example :  
public class TwoDarray {
public static void main(String[] args) {

int[][] num = new int[2][3];

num[0][0] = 10;
num[0][1] = 20;
num[0][2] = 30;
num[1][0] = 40;
num[1][1] = 50;
num[1][2] = 60;

for(int row=0; row<2; row++)
{
for(int col=0; col<3; col++)
{
System.out.print(" "+num[row][col]);
}
System.out.println();
}
}
}                     


Adding Two matrix example :
public class Matrix {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

//Declaring Array
int[][] A = new int[2][3];
int[][] B = new int[2][3];
int[][] C = new int[2][3];

//Getting input for A matrix
System.out.println("Enter elements for A matrix : ");
for (int row = 0; row < 2; row++) {
for (int col = 0; col < 3; col++) {
System.out.printf("A[%d][%d] = ",row,col);
A[row][col] = input.nextInt();
}
}

System.out.println();
//Getting input for B matrix
System.out.println("Enter elements for B matrix : ");
for (int row = 0; row < 2; row++) {
for (int col = 0; col < 3; col++) {
System.out.printf("B[%d][%d] = ",row,col);
B[row][col] = input.nextInt();
}
}

System.out.println();
//Printing A matrix
System.out.print("A = ");
for (int row = 0; row < 2; row++) {
for (int col = 0; col < 3; col++) {
System.out.print("\t "+A[row][col]);
}
System.out.println();
}

System.out.println();
//Printing B matrix
System.out.print("B = ");
for (int row = 0; row < 2; row++) {
for (int col = 0; col < 3; col++) {
System.out.print("\t "+B[row][col]);
}
System.out.println();
}

System.out.println();
//Adding A and B matrix
System.out.print("A + B = ");
for (int row = 0; row < 2; row++) {
for (int col = 0; col < 3; col++) {
C[row][col] = A[row][col] + B[row][col];
System.out.print("\t "+C[row][col]);
}
System.out.println();
}
}
}
                                         
Diagonal Matrix
  • Diagonal elements: The main diagonal elements of a square matrix are the elements where the row index equals the column index. For an n \times n matrix, these elements are at positions (0,0), (1,1), (2,2), ..., (n-1, n-1).
  • Upper Triangle: The upper triangle of a square matrix includes all the elements on and above the main diagonal.
  • Lower Triangle: The lower triangle of a square matrix includes all the elements on and below the main diagonal.
  •  matrix:  An
    n \times n
    matrix is a square matrix that has the same number of rows and columns.
  • Example of a 3×3 Matrix:

Java Program to Calculate Sum of Diagonal, Upper Triangle, and Lower Triangle Elements of a 3x3 Matrix:
public class DiagonalMatrix {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

int[][] A = new int[3][3];
int sumofdiagonal=0,sumofupper=0,sumoflower=0;


//Getting input for A matrix
System.out.println("Enter elemets for 3*3 matrix : ");
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
System.out.printf("A[%d][%d] = ",row,col);
A[row][col] = input.nextInt();
}
}

//Diagonal,Upper,Lower
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {

if(row==col)
{
sumofdiagonal = sumofdiagonal + A[row][col];
}
if(row<col)
{
sumofupper = sumofupper + A[row][col];
}
if(row>col)
{
sumoflower = sumoflower + A[row][col];
}
}
}
System.out.println("Sum of Diagonal matrix : "+sumofdiagonal);
System.out.println("Sum of Upper elements : "+sumofupper);
System.out.println("Sum of Lower elements : "+sumoflower);

}
}


Java Program to Initialize and Print a Jagged Array
This Java program demonstrates how to initialize and print a jagged array. A jagged array is an array of arrays where each "row" can have a different length. This program creates a jagged array with 4 rows of increasing lengths, initializes its elements with consecutive integers, and then prints the array.
Example Output:
                                0
                                1 2
                                3 4 5 
                                6 7 8 9  
Program:
public class OutputProgram {
public static void main(String[] args) {

int[][] number = new int[4][];
int k = 0;

// Initializing jagged array with different row lengths
number[0] = new int[1];
number[1] = new int[2];
number[2] = new int[3];
number[3] = new int[4];

// Assigning consecutive integers to the jagged array
for (int i = 0; i < 4; i++) {
for (int j = 0; j < i + 1; j++) {
number[i][j] = k;
k++;
}
}

// Printing the jagged array
for (int i = 0; i < 4; i++) {
for (int j = 0; j < i + 1; j++) {
System.out.print(number[i][j] + " ");
}
System.out.println();
}
}
}

Java Program to Sort an Array in Ascending and Descending Order
public class AscDsc {
public static void main(String[] args) {
int[] number = {2, 1, 45, 34, 67, 0};

// Sorting Method
Arrays.sort(number);

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

System.out.println("\nDescending: ");
for (int i = number.length - 1; i >= 0; i--) { //dsc sorting logic
System.out.print(number[i] + " ");
}
}
}



Array List


Java program demonstrating basic ArrayList operations: adding elements, adding collections, checking if empty, getting, setting, finding index, removing, clearing, and comparing equality of ArrayLists.
public class AddRemove {
public static void main(String[] args) {
// Declaring Array List
ArrayList<Integer> number1 = new ArrayList<>();

// Adding Elements individually
number1.add(10);
number1.add(20);
number1.add(30);

// Adding a collection of elements using addAll
number1.addAll(Arrays.asList(40, 50, 60));

// Printing Array List
System.out.print("Array List number1 contains: ");
for (int x : number1) { // Using for-each loop
System.out.print(" " + x);
}
System.out.println();
System.out.println("Size of Array List number1: " + number1.size()); // See array size

// Check if an element exists using contains
System.out.println("Array List number1 contains 20: " + number1.contains(20));

// Get an element at a specific index using get
System.out.println("Element at index 2: " + number1.get(2));

// Set a new value at a specific index using set
number1.set(2, 35);
System.out.print("After setting value at index 2, Array List number1 contains: ");
for (int x : number1) { // Using for-each loop
System.out.print(" " + x);
}
System.out.println();

// Get the index of a specific element using indexOf
System.out.println("Index of element 50: " + number1.indexOf(50));

// Check if the Array List is empty using isEmpty
System.out.println("Is the Array List number1 empty? " + number1.isEmpty());

// Removing Elements
number1.remove(2);
System.out.print("After removing, Array List number1 contains: ");
for (int x : number1) { // Using for-each loop
System.out.print(" " + x);
}
System.out.println();
System.out.println("After removing, Size of Array List number1: " + number1.size());

// Declaring another Array List for comparison
ArrayList<Integer> number2 = new ArrayList<>(Arrays.asList(10, 20, 40, 50, 60));

// Comparing two Array Lists using equals
boolean areEqual = number1.equals(number2);
System.out.println("Are number1 and number2 equal? " + areEqual);

// Clear all elements in the Array List using clear
number1.clear();
System.out.println("After clearing, is the Array List number1 empty? " + number1.isEmpty());
}
}

Explanation:

  • Add Individual Elements: Adds elements (10, 20, 30) to number1 using the add method.
  • Add All: Uses addAll to add a collection of elements (40, 50, 60) to number1.
  • Printing Elements: Uses a for-each loop to iterate over and print the elements in number1.
  • Contains Method: Checks if number1 contains a specific element (20) and prints the result.
  • Get Method: Retrieves the element at index 2 in number1 and prints it.
  • Set Method: Updates the element at index 2 to a new value (35) and prints the updated list.
  • IndexOf Method: Finds the index of a specific element (50) in number1 and prints it.
  • IsEmpty Method: Checks if number1 is empty and prints the result.
  • Remove Element: Removes the element at index 2 in number1 and prints the updated list.
  • Equals Method: Declares another ArrayList (number2) with specific elements and uses equals
  •  to compare it with number1. Prints whether the two lists are equal.
  • Clear Method: Clears all elements from number1 and checks if it is empty.





Comments