CS 112
Spring 2005
Ileana Streinu

Lecture 5


Basic Java Data Types

In Java, there are two "categories" of data types: primitive types and reference types:
Note: arrays and classes are really pointers!!

Arrays in Java: basics

  1. Declaring variables of type array: add brackets to the name of a variable. Example:
    int values[];
    declares a variable of type array of integers. So far, no memory is allocated to correspond to this variable.
  2. Allocating memory for an array = creating the array. Use the new operator to allocate memory and create an array. Example:
    values = new int[100];
    allocates an array of 100 cells, each capable of containing an integer value, and "links" it to the variable values.
  3. Instead of using a constant (such as 100), it is always a good idea to use a final class variable.

    final int MAX = 100;

    This variable is given a value which cannot be modified at run time. Then you may refer to the variable name in your program (e.g. when allocating size for it or in all the for loops that loop over the elements of the array).

    values = new int[MAX];

    Resizing the array requires now just one modification in the code, namely to change the constant value associated with the final variable.
  4. Initializing an array: can be done with a list of values, as in the following example:
    values = { 0, 1, 2, 3 ,4 ,5 };
  5. Accessing array elements: as in C, the name of the array is followed by an index between brackets. Example:
    values[2] or values[i]
    The array elements can be used in more complex constructions. For example:
    int a = values[i] + 2;
    if (values[i] == 1) x = 0;
  6. Changing array elements. This is done using the assignment operator, as in many other programming languages. Example:

    values[2] = 200;
  7. Multidimensional arrays. Example of a 2x2 matrix:
    int coords[][] = new int[5][5];
    coords[0][0] = 1;
    coords[0][1] = 2;
  8. Arrays of arrays or other objects. Example:
    String names[] = new String[3];
    You may now define arrays of buttons, of lines, of points, whatever objects you want!!!
  9. Useful statements to be used with arrays: of course, the for loops.

    for (i=0; i<MAX; i++)

Exercises using Arrays in Java

From the list of all exercises, start working on the array exercises 17-19. We will continue on Thuesday with 20-22, combining arrays, graphics and mouse events.
These exercises are part of your next homework. They must be completed by Monday night, before next Tuesday, to give you time to ask questions and work on the creative part of the homework.
Ileana Streinu