0% found this document useful (0 votes)
2 views11 pages

One Dimensional Array in Java

Uploaded by

Pandiaraj A
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views11 pages

One Dimensional Array in Java

Uploaded by

Pandiaraj A
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

One Dimensional Array in Java

Overview
A one-dimensional array in Java is a collection of similar types of elements stored
at contiguous memory locations. The data is stored in a continuous manner, which
makes operations like search, delete, insert etc., much easier.

Arrays can be one-dimensional or multi-dimensional. One dimensional arrays can


store multiple values of the same primitive type such as int, float, long, String, etc.
or objects of the same class.

Introduction To Arrays
Imagine a class full of hundreds of students and the class teacher is required to take
attendance, check copies, distribute projects, etc. But the teacher is new and doesn't
remember the names of all students.

Now, how can she carry out her duties effectively without knowing the names of
the students? So, she came up with an idea to arrange the students in a line and
assign an increasing sequence of numbers, starting from 1, to the students.

Now she got a list of all the students with their associated numbers. It made her
task very simple as now she can keep a record of all activities of a student through
the sequence of numbers. Thus, arranging data in a continuous sequence proved to
be very useful.

In programming, this can be easily done with the help of Array data structure.
An array is used to store similar data elements in continuous memory locations,
and the elements are accessed with associated index values.

They can be visualized as containers holding similar types of items like numbers,
characters, objects, etc. in a continuous manner. The idea is to store multiple items
of the same type together so that operating on them becomes easier. It can be
understood as a fleet of stairs where each stair holds a certain item and the position
of each item can be known by finding out the number of steps taken.
Interestingly, a one-dimensional array in java is an object. They are dynamically
created and may be assigned to variables of type Object. An Object class in java is
the parent class of all classes by default. All the methods in the class Object can be
invoked on an array.

There are two types of array :

1. One-dimensional array
2. Multi-dimensional array

Let's dig more about one-dimensional arrays.

One-Dimensional Array In Java


It is clear from the name that a one-dimensional array in java must deal with
only one parameter. Entities of similar types can be stored together using one-
dimensional arrays. It can store primitive data types (int, float, char, etc.)
or objects.

Creating a one-dimension array in Java


A one-dimensional array can be visualized as a single row or a column of array
elements that are represented by a variable name and whose elements are accessed
by index values.

For example, the score of a series of football matches can be stored in a one-
dimensional array.

Declaration of one-dimensional array

So, let's see how we can declare a one-dimensional array in Java.

General form:
data-type var-name[];
OR
data-type[] var-name;
OR
data-type []var-name;

An array declaration has two components :

data-type: The data type determines the data type of each element present in the
array-like char, int, float, objects etc.

var-name: It is the name of the reference variable which points to the array object
stored in the heap memory.

[ ] : It is called subscript.

Example:
int Array[];

long longArray[];

float floatArray[];

double doubleArray[];

char charArray[];

The first statement just informs the compiler that this variable (Array) will hold an
array of the integer type. To link Array with an actual, physical array of integers,
we must allocate one using the new operator and assign it to Array.

Let's learn how to create an actual array.

Construction of one-dimensional array in Java


There are mainly two ways to create an array in java :

1. We can declare and store the values directly at the time of declaration :
int marks[ ] = { 90, 97, 95, 99, 100 };

Here JVM(Java Virtual Machine that drives the Java Code, converts
Java bytecode into machine language) will assign five contiguous memory
locations to store the values assigned to the array.
As shown in the diagram, JVM stores the elements in contiguous memory
locations. Each element position can be easily accessed through the index number
starting from 0 to n-1 where n is equal to the number of elements stored in the
array.

2. The second way of creating an array is by first declaring the array and then
allocating the memory through the new keyword :
var-name = new type[size];

Here size determines the max number of elements that can be stored in the array,
To allocate memory using new we must specify the type and number of elements
in the array.
int[] Number = new int[10];

JVM has allocated memory locations to store 10 integers but we have not yet
stored actual elements in the array. So, next, we'll look at how do elements get
stored in memory.

Memory representation after construction


The new int[10] initializes and creates an object referenced as number and assigns
memory to the object in heap segment.
By default, the new operator initializes the elements in the array
to zero(for numeric types), false(for Boolean), or null (for
reference types).
Array in java is index-based, the first element of the array is stored at 0th position,
the second element at 1st position, and so on. We can access each value of the
array by using numbers with subscript ([]). Like we can access the first element
through number[0]number[0], the second element
through number[1]number[1], and similarly the last element
through number[length−1]number[length−1].

