Home | Résumé | Courses | Contact | Useful Links | Favorite Links | USC - Homepage


Introduction to Programming - (CPTR125) - Lectures  


 Return to Courses | Course Content  



Introduction to Computer Programming (CPTR 125)

by David Siguelnitzky, MIS; MTE

JAVA - Lecture 6 - Version 2.1

Arrays


Lecture Outline


    - Introduction
    - Declaring and Creating Arrays
    - Examples Using Arrays


Introduction
   
• Arrays
        –Data structures
        –Related data items of same type
        –Remain same size once created
    • Fixed-length entries
        –Group of variables
    • Have same type

A 12-element array

 

    •Using an array initializer
        – Use initializer list
    • Items enclosed in braces ({})
    • Items in list separated by commas  int n[] = { 10, 20, 30, 40, 50 };
        – Creates a five-element array
        – Index values of: 0, 1, 2, 3, 4
        – Do not need keyword new

1 // Fig. 7.3: InitArray.java
2 // Initializing an array with a declaration.
3 import javax.swing.*;
4
5 public class InitArray {
6
7     public static void main( String args[ ] )
8     {
9         // array initializer specifies number of elements and value for each element
10     
11       int array[ ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
12
13       String output = "Index\tValue\n";
14
15        // append each array element's value to String output
16       for ( int counter = 0; counter < array.length; counter++ )
17                  output += counter + "\t" + array[ counter ] + "\n";
18
19      JTextArea outputArea = new JTextArea();
20      outputArea.setText( output );
21
22      JOptionPane.showMessageDialog( null, outputArea,
23      "Initializing an Array with a Declaration", JOptionPane.INFORMATION_MESSAGE );
24
25
26      System.exit( 0 );
27
28     } // end main
29
30 } // end class InitArray

 


                Resource: Java How to Program – 5th Edition – Deitel & Deitel


 Return to Courses | Course Content  


 Home | Résumé | Courses | Contact | Useful Links | Favorite Links | USC - Homepage