O'Reilly logo

Java Garage by Eben Hewitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Declaring and Initializing Variables

Primitives

boolean hasRoadRage = true;
char size = 'm';
int age = 11;
long userID = 42L;

Arrays

Arrays can be created and populated as shown in the following. Make an array that has two cells for holding int values. The two cells are then populated with the values 11 and 12, respectively.

int[] numbers = new int[2];
numbers[0] = 11;
numbers[1] = 12;

For the preceding array, calling array.length returns 2.

In the next example, an int array is created with three cells and populated at the same time.

int[] numbers = {1,2,3};

Arrays can also be populated in loops. Here, we create a new object to be stored in each cell of an array.

 Employee[] employees = new Employee[5]; for (int x = 0; x < employees.length; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required