Great Deals

Array Declaration in java :)

15:18 suresh chaudhari 0 Comments


I am gonna discuss about various possibilities in which array can be declared.

String[] empNames []; Correct
String[][][] professions; // Correct

int[5] salaries;//Wrong
Remember JVM wont allocate size until oyu create objects.

HOw to create the array of type String.
int[] items; // Declares the array of ints
items= new int[4]; // constructs an array and assigns it
// to the testScores variable

  • Create an array of size four and assign the reference to "items" variable.

Array must be given size explicitely.
int[] list=new int[];//Not allowed
Create multidimenstional Array

int[][] myArray = new int[3][];
Notice that first bracket carry size.This means it is a array that will hold refernce to other arrays.

int[ ][ ] myArray = new int[3][ ];
myArray[0] = new int[2];
myArray[0][0] = 6;
myArray[0][1] = 7;
myArray[1] = new int[3];
myArray[1][0] = 9;
myArray[1][1] = 8;
myArray[1][2] = 5;

Onother example
Car [] cars = new Car[3];
cars[0]=new Car(); //Will Work
cars[4]=new Car(); //Will not Work.will give ArrayIndexOutOfBoundException.
cars[3]=3 // Runtime exception. There is no element at index

 One Line intialization
int x = 9;
int[] items = {6,x,8};//Length determined by number of values in "items".

Shortcut for Creating multidimensional array.
int[][] items = {{5,2,4,7}, {9,2}, {3,4}};

items[0] ///contains 5,2,4,7
items[0][1] output 2

Anonymous Array creation

Correct ->      

int[] items;
items = new int[] {4,15,2};

This implies first refernce is created and then it points to anonymous array with items {4,15,2}


 int[] items;
items = new int[3] {4,15,2};//Not allowed.

When creating anonymous array we never specify the item size in advance it will be calculated by number of items in the comma seperated list.

YOu can't assign 2 d array to 1 d array.

int[] screen;
int[][] multiplex = new int[3][];
screen = multiplex ;

  • Static block and init block

Static block: initializes static variable.Static block initializes only once.

Init block: inits instance variables.Init block runs evry time when instance of class is created..
class SmallInit {
static int x;
int y;
static { x = 7 ; } // static init block
{ y = 8; } // instance init block
>>Init blocks runs after the all constructors got executed.