Arrays in Java

Array is a collection of elements, of fixed size and type, for example, collection of 10 elements of type int. It is a data structure to group elements. In this lesson, we will learn how to work with arrays in Java Programming Language. Arrays in Java use index to access an element.

Here, we will discuss about one-dimensional and multidimensional arrays,

One-Dimensional Arrays

Arrays with a single dimension are one-dimensional arrays in Java. Let us see how to declare 1D arrays in Java:

Declaration and Initialization

For declaring one-dimensional array in Java Programming, you need to specify the datatype and the variable name like the following,

Above, datatype is the type of data you want the elements to be
variable_name is the name of the variable

The following example shows the correct way of declaring arrays in Java,

Above is an array of int. Here, we saw how to declare an array variable, with our variable name, marks. To create an array in Java and initialize it, use the new operator,

Above,

Using new to allocate an array, specify the type and how many elements you want.
variable_name: name of the variable
datatype[size]: creates a new array

Let us see an example that allocates 10 element array of integers and assigns reference of the array to the variable marks. These 10 elements are the marks of 10 students in a subject,

Now our array looks like,

Let us learn how to assign value to the elements. The indexes in array start with 0.

Right now, we have space for 10 elements. Add the index in the square brackets and insert value to the specified element, like

The following assigns the value 90 to the first element,

The following assigns the value 75 to the second element,

The following assigns the value 80 to the third element,

We can also assign values to elements like,

Let us see what we have done till now,

One-Dimensional Array in Java

As we saw above, add all the elements and run the entire example below,

First Array Program in Java

Showing the usage of one-dimensional array to add marks of 10 students,

The following is the output of the above example,

One Dimensional Arrays in Java Example

In this lesson, we learned arrays in Java and how to work with one-dimensional arrays. Multi-Dimensional Arrays are discussed in the next lesson.

Loops in Java
Multidimensional Arrays in Java
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading