Monday, June 1, 2020

Arrays

Arrays
  • A single variable that can hold multiple values is called an array. i. e. array is used to store group of elements. These elements are homogeneous and fixed number. 
  • The main advantage of array is we can represent multiple values with a single variable
  • Arrays are index based and index starts from 0

Arrays Declarations:
  • One dimensional Array declaration:
int[] x , int []x; int x[] all are OK but recommended one is int[] x because name is clearly separated from type. At the time of declaration, we can not specify the size otherwise we will get compile time error. Example int[6] x; is invalid and int[] x is valid.

  • Two dimensional Array declaration:
int[][] x;

If we want to specify the dimension before the variable, that facility is applicable only for first variable in a declaration. If we are trying to apply for remaining variable, we will get compile time error.

  • Three dimensional array declaration:
int[][][] a;

Arrays Creation (Instantiation):
Every array in java are object only, hence we can create arrays by using new operator. We must specify the size of array at the time of array creation.
int[] a = new int[3]; here a is a reference variable. For every array type, corresponding classes are available and these classes are part of java language and not available to the programmer level.

Array Initialization:
Once we creates an array, every elements by default initializer with default values. Whenever we are trying to print any reference variable, internally toString() will be called, which is implemented  by default to return the string in the following form. classname@hashcode-inhexadecimalform. Every array element default initializer with default values. If we are not satisfied with default values then we can override these values with our customized values.

Array declaration, creation and initialization in single line:

We can declare, create and initialize an array in a single line (short-cut representation)

int[] x; //declaration
x = new int[3]; //instantiation
x[0] =10; //initialization
x[1] =20;
x[2] =30;
We can do it in a single line as:
int[] x = {10, 20, 30};


Ways to Print Arrays:

Example I:

public class ArrayDemo1 {
       public static void main(String[] args) {
             
             int[] a = { 10, 20, 30, 40 };
             
             System.out.println(".............directly print one by one..........");
             System.out.println(a[0]);// 1st approach to print array data
             System.out.println(a[1]);
             System.out.println(a[2]);
             System.out.println(a[3]);
             //using for loop
             System.out.println("...........print using for loop.............");
             for (int i = 0; i < a.length; i++)// 2nd approach
             {
                    System.out.println(a[i]);
             }
             System.out.println(".......print using enhanced for loop.......");
             for (int aa : a) {
                    System.out.println(aa);// 3rd approach
             }
             System.out.println("........boolean data...............");
             boolean[] b = new boolean[3];
             for (boolean bb : b) {
                    System.out.println(bb);
             }
       }
}
Output:

.............print one by one..........
10
20
30
40
...........print using for loop.............
10
20
30
40
.......print using enhanced for loop.......
10
20
30
40
........boolean data...............
false
false
false


Example II: When we create the array with instantiation, array is created with specified size with default values. When we initialize the values, default values will be replaced.

public class ArrayDemo2 {
       public static void main(String[] args) {
             int[] a = new int[5];
             a[0] = 10;
             a[1] = 20;
             a[2] = 30;
             // using for loop
             System.out.println("......using for loop...........");
             for (int i = 0; i < a.length; i++) {
                    System.out.println(a[i]);
             }
             
             System.out.println(".........using advanced for loop...........");
             boolean[] b = new boolean[3];
             for (boolean bb : b) {
                    System.out.println(bb);
             }
             
       }
}

Output:

......using for loop...........
10
20
30
0
0
.........using advanced for loop...........
false
false
false



Example III: array of size three and inserted three elements:

class Employee{
int eid;
String ename;
       public Employee(int eid, String ename) {
             this.eid = eid;
             this.ename = ename;
       }      
}
public class ArrayDemo3 {
public static void main(String[] args) {
       
       Employee[] e = new Employee[3];

       e[0] = new Employee(111, "Ratan");
       e[2] = new Employee(222, "Anu");
       e[4] = new Employee(333, "Durga");
       
       for (Employee ee: e) {
             System.out.println(ee.eid +"..."+ ee.ename);
       }
}
}

Output:

111...Ratan
222...Anu
333...Durga

Example IV: When array size is different from no of elements, NullPointerException occurs:

class Employee{
int eid;
String ename;
       public Employee(int eid, String ename) {
             this.eid = eid;
             this.ename = ename;
       }      
}
public class ArrayDemo3 {
public static void main(String[] args) {
     
       
       Employee[] e = new Employee[5];
This statement creates the array which can hold references to five Employee objects. It does not create the Employee objects themselves. They have to be created separately by using the constructor of Employee class. e contains five memory spaces in which the address of five Employee objects may be stored. If we try to access the Employee objects even before creating them, runtime error would occur. For example, e.eid = 111; throws NullPointerException during runtime which indicates that e[0] is not yet pointing to a Employee object. 

       e[0] = new Employee(111, "Ratan");
       e[2] = new Employee(222, "Anu");
       e[4] = new Employee(333, "Durga");

       for (Employee ee: e) {
             System.out.println(ee.eid +"..."+ ee.ename);
       }
}
}

Output:

111...Ratan
Exception in thread "main" java.lang.NullPointerException
       at com.cerotid.ratanjavavideos.learning.ArrayDemo3.main(ArrayDemo3.java:22)

Example V: When Employee contain null data and Employee data, to store both data, use Object class (i.e. array contains both null data and Employee data):

public static void main(String[] args) {
       
       Employee[] e = new Employee[5];

       e[0] = new Employee(111, "Ratan");
       e[2] = new Employee(222, "Anu");
       e[4] = new Employee(333, "Durga");
       
       for (Object o: e) {
             if(o instanceof Employee) {
                    Employee ee = (Employee)o;                   // converting object into Employee
                    System.out.println(ee.eid +"..."+ee.ename); // instanceof operator is used to find the type of object
             }
             if (o == null) {
                    System.out.println(o);
             }
       }
}
}

