Professional Documents
Culture Documents
*;
public class ArrayIntroduction {
public static void main (String [ ] args)
{
// An array is a block of values of the
// same variable type.
// To create an array, add square brackets
// after the variable type, and use "new"
// to create a block of the proper type
// and size
int [ ] list = new int[5]; // 5 elements
String [ ] names = new String[3];
// size must be a positive integer
// The "length" field tells us how many
// spaces an array has in all (used and unused)
System.out.println(list.length);
// Arrays are fixed in size at creation time
// Use [ ] notation to retrieve the value at
// a specific position in the array:
// 0 - (length-1)
names[1] = "Bill";
names[2] = "David";
System.out.println(names[1]);
System.out.println(names[0]);
// (Java assigns default values to empty
// elements)
//
//
//
//
//
//
//
//
//
//
//
//
// Option 1:
// Create an array of a user-specified size
System.out.print("Enter the size of the array: ");
Scanner s = new Scanner(System.in);
int userSize = s.nextInt();
int [] user = new int[userSize];
// Read in the appropriate number of values
for (int i = 0; i < userSize; i++)
{