One dimensional array in java with examples

Here we will discuss One dimensional array in java and cover basic examples

What is One dimensional (Single dimensional) array in java

An array is a collection of similar elements. All array elements are stored in the contiguous memory location.

One dimensional or single-dimensional array is an array with one dimension.

One dimensional array declaration in java

Syntax

Example

In the above declaration, age is a reference variable that will hold reference of array same for price and for names.

One dimensional array construction

The array uses a new operator to dynamically allocate memory locations.
Syntax

Example

the new operator will dynamically allocate memory for 5 integer values that are 5*4=20 bytes continuously.

The array uses zero-based indexing where the first element is stored in a zero location. The last element is stored in the array size-1 location.

We can assign values in array elements one by one as below

Single dimensional array initialization in java

Array declaration and initialization can be done in one statement
syntax

Example

Accessing array element: array element can be accessed by its index value.

Syntax

For example age[0] access all first value of the array we can use a loop
We can print all values in age below

One dimensional array in java examples

Array programs in java

Result

We can also use for each loop to show array elements

Java array programs

Output

Array input in java

The scanner class is used here to get Input in the array.

Static array in java

To create a static array add the keyword static before an array.

Length of array in java

the length property of an array is used to find the length of an array

How to store string in array in java

String to integer array in java

This program is taking a string as an argument converting it to StringTokenizer based on delimiter [,] and space.

A string tokenizer contains a set of string tokens these tokens are converted to an integer using Integer.parseInt().

above program can handle the following strings

String s1 = “1 2 3 4 5 6 7 8 9”; or

String s1 = “1,2,3,4,5,6,7,8,9”;

String s1 = “[1,2,3,4,5,6,7,8,9]”;

Anonymous array in java

anonymous arrays in java are arrays without a name

like

new Integer[]{1, 2, 3, 4, 5, 6, 7}

new String[]{“Ram”,”Mohan”,”Sohan”};