Output:
111...Ratan
null
222...Anu
null
333...Durga

Example VI: When we have integer array of size 5 and two locations have null values, how to find the index of these values?
package com.cerotid.ratanjavavideos.learning;
class Employee{
int eid;
String ename;
       public Employee(int eid, String ename) {
             this.eid = eid;
             this.ename = ename;
       }      
}
public class ArrayDemo3 {
public static void main(String[] args) {
       
       Employee[] e = new Employee[5];

       e[0] = new Employee(111, "Ratan");
       e[2] = new Employee(222, "Anu");
       e[4] = new Employee(333, "Durga");
       
       /*for (Object o: e) {
             if(o instanceof Employee) {
                    Employee ee = (Employee)o;                   // converting object into Employee
                    System.out.println(ee.eid +"..."+ee.ename); // instanceof operator is used to find the type
             }                                              // object
             if (o == null) {
                    System.out.println(o);
             }*/
       
       for (int i = 0; i<e.length; i++) {
             if (e[i]== null) {
                    System.out.println(i);
             }
       }
       }
}
Output:
1
3

Example VII: Example showing difference between length and length();
public class ArrayDemo4 {
       public static void main(String[] args) {
int[] a = new int[5];
System.out.println(a.length); // length is a variable used to find the size of array
String str = "Ratan";
System.out.println(str.length()); // length() is a method used to find the length of String
       }
}
Output:
5
5

Example VIII: How to represent the method return type and argument as array: (method return type is integer and argument is the array)
public class MethodReturnTypeArray {
       int[] m1() {
             System.out.println("m1 method");
             int[] a = { 10, 20, 30 };
             return a;
       }
       void m2(double[] d) {
             System.out.println("m2 method");
             for (double dd : d) {
                    System.out.println(dd);
             }
       }
       public static void main(String[] args) {
             MethodReturnTypeArray t = new MethodReturnTypeArray();
             int[] x = t.m1();
             for (int xx : x) {
                    System.out.println(xx);
             }
             double[] d = { 10.4, 20.5, 30.6 };
             t.m2(d);
       }
}
Output:
10
20
30
m2 method
10.4
20.5
30.6

Limitations of Arrays:
  • Arrays are fixed in size i. e. once we create an array with some size, there is no way we can increase or decrease its size based on our requirement. Hence, in order to use array, we need to know the size in advance which may not be possible always.
  • Arrays can hold only homogeneous data type elements
Example
Student[] s = new Student[10000];
s[0] = new Student;(correct) but s[1] = new Customer(); (wrong)

We can resolve this problem by using object arrays. Object array (array of Objects) is able to store any type of data (for example Employee data, Student data, Customer data etc.). The 'instanceof operator' is used to check the type of object
Object [] o = new Object[1000];
o[0] = new Student();
o[1] = new Customer();
Example I:
public class ObjectArrary {
       public static void main(String[] args) {
             Object[] o = new Object[3];

             o[0] = new Emp(111, "Ratan");
             o[1] = new Student(1, "aaa");
             o[2] = new Integer(10);

             for (Object oo : o) {
                    if (oo instanceof Emp) {
                          Emp e = (Emp) oo;      //for user defined type, we need to do type cast
                          System.out.println(e.eid + "..." + e.ename);
                    }
                    if (oo instanceof Student) {
                          Student s = (Student) oo;
                          System.out.println(s.sid + "..." + s.sname);
                    }
                    if (oo instanceof Integer) {   // for wrapper classes, no need of type casting
                          System.out.println(oo);
                    }
             }
       }
}
Output:
111...Ratan
1...aaa
10

Example II:
class Animal {}
class Dog extends Animal {}
class Puppy extends Dog {}
public class ArrayExample {
       public static void main(String[] args) {
             Animal[] a = new Animal[3];
             a[0] = new Animal();
             a[1] = new Dog();
             a[2] = new Puppy();
             for (Animal aa : a) {
                    System.out.println(aa.toString()); //line 16 and 17 are same
                    System.out.println(aa);            //When you print the reference variable, internally it calls toString()
             }
       }
}

output:
com.cerotid.ratanjavavideos.learning.Animal@15db9742
com.cerotid.ratanjavavideos.learning.Animal@15db9742
com.cerotid.ratanjavavideos.learning.Dog@6d06d69c
com.cerotid.ratanjavavideos.learning.Dog@6d06d69c
com.cerotid.ratanjavavideos.learning.Puppy@7852e922
com.cerotid.ratanjavavideos.learning.Puppy@7852e922
  • There is no underlying data structure i.e. arrays do not support predefined methods. We have to write code explicitly, which is complexity of program.

Array vs ArrayList in Java

Array is a fixed length data structure whereas ArrayList is a variable length Collection class. We cannot change length of array once created in Java but ArrayList can be changed.
We cannot store primitives in ArrayList, it can only store objects. But array can contain both primitives and objects in Java. Since Java 5, primitives are automatically converted to objects which is known as auto-boxing.
import java.util.*;
public class ListExample {
public static void main(String[] args) {
List<Integer> list=new ArrayList<>();
list.add(Integer.valueOf(10));//storing Integer object
list.add(20);//Now compiler converts it into Integer.valueOf(20) which is object
(The ints are cast to Integer implicitly)
list.add(30);
System.out.println("Traversing List...");
for(Integer i:list){
System.out.println(i);
}
}
}

Create an ArrayList object called cars that will store strings:
import java.util.ArrayList; // import the ArrayList class
ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object


No comments:

Post a Comment