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; ...

Get Java Garage now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.