05.0 Java Notes‎ > ‎

Java: 1D Arrays

Site:  Oracle Java Array Tutorial

Arrays 

  • An array is data structure that allows the storing multiple values within the same variable.
  • only one variable name use to reference the array
  • each item stored in the array is called an element.
  • all items in the must be of the same data type.
  • you must know the maximum number of items that will be stored in the array
  • The array is accessed by using the index (or subscript) of the element within the array.
  • Java arrays start at index of 0
  • Arrays have a known length, once the size is set, it can not be changed

Accessing elements in an array
  • The array is accessed through the the index of the array
  • In Java, an array is a reference data type. A reference data type does not hold the value of the variable - it only points to the location that hold the data.  This means that you can not create a copy of an array with an assignment statement ( the equal sign) 

Creating Arrays in Java

Either one of the following two coding techniques will create an array that will hold 10 integers

// declares the array

int[] n;  


// initializes the array

n = new int[10];  

//declare and initialize in one line


int[] n= new int[10]; 



Either one of the following two coding techniques will create an array that will hold 10 Strings

String[] str;

str = new String[10];

String[] str= new String[10];



you can have an array of any data type, including an array of a class you create!


Assign Values in an Array

the following code will place ten random integers into the array from 0 to 99

for(int x=0;x<10;x++){

n[x]= (int)(Math.random()*100);

}

in this case the x is used as the index of the array and the counter for the for loop


Retrieve Values from an Array

the following code will add all the integers in the array together. 

int sum = 0;

for(int x=0;x<10;x++){

sum = sum + n[x];

// System.out.println(x+":  "+n[x]+":  "+ sum);

}



To create a copy of an array, you must use the System.arrayCopy()method, find the details in the Java API

Comments