Array PDF
Array PDF
ARRAYS
Java Array is an Object that holds a fixed number of values of a single data type.
The length of Array is established when the Array is created.
Array length is fixed, index starts from zero to n1.
CREATING OF ARRAYS
1st Method
Syntax
dataType arrayName []; //Creating Array
arrayName = new dataType[size]; //Define Size
arrayName[0]=value;//Assign value
arrayName[1]=value;
arrayName[2]=value;
Example
public static void main(String args[])
{
int a [];
a = new int[3];
a[0]=10;
a[1]=20;
a[2]=30;
System.out.println(a[0]);//10
System.out.println(a[1] + a[2]);//50
}
2nd Method
Syntax
dataType [] arrayName= new dataType[length]; //Declare Array with length
arrayName[index] = value; //Assign value
Example
public static void main(String args[])
Kamal Subramani
2
{
int [] abc = new int [4];
abc[1] =10;
System.out.println(abc[1]); //10
3rd Method
Syntax
dataType [] arrayName = {value1, value2, value3} //Declare Array and Assign values
Example
public static void main(String args[])
{
int [] xyz = {10, 20, 30, 40};
System.out.println(xyz[2]);//30
}
DECLARING DIFFERENT TYPES OF ARRAYS
Example
public static void main(String[] args)
{
char [] abc = {'A', 'B', 'Z'}; //Array of Characters
int [] xyz = {10, 20, 30, 40}; //Array of Integers
String [] a = {"UFT", "Selenium", "RFT"}; //Array of Strings
boolean [] b ={true, false, false, true}; //Array of Boolean values
System.out.println(abc[1]);//B
System.out.println(xyz[3]);//40
System.out.println(a[1]);//Selenium
System.out.println(b[2]);//false
}
Kamal Subramani
3
{
System.out.println(array2[i]);
}
}
TYPES OF ARRAYS
1. Single dimensional Array
2. Multi dimensional Array
Example
public static void main(String[] args)
{
int [] [] array2 = {{1, 3, 5, 7}, {2, 4, 6, 8}};//Multi dimensional Array
System.out.println(array2[0][0]);//1
System.out.println(array2[1][0]);//2
System.out.println(array2[1][2]);//6
}
ADVANTAGES:
Using Arrays we can optimize the code, data can be retrieved easily.
We can get required data using index position
DISADVANTAGES:
We can store fixed number of Elements only.
It doesn't change its size during execution.
Kamal Subramani