Link to home
Start Free TrialLog in
Avatar of JRawabi
JRawabi

asked on

Arrays in java

What is the difference between the following declarations:

int myList = new int [10]


and

int [] myList = {1,2,3,4,5,6,7,8,9,10}  // I know this initialize the array.


1- In he first declaration it is mentioned that i create a reference. Reference to what?
2- What is the difference between the two?
3-Which one we should use?


Thanks
ASKER CERTIFIED SOLUTION
Avatar of krakatoa
krakatoa
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of JRawabi
JRawabi

ASKER

Thanks but what about this referencing in the first eclaration?
Well, myList is a reference (a chunk of storage memory) to an array of integers, sized 10 elements.

(BTW, you need to declare it thusly :

int[] myList = new int [10];

and not as you presently have declared it).
Smthg like this shows it :

public class ArrayMaker {

   static int[] myList = new int [10];

	public static void main(String[] args){

		for(int a = 0;a<myList.length;a++){

			myList[a] = a;
		}

		for (int b=0;b<myList.length;b++){

			System.out.println(myList[b]);
		}

		myList = null;

		System.gc();
		int[] myList = {1,2,3,4,5,6,7,8,9,10};

		for(int c=0;c<myList.length;c++){System.out.println(myList[c]);}
	}

}

Open in new window