One dimensional array in java with 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



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

One dimensional array construction

Array uses new operator to dynamically allocating memory locations.


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

Array uses zero based indexing where first element is stored in zero location. Last element is stored in array size-1 location.

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

Single dimensional array initialization in java

Array declaration and initialization can be done in one statement


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


Example age[0] access all first value of array we can use loop
We can print all values is age below

One dimensional array in java examples

Array programs in java


We can also use for each loop to show array elements

Java array programs


Array input in java

Scanner class is used here to get Input in the array.

Static array in java

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

Length of array in java

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.

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 array in java are arrays without name


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

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