Arrays in Java Application

The following Java program application uses Arrays. The program reads five numbers, find their sum and print the numbers in the reverse order. I will be using the JCreator IDE in developing the program. To start in this tutorial, first open the JCreator IDE, click new and paste the following code.
  1. import java.util.*;
  2.  
  3. public class Arrays
  4. {
  5. static Scanner console = new Scanner (System.in);
  6.  
  7. public static void main (String[] args)
  8. {
  9. int[] items = new int [5];
  10.  
  11. int sum;
  12. int counter;
  13.  
  14. System.out.println("Enter five integers: ");
  15.  
  16. sum = 0;
  17.  
  18. for (counter = 0; counter < items.length;
  19. counter++)
  20. {
  21. items[counter] = console.nextInt();
  22. sum = sum + items[counter];
  23. }
  24.  
  25. System.out.println("The sum of the numbers = " + sum);
  26. System.out.print("The numbers in reverse order are: ");
  27.  
  28. for (counter = items.length - 1; counter >= 0;
  29. counter--)
  30. System.out.print(items[counter] + " ");
  31.  
  32. System.out.println();
  33.  
  34. }
  35. }
Sample run:
  1. Enter five integers:
  2. 5 6 6 2 4
  3. The sum of the numbers = 23
  4. The numbers in reverse order are: 4 2 6 6 5
Why do we need Arrays? In previous tutorial, you already know how to read numbers, print them and find their sum. The different here is that we want to print the numbers in reverse order. We cannot print the first four numbers until we have printed the fifth. This means that we need to store all the numbers before we can print them in reverse order. An array is a collection of a fixed number of variables called elements, wherein all the elements are arranged in a list form. The statement  int[] items = new int [5]; declare an array item of five elements. The statement
  1. for (counter = items.length - 1; counter >= 0;
  2. counter--)
  3. System.out.print(items[counter] + " ");
prints the numbers in the reverse order.

Add new comment