Lets see what is Array in Java,

“An Array is like a books in shelf ..”

Below 3 steps, explains how to declare, store elements, access array in Java.

1. Declare an int array variable. An array variable is a remote control to an array objects.

int[] books;

2. Create a new int array with a length of 8, and assign it to previously declared int[ ] variable books.

books = new int[8];

3. Give element in an array a int value. Remember, elements in an int array are just int variables.

books[0] = 20;
books[1] = 25;
books[2] = 30;
books[3] = 35;
books[4] = 40;
books[5] = 45;
books[6] = 50;

Note: An array itself is an object, even though it holds 7 primitives.

 

Arrays are objects too

Java provides lot of sophisticated data structures including maps, trees, set but Arrays are great to use when you need fast random access by letting you use an index position to get to any element in the array.

Every element in an array in just a variable. We could also say it as one of the eight primitive variable types or a reference variable. So, in an array of type int (int [ ]),  each element can hold an int.

Likewise in an array of AddressBook[ ], each element can hold a AddressBook? It is wrong, because the reference variable just holds a reference, not the object itself.

Arrays are always objects, whether they are declared to hold primitives or object reference.

Example

public class Book {

  String name;
  String author;
  int noOfPages;
}
public class BooksTester {

  public static void main(String[] args) {
    
    // make a book array
    Book[] booksInShelf = new Book[3];
    int x = 0;
    
    // store some book in book array reference
    booksInShelf[0] = new Book();
    booksInShelf[1] = new Book();
    booksInShelf[2] = new Book();
    
    //access the books using book array reference
    booksInShelf[0].name = "Wings of Fire";
    booksInShelf[0].author = "APJ Abdul kalam";
    booksInShelf[0].noOfPages = 300;
    
    booksInShelf[1].name = "Ignited Minds";
    booksInShelf[1].author = "APJ Abdul Kalam";
    booksInShelf[1].noOfPages = 250;

    booksInShelf[2].name = "India 2020";
    booksInShelf[2].author = "APJ Abdul Kalam";
    booksInShelf[2].noOfPages = 400;
    
    // looping through the array to get all reference information
    while(x<3){
      System.out.println("\""+booksInShelf[x].name+"\" is written by "+booksInShelf[x].author);
      x++;
    }
    
  }
}

Output

"Wings of Fire" is written by APJ Abdul kalam
"Ignited Minds" is written by APJ Abdul Kalam
"India 2020" is written by APJ Abdul Kalam

Conclusion

Hence we saw about, what is Array in Java, how to declare Array in Java, Elements of Array in Java, How Arrays become an object and object reference is used in accessing Array in Java.

Please follow and like us:
error