Arrays concept

Java Arrays

  • Normally, an array is a collection of similar type of elements which have a contiguous memory location.
  • Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.

  • Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on.

Advantages

  • Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
  • Random access: We can get any data located at an index position.

Disadvantages

  • Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in Java which grows automatically.

Types of Array in java

There are two types of array.
  • Single Dimensional Array
  • Multidimensional Array

Processing Arrays

When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known.

Single Dimensional Array in Java

Syntax to Declare an Array in Java
  1. dataType[] arr; (or)  
  2. dataType []arr; (or)  
  3. dataType arr[];  

  1. Instantiation of an Array in Java
    1. arrayRefVar=new datatype[size];  
  2. /Java Program to illustrate how to declare, instantiate, initialize  
  3. //and traverse the Java array.  
  4. class Testarray{  
  5. public static void main(String args[]){  
  6. int a[]=new int[5];//declaration and instantiation  
  7. a[0]=10;//initialization  
  8. a[1]=20;  
  9. a[2]=70;  
  10. a[3]=40;  
  11. a[4]=50;  
  12. //traversing array  
  13. for(int i=0;i<a.length;i++)//length is the property of array  
  14. System.out.println(a[i]);  
  15. }}  

Comments