Java Array

Complete Array Tutorial in Java with Programming Example

Java ArrayIn this chapter you will learn:

  1. What is an Array?
  2. Single Dimensional Array vs. Multi-Dimensional Array
  3. How to pass an array to method
  4. Array Class and Manipulation

What is an array?

An array is a collection of data of same data type. It is like a container object which holds fixed number of same type value. The size of array is defined when initialized array. The item stored in array is called element and each element is accessed by index position. Normally the first index position of array is 0.

Array

Types of Array

There are two types of array in Java.

  1. Single Dimensional Array
  2. Multi-Dimensional Array

Single Dimensional Array

Single dimensional array has only one row of data. It is also considered as simple type array. The data can be stored or accessed using simple for loop or other looping constructs.

Initialization:

Array

In the above example there are 8 elements in array which stores data in following manner.

Index position 0 = 23
Index position 1 = 55
Index position 2 = 34
Index position 3 = 90
Index position 4 = 37
Index position 5 = 77
Index position 6 = 16
Index position 7 = 56

Programming Example

Output

Index Position: 0 Value = 23
Index Position: 1 Value = 55
Index Position: 2 Value = 34
Index Position: 3 Value = 90
Index Position: 4 Value = 37
Index Position: 5 Value = 77
Index Position: 6 Value = 16
Index Position: 7 Value = 56D:\JavaProgram>__

Multi-Dimensional Array

Multi-Dimensional array have more than one row of data. It is actually a set of single dimensional array. To access multi-dimensional array data you need to use nested loop.

Initialization

Multi Dimensional Array

Programming Example

Output

book[0][0] = Book  book[0][1] = AuthorName  book[0][2] = Age
– – – – – – – – – – – – – – – – – – – – – – – – – – – – – –
book[1][0] = C#   book[1][1] = Lyric Angel   book[1][2] = 30
– – – – – – – – – – – – – – – – – – – – – – – – – – – – – –
book[2][0] = Java  book[2][1] = Eddy Angelil   book[2][2] = 34
– – – – – – – – – – – – – – – – – – – – – – – – – – – – – –
book[3][0] = PHP  book[3][1] = Raine Finley   book[3][2] = 28
– – – – – – – – – – – – – – – – – – – – – – – – – – – – – –
_

Pass Array to a method

You can also pass an array to method. The method will process the array and return output as per your programming logic. Here, we are including a programming example in which we have created two methods that will return largest number and smallest number.

Programming Example

Output

Largest Number is 65
Smallest Number is 10
_

Summary

In this chapter you have learned complete details of java array with programming examples. All topics are explained with suitable programming examples. In the next chapter you will learn about Strings and Collections.



Leave a Reply

Your email address will not be published. Required fields are marked *