# Welcome to Computer Programming

 Data Structures - Arrays   Until this point we have only dealt with single variables that represent a number, string or a class. However often we want variables that can hold lists of the same type of items. It allows us to manipulate data quickly and efficiently. For example if we wanted a list of names, monsters, or numbers it would make sense to use arrays. (NOTE: there are other ways to do this like arraylists, linked lists; which have adv/dis from arrays that we will get in to in the AP class) For example if we were making a video game like frogger and we wanted to have a series of bars. The bar are all similar and would be declared in a bar class. Up to this point we would say: ``Bar bar1 = new Bar (200);`` ``Bar bar2 = new Bar (250); `` ... and so on Then we wanted to move each bar, we would then say something like ``bar1.moveBar()`` ``bar2.moveBar()`` .... and so on Then to move each Bar ``bar1.drawBar(bufferGraphics)`` ``bar2.drawBar(bufferGraphics)`` .... and so on   However say if we had 50 Bars, this would be rather inpractical: Can you imagine putting this for 50 Bars - you would need 150 lines of code just to initialise the Bar, then tell it to move and draw.   With arrays this can be done in literally 6 lines of code, which is nice. How you ask? Well, we're getting there.   Declaring Arrays To declare an array, you will need to know the size of the list (to avoid this - use arraylists). You will declare it very similar to how you declare a normal single variable, except you put [] after the name and also the type: So if we wanted to have an array of 3 integers, we would declare it as such: ``int x[]=new int[3];`` Or if we wanted a list of 100 names, we would say: `` String names[] = new String[100];`` If we wanted to have a 50 dogs, we would say: ``Dog dogs[]=new Dog[50]; `` If we wanted to have a 50 bars, we might say: ``Bar allBars[]=new Bar[50]; `` This is just the declaration, but we have not actually created any values, or any dogs. We have just declared a chunk of memory that will hold a number, or a name, or a dog.   Using arrays To access a location of the array, you will say the location of the array that you want access to. Just like strings, the 1st entry in an array is the 0 place and the 2nd entry is known as the 1 place. So if we wanted to set the value of the array of 3 integers above to have to have the value of 5 in location 0. We would say: ``[0]=5;`` Or if we wanted to multiply the 3rd entry by 5 and display it, we would say: ``int product=x[2]*5;`` System.out.println("That product is " + product); So if we wanted to put values in the array of names, we might say: ``names[0]="John"`` ``names[1]="Paul"`` ``names[2]="Abdi"`` ``names[3]="Rosie"`` etc If we wanted to initialise dogs in the array of dogs, we might say: ``dogs[0]=new Dog ("Scruffy", 100,200);``   Declare and Initialize shortcut If we wanted to initialise all the bars at once do it in a loop: ``````for (int i=0; i