Table of contents
- About Array
- Syntax for declaration, creating, initializing and accessing
- Array Length
- Array input and output
- Iterating Through Arrays
- Arrays.toString( ) Method
- Multi-Dimensional Arrays
- Array Manipulation
- Exceptions
- ArrayLists
- 1.Transpose of a matrix example
- 2.Swapping values in array
- 3.Maximum value in the array
- 4.Reversing the array
- Conclusion
About Array
In Java, an array is a fundamental data structure that allows the storage of multiple values of the same data type under a single variable name. Arrays provide a convenient way to manage collections of elements, such as integers, characters, or objects, in a sequential manner.
Syntax for declaration, creating, initializing and accessing
The syntax for declaring, creating, and initializing an array involves specifying the data type of the elements, followed by the array variable name, square brackets, and the size of the array (if known at the time of declaration).
1.Declaration:
// Syntax for declaring an array
data_type[] array_name;
Example:
//declare an array of integers
int[] numbers;
2.Initialization:
With Known Size:
// Syntax for creating and initializing an array with a known size array_name = new data_type[size];
Example:
// Creating and initializing an array of integers with a size of 5 numbers = new int[5];
Inline Initialization:
// Syntax for creating and initializing an aray with known values
data_type[] array_name = {value1, value2, ..., valueN};
Example:
// Creating and initializing an array of integers with specific values
int[] numbers = {1, 2, 3, 4,}
3.Accessing elements
// Syntax for accessing elements in an array
element_value = array_name[index];
Example:
// Accessing the third element in the array
int thirdElement = numbers[2];
Array Length
- You can find the length of an array using the
length
property.
int length = numbers.length; // Gets the length of the 'numbers' array
Array input and output
Below, I'll demonstrate how to read and display array elements from the user using the Scanner
class for input and a simple loop for output.
import java.util.*;
class HelloWorld {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int[][] arr=new int[3][3];
//Array input
for(int r=0; r<arr.length; r++){
for(int c=0; c<arr[r].length; c++){
arr[r][c]=sc.nextInt();
}
}
//Array output
for(int r=0; r<arr.length; r++){
for(int c=0; c<arr[r].length; c++){
System.out.print(arr[r][c]+ " ");
}
System.out.println();
}
}
Iterating Through Arrays
- Use loops like
for
orforeach
to iterate through array elements.
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
for (int num : arr) {
System.out.println(num);
}
Arrays.toString( ) Method
Returns a string representation of the contents of the specified array.
The string representation consists of a list of the array's elements, enclosed in square brackets (
"[]"
). Adjacent elements are separated by the characters", "
(a comma followed by a space).Elements are converted to strings as by
String.valueOf(int)
. Returns"null"
ifarr
isnull
.
// Create an array of integers
int[] numbers = {1, 2, 3, 4, 5};
// Use Arrays.toString to get a string representation of the array
String arrayString = Arrays.toString(numbers);
// Print the string representation
System.out.println("Array as a string: " + arrayString);
//Output : Array as a string: [1, 2, 3, 4, 5]
Multi-Dimensional Arrays
In Java, a multi-dimensional array is an array of arrays, allowing the organization of data in a grid-like structure. The most common type is a 2D array, representing a matrix with rows and columns. The syntax involves declaring the array with two sets of square brackets, specifying the dimensions.
- While declaring a 2D array in Java, it is not compulsory to add no of columns though, because they can change with each elements
int arr[][] = { {1, 2, 3}, {4, 5}, {6, 7, 8, 9, 10} };
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int element = matrix[1][2]; // Accesses the element at row 1, column 2 (value 6)
Array Manipulation
- Arrays can be sorted, searched, and modified using various methods and algorithms provided by Java.
Arrays.sort(numbers); // Sorts the 'numbers' array in ascending order
int index = Arrays.binarySearch(primeNumbers, 7); // Searches for the value 7 in 'primenumbers'
Exceptions
Be cautious to avoid accessing elements outside the array bounds, which can lead to ArrayIndexOutOfBoundsException
.
int outOfBounds = numbers[10]; // This will throw an exception if the array size is less than 11
ArrayLists
ArrayList is a part of collection framework and is present in java.util package. It provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed.
Syntax:
ArrayList<Type> str = new ArrayList<Type>();
The difference between a built-in array and an ArrayList
in Java, is that the size of an array cannot be modified (if you want to add or remove elements to/from an array, you have to create a new one). While elements can be added and removed from an ArrayList
whenever you want.
Example program
import java.io.*;
import java.util.*;
class HelloWorld {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
//declare arraylist with size n
ArrayList<Integer> arr1=new ArrayList<Integer>(n);
//declare arraylist without n
ArrayList<Integer> arr2=new ArrayList<Integer>();
//first print the two arrays
System.out.println("array1:" + arr1);
System.out.println("array2:" + arr2);
//append elements at the end of list
for(int i=0; i<n; i++){
arr1.add(i);
arr2.add(i);
}
//now print the array after appending elements
System.out.println("array1:" + arr1);
System.out.println("array2:" + arr2);
}
}
1.Transpose of a matrix example
import java.util.*;
class HelloWorld {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int r=sc.nextInt();
int c=sc.nextInt();
int a[][]=new int[r][c];
for(int i=0; i<r; i++){
for(int j=0; j<c; j++){
a[i][j]=sc.nextInt();
}
}
System.out.println("orginal mat: ");
for(int i=0; i<r; i++){
for(int j=0; j<c; j++){
System.out.print(a[i][j]+" ");
}
System.out.println();
}
System.out.println("tranpose mat: ");
for(int i=0; i<c; i++){
for(int j=0; j<r; j++){
System.out.print(a[j][i]+" ");
}
System.out.println();
}
}
}
Run the above code check the output on your compiler for better clarification.
2.Swapping values in array
import java.util.*;
class HelloWorld {
public static void main(String[] args) {
int[] arr={1,2,3,4,5,6};
swap(arr, 1,2); //index of the arr
System.out.print(Arrays.toString(arr));
}
static void swap(int[] arr, int i,int j){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
//output is [1,3,2,4,5,6]
3.Maximum value in the array
import java.util.*;
class HelloWorld {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] arr=new int[n];
for(int i=0; i<n; i++){
arr[i]=sc.nextInt();
}
System.out.print(max(arr));
}
static Integer max(int[] arr){
int m=arr[0];
for(int i=0; i<arr.length; i++){
if(m<arr[i]){
m=arr[i];
}
}
return m;
}
}//output: 5
// 23 45 36 87 56
// 87
4.Reversing the array
import java.util.*;
class HelloWorld {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] arr=new int[n];
for(int i=0; i<n; i++){
arr[i]=sc.nextInt();
}
for(int i=arr.length-1; i>=0; i--){
System.out.print(arr[i]+" ");
}
}
}//output: 4
//12 23 34 45
//45 34 23 12
Conclusion
In conclusion, arrays are the backbone of data storage and manipulation in Java. They offer an efficient means of organizing and managing collections of elements, streamlining code organization and enhancing readability. With the ability to access individual elements via indexing, arrays enable various data retrieval and manipulation tasks while reducing redundancy.
We've explored the essential aspects of arrays in Java, from their declaration and initialization to accessing elements and determining array length. Iteration through arrays, utilizing the Arrays.toString()
method for representation, and even handling multi-dimensional arrays have been discussed.
Stay tuned for more interesting topics on the way. Cheers to all, Happy coding!