Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

U -1 Array in java

Uploaded by

shivkailashsahu2
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

U -1 Array in java

Uploaded by

shivkailashsahu2
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Arrays

 Arrays are fundamental structures in Java


 Java array is an object which contains elements of a similar data type.
 Additionally, The elements of an array are stored in a contiguous memory location.
 It is a data structure where we store similar elements.
 We can store only a fixed set of elements in a Java array.
 Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored
on 1st index and so on.
 Java allows us to create single- or multi-dimensional arrays

Basics of Arrays in Java

There are some basic operations we can start with as mentioned below:

1. Array Declaration
To declare an array in Java, use the following syntax:

type[] arrayName;

 type: The data type of the array elements (e.g., int, String).

 arrayName: The name of the array.

Note: The array is not yet initialized.

2. Create an Array
To create an array, you need to allocate memory for it using the new keyword:

// Creating an array of 5 integers


numbers = new int[5];

This statement initializes the numbers array to hold 5 integers. The default value for each
element is 0.

3. Access an Element of an Array


We can access array elements using their index, which starts from 0:

// Setting the first element of the array


numbers[0] = 10;
// Accessing the first element
int firstElement = numbers[0];

The first line sets the value of the first element to 10. The second line retrieves the value of the
first element.

4. Change an Array Element


To change an element, assign a new value to a specific index:

// Changing the first element to 20


numbers[0] = 20;

5. Array Length
We can get the length of an array using the length property:

// Getting the length of the array


int length = numbers.length;

Array Properties
 In Java, all arrays are dynamically allocated.
 Arrays may be stored in contiguous memory [consecutive memory locations].
 Since arrays are objects in Java, we can find their length using the object property length. This is different
from C/C++, where we find length using size of.
 A Java array variable can also be declared like other variables with [] after the data type.
 The variables in the array are ordered, and each has an index beginning with 0.
 Java array can also be used as a static field, a local variable, or a method parameter.
 An array can contain primitives (int, char, etc.) and object (or non-primitive) references of a class,
depending on the definition of the array. In the case of primitive data types, the actual values might be
stored in contiguous memory locations (JVM does not guarantee this behavior). In the case of class
objects, the actual objects are stored in a heap segment.

Note: This storage of arrays helps us randomly access the elements of an array [Support
Random Access].

Creating, Initializing, and Accessing an Arrays in Java


For understanding the array we need to understand how it actually works. To understand this
follow the flow mentioned below:

 Declare
 Initialize
 Access
i. Declaring an Array
The general form of array declaration is

Method 1:
type var-name[];

Method 2:
type[] var-name;

The element type determines the data type of each element that comprises the array. Like an
array of integers, we can also create an array of other primitive data types like char, float,
double, etc., or user-defined data types (objects of a class).

Note: It is just how we can create is an array variable, no actual array exists. It merely tells
the compiler that this variable (int Array) will hold an array of the integer type.

Now, Let us provide memory storage to this created array.

ii. Initialization an Array in Java


When an array is declared, only a reference of an array is created. The general form of new as
it applies to one-dimensional arrays appears as follows:

var-name = new type [size];

Here, type specifies the type of data being allocated, size determines the number of elements
in the array, and var-name is the name of the array variable that is linked to the array. To
use new to allocate an array, you must specify the type and number of elements to
allocate.
Example:

// declaring array
int intArray[];

// allocating memory to array


intArray = new int[20];

// combining both statements in one


int[] intArray = new int[20];

Note: The elements in the array allocated by new will automatically be initialized to zero (for
numeric types), false (for boolean), or null (for reference types). Do refer to default array
values in Java.

Obtaining an array is a two-step process. First, you must declare a variable of the desired array
type. Second, you must allocate the memory to hold the array, using new, and assign it to the
array variable. Thus, in Java, all arrays are dynamically allocated.
Array Literal in Java
In a situation where the size of the array and variables of the array are already known, array
literals can be used.

// Declaring array literal


int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };

 The length of this array determines the length of the created array.

 There is no need to write the new int[] part in the latest versions of Java.

iii. Accessing Java Array Elements using for Loop


Now , we have created an Array with or without the values stored in it. Access becomes an
important part to operate over the values mentioned within the array indexes using the points
mentioned below:

 Each element in the array is accessed via its index.

 The index begins with 0 and ends at (total array size)-1.

 All the elements of array can be accessed using Java for Loop.

Let us check the syntax of basic for loop to traverse an array:

// Accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println(“Element at index ” + i + ” : “+ arr[i]);

// Java program to illustrate creating an array


// of integers, puts some values in the array,
// and prints each value to standard output.

class GFG {
public static void main(String[] args)
{
// declares an Array of integers.
int[] arr;

// allocating memory for 5 integers.


arr = new int[5];

// initialize the elements of the array


// first to last(fifth) element
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index "
+ i + " : " + arr[i]);
}
}

Output
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50

Types of Array in java


There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Single-Dimensional Array in Java


 These are the most common type of arrays

 A single-dimensional array in Java is a linear collection of elements of the same data type.

 It is declared and instantiated using the following syntax:

dataType[] arr; (or)


dataType []arr; (or)
dataType arr[];
Instantiation of an Array in Java

arrayRefVar=new datatype[size];
// A single-dimensional array
int[] singleDimArray = {1, 2, 3, 4, 5};
Multidimensional Array in Java
 A multidimensional array in Java is an array of arrays where each element can be an array itself.

 Multidimensional arrays are arrays of arrays with each element of the array holding the reference of other
arrays.

 These are also known as Jagged Arrays.

 Multidimensional arrays are useful when you want to store data as a tabular form, like a table with rows
and columns.

 A multidimensional array is created by appending one set of square brackets ([]) per dimension.

Syntax:
There are 2 methods to declare Java Multidimensional Arrays as mentioned below:

// Method 1
datatype [][] arrayrefvariable;

// Method 2
datatype arrayrefvariable[][];

Declaration:
// 2D array or matrix
int[][] intArray = new int[10][20];

// 3D array
int[][][] intArray = new int[10][20][10];

Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

myNumbers is now an array with two arrays as its elements.

Access Elements
To access the elements of the myNumbers array, specify two indexes: one for the array, and one
for the element inside that array. This example accesses the third element (2) in the second array
(1) of myNumbers:

Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

System.out.println(myNumbers[1][2]); // Outputs 7
Change Element Values
You can also change the value of an element:

Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

myNumbers[1][2] = 9;

System.out.println(myNumbers[1][2]); // Outputs 9 instead of 7

Loop Through a Multi-Dimensional Array


You can also use a for loop inside another for loop to get the elements of a two-dimensional array
(we still have to point to the two indexes):

Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

for (int i = 0; i < myNumbers.length; ++i) {

for (int j = 0; j < myNumbers[i].length; ++j) {

System.out.println(myNumbers[i][j]);

}
}

Or you could just use a for-each loop, which is considered easier to read and write:

Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

for (int[] row : myNumbers) {

for (int i : row) {

System.out.println(i);

You might also like