Tag Archives: Array Length

Array Data Structure and Complexity (Big-O)


“Array is collection (or group of) of homogeneous (same data type) items  referred to single variable, which store in contiguous space in memory.”

Note : Java works differently then they do in C/C++, In Java array elements are not stored in continuous locations.

For example: You have 10 integer numbers and want minimum, maximum and  average of these numbers. One way is take 10 variables and perform comparison and operations of these numbers. If numbers are in hundreds very difficult to deal with that because need to handle 100 variables. That’s what array come on picture to deal with same type data.

Points to remember:

  • Array always keep elements of same type such as primitive type or objects.
  • In Java array is dynamically allocated.
  • Array size always specified in int value not in short or long.
  • If number of elements in array are n ,then indexing of array start from 0…n-1.
  • Array is object in Java , if need to find  length, check for member length. To check length of array in C/C++ use sizeof.
  • Array can be use as static field, a local variable or a method parameter.
  • In java direct super class of Array is Object and implements java.lang.Cloneable and java.io.Serializable interface.
  • Time Complexity Access : Θ(1)
  • Time Complexity Search : Θ(n)
  • Time Complexity Insertion : Θ(n)
  • Time Complexity Deletion : Θ(n)
  • Space Complexity: O(n)

In data structure array are two types:

  • One dimensional arrays
  • Multi dimensional arrays

One Dimensional Array

One dimensional array also called as linear array.

Single Dimentional Array

Declaration of Array

Declaration show the reference of values as array and each value in array specified as type.

type var-name [];
or
type [] var-name;

Example to declare array of different types.

// both are valid way of declarations
int numbers[];
or int[] numbers; 

byte byteArr[];
short shortsArr[];
boolean booleanArr[];
long longArr[];
<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>float floatArr[];
double doubleArr[];
char charArr[];
//array of reference objects of Class Type MyTestClass
MyTestClass myClassArray[]; 

//Array of unknown type object, as oBject is super class of class class
Object[]  objectArr,
//Array of unknown type of collection as Collection is super interface in Collection framework
Collection[] callectionArr;

Instantiation of Array

On array declaration only the reference of array created, to allocate memory to array need specified the size of array as below. where the size is always a integer value greater than zero.


var-name = new type[size];

For Example:

int numbers[]; //declaration
numbers=new int [10];//create an instance of array of 10 numbers.

Object[] objectArr; //declaration

objectArr=new Object[10]; //create an instance of array of 10 Objects.

Note:

  • For primitive type array instantiation, array elements values by default initialize with specified primitive default value. For example : primitive type int default value is 0, all the  elements array by default initialize with 0.
  • For reference type array instantiation, array element values by default initialize with specified primitive default value. For example : reference type Object default value is null, all the  elements array by default initialize with null.

Array Instantiation with Literals

If you already know the elements of an array , use literals in array to instantiation and assignment of values at same time.

//Array with int literals
int [] numbers={10,, 50, 70 , 90, 80};
//Array with String literals
String [] names= {"Saurabh", "Gaurav", "Raghav"};

Accessing of array

To access/assign the elements of an array, use index position within range 0 to n-1 for the size of array length n. If trying to access array beyond this range (0…n-1) for primitive and reference type, get an exception as ArrayIndexOutOfBoundException in case of String will throw StringIndexOutOfBoundsException


//accessing/assign value on array
arrName[index];

Example

//access value from array on index position 2, will result 70
int number=numbers[2];

//Assign value on index position , new change value 80
numbers[2]=80;

Java Program for Single Dimensional Array

Here is example of single line array , considering all above cases;


public class OneDimentionalArray {

	public static void main(String[] args) {

		//declaration by both ways
		int numbers[];

		//Instantion for array of int type size 10
		//By default initialize with 0 for primitive type int
		numbers=new int[10];

		//instantition with literals
		String []names= {"Saurabh","Gaurav","Raghav"};

		System.out.println("Print Numbers :");
		//access array with for loop
        for(int i=0; i<=numbers.length-1;i++)
		{
			System.out.println(numbers[i]);
		}

		System.out.println("\nPrint Name :");
		//access array with for each loop
		for(String name:names)
		{
			System.out.println(name);
		}

		// Assign values to Arrays by for loop
		for(int i=0; i<=numbers.length-1;i++)
		{
			numbers[i]=i*10;
		}

		//manually assign values,Raghav will replace with Ramesh
		names[2]="Ramesh";

		System.out.println("\n\nUpdate Values from arrays");

		//access array with for loop
                for(int i=0; i<=numbers.length-1;i++)
		{
			System.out.println(numbers[i]);
		}

		System.out.println("\nPrint Name :");
		//access array with for each loop
		for(String name:names)
		{
			System.out.println(name);
		}

	}

}

Output


Print Numbers :
0
0
0
0
0
0
0
0
0
0

Print Name :
Saurabh
Gaurav
Raghav


Update Values from arrays
0
10
20
30
40
50
60
70
80
90

Print Name :
Saurabh
Gaurav
Ramesh

Multi Dimensional Array

Multi-dimensional arrays also called Jagged Arrays, are arrays of arrays with each element of the array holding the reference of another array. A multi-dimensional array is created by appending square brackets ([]) per dimension.
For Example


int[][] intArr=new int [2][3]; //2D array
int numbers[][][]=new int [2][3][4]; //3D array

//2D representation with literals
//Create an array of size [2][3] and assign given values
int [][]numbers ={{2,5,7},{4,6,9}}

Two Dimentional Array

Java Program for Two Dimensional Array


public class TwoDimentionalArray1 {

	public static void main(String[] args) {

		//declaration
		int numbers[][] = {{2,5,7},{4,6,9}};

		//access in array of two dimensional array
        for(int i=0; i<=numbers.length-1;i++)
		{
        	for (int j=0; j<numbers[i].length;j++)
			System.out.println("numbers["+i+"]["+j+"]="+numbers[i][j]);
		}

		System.out.println("\n\nUpdate Values from arrays");

		numbers[0][1]=20;
		numbers[1][2]=30;
		numbers[0][0]=40;

		for(int i=0; i<=numbers.length-1;i++)
		{
        	for (int j=0; j<numbers[i].length;j++)
			System.out.println("numbers["+i+"]["+j+"]="+numbers[i][j]);
		}
	}

}

Output


numbers[0][0]=2
numbers[0][1]=5
numbers[0][2]=7
numbers[1][0]=4
numbers[1][1]=6
numbers[1][2]=9


Update Values from arrays
numbers[0][0]=40
numbers[0][1]=20
numbers[0][2]=7
numbers[1][0]=4
numbers[1][1]=6
numbers[1][2]=30

 

Advertisements