JAVA ARRAY
JAVA ARRAY
Arrays are objects
that store multiple variables of the same type.
However, an array
itself is an object on the heap.
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.
DECLARING ARRAY
Data type [ ] arrayname;
•INSTANTIATING AN
ARRAY IN JAVA
var-name = new type
[size];
Example:
int intArray[]; //declaring array
intArray = new int[20]; // allocating
memory to array
Single dimentional
array
Example 1
class Testarray
{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Example
2
class Testarray1
{
public static void main(String args[])
{
int a[]={33,3,4,5};//declaration, instantiation and initialization
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
MULTIDIMENSIONAL ARRAY IN JAVA
In such case, data is
stored in row and column based index (also known as matrix form).
Syntax
dataType[][] arrayRefVar;
Example
int[][] arr=new int[3][3];//3 row and 3 column
class Testarray3
{
public static void main(String args[])
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Great
ReplyDelete