Initialization of one-dimensional array


Let's code to add values to the one dimensional array :
public class AssignValues {

public static void main(String args[]) {


int number[]; // array declared
number = new int[10]; // allocating memory, initialization
number[0] = 11;
number[1] = 22;
number[2] = 33;
number[3] = 44;
number[4] = 55;
number[5] = 66;
number[6] = 77;
number[7] = 88;
number[8] = 99;
number[9] = 100;
}
}
Note:

 Since we chose int data type we can only add integer values to the array. So,
the type of variable depends on the data type of an array.
 The size of the array depends upon how many values we are providing at the
time of initialization.
 The size of one dimensional arrays cannot be changed once created.

Memory representation after initialization

One-Dimensional Array Examples


Example 1: standard method
The standard method includes declaring a variable and initializing it using new or
with a specialized set of values using array initializer.

General Syntax:
data_type[] var_name = new data_type[];
OR
data_type var_name[] = {}; // curly braces encloses
specialized set of values

For Example:
public class Example {

public static void main(String args[]) {


int arr[] = { 1, 5, 10, 15, 20 }; // initializing array
for (int i = 0; i < [Link]; i++) {
[Link](arr[i] + " "); // printing array
elements
}
}
}

Output :
1 5 10 15 20

In the above example, we created a one-dimensional array of type int and


stored 5 elements 1, 5, 10, 15,20 and set the arr variable to refer to the new array.
Each element of the array is accessed through its index value. Use this Java Online
Compiler to compile your code.

Example 2: using the scanner


The Scanner class is used to get user input, and it is found in the [Link] package.
It was introduced to make it easy to read basic data types from a character input
source.

To use the Scanner class, first we need to create a Scanner object. The constructor
specifies the source(Reader, InputStream, String or File) of the characters that the
Scanner will read in our program. The scanner acts as a wrapper for the input
source.

To take integer input from the user:


Scanner standardInputScanner = new Scanner([Link]);

// reads the next token from the input source


// and tries to convert it to a value of type int.
int input = [Link]();

Code:
import [Link];

public class OneDimensionalArrayInput {

public static void main(String args[]) {


// creating object of Scanner class
Scanner scan = new Scanner([Link]);

[Link]("Enter length of Array: ");


int arrLength = [Link]();

int[] anArray = new int[arrLength];


[Link]("Enter the elements of the Array");
for (int i = 0; i < arrLength; i++) {
// taking array input
anArray[i] = [Link]();
}

[Link]("One dimensional array elements


are:");
for (int i = 0; i < arrLength; i++) {
// printing array elements
[Link](anArray[i] + " ");
}
}
}

Output:
Enter length of Array:
5
Enter the elements of the Array
1
2
3
4
5
One dimensional array elements are:
1 2 3 4 5

Explanation:

Here we have used Scanner class to take input from the user and
the nextInt() method of the Scanner class to take integer input. It created an array
of sizes 5 with elements 1, 2, 3, 4,5.
Example 3: Using String
A String is a sequence of characters. It is an immutable object, which means its
value can not be changed. A String Array is an Array of a fixed number of String
values. String arrays are declared, stored and operated in the same way we handle
integer arrays.

Syntax:
String[] var_name = {};

Create String Array:


public class StringArray {

public static void main(String args[]) {


String[] array = { "Learning", "One-dimensional array",
"in java" };

[Link]("String array elements are:");

for (int i = 0; i < [Link]; i++) {


[Link](array[i]);
}
}
}

Output :
String array elements are:
Learning
One-dimensional array
in java

Benefits Of One-Dimensional Array


 Arrays help to maintain enormous data under a single variable name
 They help in accessing elements easily using the index number.
 No chance of extra memory being allocated, which avoids memory overflow
or shortage of memory in arrays.
 We can retrieve or sort the data easily using one-dimensional arrays.

Conclusion
 An array is a collection of similar types of elements stored at contiguous
locations. It can store primitive data types (int, char, float, etc.) or objects.
 One-dimensional array or single dimensional array must deal with values of
only one data type. One dimensional arrays can also store multiple objects
of the same class.
 An array in java is an object of a dynamically generated class that can be
initialized and created using the new operator.
 Array in java is index-based, the first element of the array is stored at
the 0th index, the second element at the 1st index, and so on.
 One dimensional arrays in Java are static in size. This means, once created,
the size of one dimensional arrays cannot be changed.

You might also like