What is Array in Java with Example - onlyxcodes

Saturday 20 May 2023

What is Array in Java with Example

Java arrays enable developers to store and handle multiple values under a single variable name, making them a crucial component of Java programming. 


Everything you need to know about Java arrays, including their syntax, types, and applications, will be covered in this tutorial.


array in java with example

Table Content

1. What is Array in Java?

2. Java Array Syntax

3. How to Initialize Arrays in Java?

4. How do you access an array element in Java?

5. How do you find the length of an array in Java?

6. How to get all values from array in Java?

7. How to Print string array values using for each loop in Java?

8. How can I change the value of an array in Java?

9. How do you swap array values in Java?

10. How to transfer array values to another array in Java?

11. What is Array Index out of Bounds Exception in Java?

12. How do you return an array from a function in Java?

13. How to add an object to an array in Java?


What is Array in Java?

An array is an object that is used to store a fixed-size collection of identical-type elements in Java. It offers a method of storing numerous instances of the same data type under the same variable name.


Because Java arrays have a fixed length, the size of the array must be specified at the time of creation and cannot be modified afterward. 


An array's elements are accessed using their index, which indicates where in the array they are located. 


The first element's index is 0, and the last element's index is the length of the array minus one.


Java Array Syntax

A chosen data type, square brackets ([]), the array name, and the number of members in the array are used to declare arrays in Java. 


Use the new keyword to make an array and give it a size:


This creates an array of integers with a length of 5.


Int[] numbers = new int[5];

How to Initialize Arrays in Java?

The array can also be initialized with particular values:


Here's an illustration:


Within the curly brackets, we declare an array of integers called "numbers" and set its initial value to 5. It should be noted that once an array is established, its fixed element count cannot be altered.


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

How do you access an array element in Java?

The index of the element that appears in square brackets after the array name in Java can be used to access an array element. 


The index, which starts at "0" for the first element in the array, indicates where the element is located inside the array.


Here is an illustration of accessing a Java array element:


We have an integer array called numbers in this example. You may get the value stored at a specific position in an array by putting the index in square brackets (numbers[index]).


class Test
{
	public static void main(String args[])
	{
		int[] numbers = {1, 2, 3, 4, 5};

		// Accessing the first element (index 0)
		
		int firstElement = numbers[0];
		System.out.println("First element: " + firstElement);

		
		// Accessing the third element (index 2)
		
		int thirdElement = numbers[2];
		System.out.println("Third element: " + thirdElement);

	}
}

Output:


First element: 1
Third element: 3

How do you find the length of an array in Java?

Java's length property can be used to determine an array's length. 


Here's an illustration:


The find_length variable in this example will be used to hold the array's element count, which in this case is 5. 


For arrays in Java, the length property can be applied to arrays of any type, including int[], String[], or Object[].


class Test
{
	public static void main(String args[])
	{
		int[] array = {1, 2, 3, 4, 5};
		int find_length = array.length;

		System.out.println("Length of the array: " + find_length);
	}
}

Output:


Length of the array: 5  

How to get all values from array in Java?

In Java, a loop can be used to repeatedly iterate over each element of an array to retrieve all of its contents. You can use a for loop or a for each loop among different types of loops. 


A for loop example is provided below:


An integer array with the values [1, 2, 3, 4, 5] is used in this example. 


Using the loop variable " i ", the for loop iterates through each array index. 


We use array[i] within the loop to read the value at each index and save it in the value variable. The value is then printed to the console.


class Test
{
	public static void main(String args[])
	{
		int[] array = {1, 2, 3, 4, 5};

		for (int i = 0; i < array.length; i++) 
		{
			int value = array[i];
			
			System.out.println(value);
		}
	}
}

Output:


1
2
3
4
5

Using foreach loop,


As an alternative, you can use a foreach loop to make the syntax simpler:


The foreach loop automatically assigns each element of the array to the value variable in this scenario. After that, the value is printed to the console.


To suit your particular array type and preferred output format, you can edit the code.


class Test
{
	public static void main(String args[])
	{
		int[] array = {1, 2, 3, 4, 5};

		for (int value : array) 
		{
			System.out.println(value);
		}
	}
}

Output:


1
2
3
4
5

How to Print string array values using for each loop in Java?

Java programmers can use a for-each loop to print the contents of a string array by performing the following steps:


Create a string array, then fill it with some data.


To go through each element of the array, use a for-each loop.


Print each element inside the loop.


Here is a sample of some code that illustrates this:


The string array named str in the example above has three elements: "usa," "united kingdom," and "australia." 


Each element in the array is iterated over and assigned to the variable element by the for-each loop. 


The element's value is then simply printed using System.out.println().


class Test
{
	public static void main(String args[])
	{
		String[] str = {"usa", "united kingdom", "australia"};

        // Using for-each loop to print the array elements
        for (String element : str) 
		{
            System.out.println(element);
		}
	}
}

Output:


When you run the above code, it will output:


Each element of the string array will be printed on a new line.


usa
united kingdom
australia

How can I change the value of an array in Java?

In Java, you may simply assign a new value to the desired array index to modify the value of an array element. Here's an illustration:


In this example, we have a numbers array containing the values 1, 2, 3, 4, and 5. 


The value at index 2 should be changed to 10. 


This is accomplished by immediately assigning the new value using the index notation: numbers[2] = 10.


class Test
{
	public static void main(String args[])
	{
		int[] numbers = {1, 2, 3, 4, 5};
        
        // Change the value at index 2
        numbers[2] = 10;
        
        // Print the modified array
        for (int i = 0; i < numbers.length; i++) 
		{
            System.out.println(numbers[i]);
        }
	}
}

