Introduction to Array - The Coding Shala

Home >> Data Structures >> Introduction to Array

Introduction to Array

An Array is a data structure used to store a collection of elements sequentially. we store elements of the same type in an array for example elements can be int, char or String, etc. We can access elements in array randomly or by index. 
The weakness of array is array must be implemented in contiguous memory.

NOTE: The index of an array starts with zero(0).

Arrays are two types: 
  • One-dimensional array(liner array)
  • Multi-dimensional array
The following example explains the basic operations of an Array: 

import java.util.Arrays;

//Array Example
public class Main{
 public static void main(String[] args) {
  int[] arr = new int[5]; //array arr with size 5 type int
  int[] arr2 = {4,2,1};//we can decalre like this also
  
  //we access element with index(0 to length)
  int len1 = arr.length; //get length of array
  
  //insert element in array
  for(int i=0;i<len1;i++) {
   arr[i] = i;
  }
  
  //accessing element
  for(int i=0;i<len1;i++) {
   System.out.print(arr[i]+" ");
  }
  System.out.println();
  //accessing element with index
  System.out.println("Element at index 1 in array arr2 is: "+arr2[1]);
  
  //change element with index
  arr2[1] = 10;
  System.out.println("Element at index 1 in array arr2 is: "+arr2[1]);
  
  //for each loop in array
  System.out.println("Before sorting arr2 is: ");
  for(int i : arr2) {
   System.out.print(i +" ");
  }
  
  //sort an array
  Arrays.sort(arr2);
  System.out.println();
  System.out.println("After sorting arr2");
  for(int i=0; i<arr2.length;i++) {
   System.out.print(arr2[i]+" ");
  }
 }
}
Output: 

0 1 2 3 4 
Element at index 1 in array arr2 is: 2
Element at index 1 in array arr2 is: 10
Before sorting arr2 is: 
4 10 1 
After sorting arr2
1 4 10 

To know more about Arrays in Java  Java Arrays.


Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Add two numbers in Scala - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

New Year Chaos Solution - The Coding Shala

Goal Parser Interpretation LeetCode Solution - The Coding Shala