Java Arrays

Arrays in Java
 

1) Introduction:
> Java Array is an object that holds a fixed number of values of a single data type.

> The length of an Array is established when the Array is created.

> Array length is fixed, Java Array has Zero based index.

2) Declaration of Arrays in Java:
int abc []; // Array of Integers

abc = new int[10]; //creating Array and defning size.

System.out.println(abc.length); //Finding length of the Array.

abc[0] =10;
abc[1] = 20;
.
.
--------------
int [] abc = new int[5];

abc[0] =2;
abc[1] =3;
System.out.println(abc[0]+abc[1]);
------------------------------
int [] abc = {10, 20, 30, 40, 50} //Creating Array and Initializing

System.out.println(abc.length);
System.out.println(xyz[1]+xyz[2]);
//Priting Array
for (int i=0; i < xyz.length; i++) {
    System.out.println(xyz[i]);   
    }
-------------------
Creating Arrays (Different data types)
int [] array1 ={1, 2, 3, 4, 5}; // Array of Integers
char [] array2 ={'A', 'B', 'C'}; // Array of Characters
boolean [] array3 = {true, false, false, true,false}; // Array of Boolean values
String [] array4 = {"Selenium", "UFT", "Java", "LoadRunner"}; // Array of Strings
   
    System.out.println(array1[1]); // 2
    System.out.println(array2[1]); // B
    System.out.println(array3[1]); // false
    System.out.println(array4[0]); // Selenium
   
--------------------------------
3) Copy of values an Array into another Array
 

Example 1:int [] array1 ={1, 2, 3, 4, 5};
    int [] array2;
    array2 = array1;
   
    System.out.println(array2[2]);

Example 2:
int [] array1 ={1, 2, 3, 4, 5};
    int [] array2 = new int [array1.length];
   
    System.arraycopy(array1, 2, array2, 2, 3);
    System.out.println(array2[2]);

4) Advantages of Arrays:
 

> Using Arrays we can optimize the code, data can be retrieved or sorted easily.

> We can get required data using index position.

5) Disadvantages of Arrays
 

> We can store fixed number of elements only in the Array, It doesn't change its size at Runtime.

> An Array holds only one type of data.

6) Types of Arrays
 

a) Single dimensional Array

b) Multidimensional Array


Creating multidimensional Array:


int [][] abc = new int [3][4];

abc [0][0] =1;
abc [0][0] =2;
.
.
-----------
int xyz [][] = {{1, 3, 5, 7, 9}, {2, 4, 6, 8, 10}};
-----------------------------------------------------

Also Read:



Java Variables

Java Operators 

Java Conditional Statements 

Java Loop Statements

Java Methods

0 comments:

Post a Comment