Arrays in Java

An array is an object that holds a fixed number of values of a certain variable type. There are many uses for arrays; they allow programmers to not need to declare a new variable for each value stored. If ten numbers need to be stored (ages, weights, wages, etc.), a single array with ten components may instead be used. This saves a lot of time and space. Arrays are declared in a similar manner to variables: int[] exampleArray = new int[5]; This array will hold 5 integers. Values may be assigned to the array, or it may be left untouched so that the user may input the values. However, assigning values to array components also works very similarly to assigning values to a single variable.
  1. exampleArray[0] = 80;
  2. exampleArray[1] = 95;
  3. exampleArray[2] = 100;
  4. exampleArray[3] = 90;
  5. exampleArray[4] = 85;
As you can see, the list of components begin with 0 and end with 4. No matter how many you declare, the first will always be 0, not 1. These values may also be treated in any other way that other variables would be. Take the following program, for example. The array is used to store test scores, and then they are totaled and averaged.
  1. public class arrays
  2. {
  3.  
  4. public static void main(String[] args)
  5. {
  6.  
  7. int[] scores = new int[5]; //declaration of array
  8.  
  9. scores[0] = 80;
  10. scores[1] = 95;
  11. scores[2] = 100;
  12. scores[3] = 90;
  13. scores[4] = 85;
  14.  
  15. int total = scores[0] + scores[1] + scores[2] + scores[3] + scores[4];
  16. int average = total / 5; //finds the total and average of the scores
  17.  
  18. System.out.println("\nThe five test scores are: " + scores[0] + ", " + scores[1] + ", " + scores[2] + ", " + scores[3] + ", and " + scores[4]);
  19.  
  20. System.out.println("\nThe total points from all tests is " + total);
  21.  
  22. System.out.println("\nThe average score is " + average);
  23.  
  24. }
  25.  
  26. }
Try editing the code a bit to have the user input test scores on their own by making use of a scanner.

Tags

Add new comment