Output:


If we print the elements of the array after changing the value, we will see the following output:


As you can see, the value at index 2 has been changed to 10.


1
2
10
4
5

How do you swap array values in Java?

Java allows you to swap array values by holding one of the values in a temporary variable while performing the swap. 


An illustration of how to change the values of two members in an array is given below:


In this illustration, a temporary variable called "temp" is used to switch the values at indexes "0" and "1". The changed array is printed to confirm the outcome after the swap.


Keep in mind that you can swap elements at any desired indexes within the array using the same logic.


class Test
{
	public static void main(String args[])
	{
		int[] array = {1, 2, 3, 4, 5};

        // Swapping the values at index 0 and 1
        int temp = array[0];
        array[0] = array[1];
        array[1] = temp;

        // Printing the modified array
        for (int i = 0; i < array.length; i++) 
		{
            System.out.print(array[i] + " ");
        }

	}
}

Output:


2 1 3 4 5

How to transfer array values to another array in Java?

In Java, you can use a loop or the System.arraycopy() function to move values from one array to another. 


Here are illustrations of both strategies:


Using a Loop:


class Test
{
	public static void main(String args[])
	{
		int[] sourceArray = {1, 2, 3, 4, 5};
		
		int[] destinationArray = new int[sourceArray.length];

		for (int i = 0; i < sourceArray.length; i++) 
		{
			destinationArray[i] = sourceArray[i];
			
			System.out.println(destinationArray[i]);
		}
		
	}
}

Output:


1
2
3
4
5

Using System.arraycopy():


class Test
{
	public static void main(String args[])
	{
		int[] sourceArray = {1, 2, 3, 4, 5};
		
		int[] destinationArray = new int[sourceArray.length];

		System.arraycopy(sourceArray, 0, destinationArray, 0, sourceArray.length);
		
		for (int i = 0; i < destinationArray.length; i++) 
		{
			System.out.println(destinationArray[i]);
		}

	}
}

Output:


1
2
3
4
5

Both strategies will copy the contents of sourceArray into a new array called destinationArray. Both of these methods will result in the same values in destinationArray as in sourceArray.


What is Array Index out of Bounds Exception in Java?

When you attempt to access an array element in Java using an index that is outside the array's valid range of indices, a "ArrayIndexOutOfBoundsException" is thrown. 


Every array in Java has a defined size that is established upon array creation, and the array elements' indices range from 0 to array.length - 1.


Java will issue a "ArrayIndexOutOfBoundsException" to indicate that you are attempting to access an invalid index when you try to access an array element using an index that is less than 0 or larger than or equal to the array's length.


For example, consider an array with length 5 (indices 0 to 4):


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

An "ArrayIndexOutOfBoundsException" will be raised if you attempt to access an element outside of this range, such as array[5] or array[-1]. 


This exception acts as a runtime warning and shows that your code is trying to access an incorrect array.


Make sure the index you use to access array elements is within the array's valid range of indices to avoid this exception from occurring.


How do you return an array from a function in Java?

The steps below describe how to return an array from a function in Java.


Declare an array type as the function's return type. For instance, you may use the following syntax to return an array of integers:  public static int[] functionName().


Within the function, create the array you wish to return.


To return an array from a function, use the return keyword and the array name.


Here is an illustration showing how to have a Java function return an array of integers:


The getNumbers() function returns an array of integers in this case. 


The getNumbers() function is called in the main() function, and the returned array is saved in the numbers variable. 


A for-each loop is then used to output the array's elements.


Make sure the returned array matches the defined type and that the correct array type is specified in the function definition.


class Test
{
	public static void main(String args[])
	{
		int[] numbers = getNumbers();
		
        for (int elements : numbers) 
		{
            System.out.println(elements);
        }

	}
	
	public static int[] getNumbers() 
	{
        int[] numbers = {1, 2, 3, 4, 5};
		
        return numbers;
    }

}

Output:


1
2
3
4
5

How to add an object to an array in Java?

Java allows you to add an object to an array by doing the following steps:


Make the desired size of objects in an array. To make an array of integers with a size of 10, for instance:


int[] arr = new int[5];

Declare and set the object's initial values before adding it to the array. 


For instance, here's how you add the integer 5:


int valueToAdd = 5;

Choose the index in the array at which you wish to add the object. The first index in an array is 0.


For instance, here's how to include the object at index 3:


int index = 3;

Put the object at the array's provided index:


array[index] = valueToAdd;

The object will be added to the array at the provided index after completing these steps. 


Keep in mind that for the assignment to be valid, the object must be of the same type as the elements of the array, or a comparable type.


Full Code,


class Test
{
	public static void main(String args[])
	{
		int[] arr = new int[5];
		
		arr[0] = 10;
		arr[1] = 20;
		arr[2] = 30;
		arr[3] = 40;
		arr[4] = 50;
		
		//orignal array
		
		System.out.println("Orignal Array");
		
		for(int values : arr)
		{
			System.out.println(values);
		}
		
		System.out.println("------------------------");
		
		int valueToAdd = 5;
		
		int index = 3;
		
		arr[index] = valueToAdd;
		
		//after add object in array
		
		System.out.println("After Add Object");
		
		for(int values : arr)
		{
			System.out.println(values);
		}
		
	}
	
}

Output:


Orignal Array
10
20
30
40
50
------------------------
After Add Object
10
20
30
5
50

No comments:

Post a Comment

Post Bottom Ad