Home page

Wednesday, June 7, 2023

Array In JAVA

 public class ArrayExample {

    public static void main(String[] args) {

        // Declaring and initializing an array of integers

        int[] numbers = new int[5];

        numbers[0] = 10;

        numbers[1] = 20;

        numbers[2] = 30;

        numbers[3] = 40;

        numbers[4] = 50;


        // Accessing and printing elements of the array

        System.out.println("Element at index 0: " + numbers[0]);

        System.out.println("Element at index 2: " + numbers[2]);

        System.out.println("Element at index 4: " + numbers[4]);


        // Declaring and initializing an array of strings

        String[] names = { "Alice", "Bob", "Charlie", "David" };


        // Accessing and printing elements of the array

        System.out.println("Element at index 1: " + names[1]);

        System.out.println("Element at index 3: " + names[3]);

    }

}

In this example, we demonstrate two types of arrays: an array of integers (numbers) and an array of strings (names).

First, we declare and initialize the numbers array by specifying the size as 5 using new int[5]. Then, we assign values to each element of the array using the index. For example, numbers[0] = 10 sets the value 10 to the first element of the array.

Next, we access and print elements of the numbers array using the index. For instance, numbers[0] gives us the value at the first index, which is 10.

Similarly, we declare and initialize the names array using an array initializer, where we directly assign values to the array elements. We then access and print elements of the names array using the index.

Output:
Element at index 0: 10
Element at index 2: 30
Element at index 4: 50
Element at index 1: Bob
Element at index 3: David

No comments:

Post a Comment