O'Reilly logo

Java® Programming 24-Hour Trainer by Yakov Fain

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

Chapter 5

Back to Java Basics

This tutorial didn’t start with detailed coverage of basic constructs of the Java language such as the syntax of if statements, loops, and the like. You started learning Java programming with getting used to object-oriented terms and constructs of the language. This lesson is a grab bag of basic language elements, terms, and data structures.

Arrays

An array is a data storage that’s used to store multiple values of the same type. Let’s say your program has to store names of 20 different girls, such as “Masha”, “Matilda”, “Rosa” and so on. Instead of declaring 20 different String variables, you can declare one String array with the capacity to store 20 elements:

String []  friends = new String [20];  // Declare and instantiate array
friends[0] = "Masha";                  //Initialize the first element
friends[1] = "Matilda";                //Initialize the second element
friends[2] = "Rosa";
 
// Keep initializing the elements of the array here
 
friends[19] = "Natasha";                //Initialize the last element

The first element of an array in Java always has an index of 0. While declaring an array you can place brackets either after the data type or after the variable name. Both of the following declarations are correct:

String friends[];
String[] friends;

You must know the size of the array before assigning values to its elements. If you want to be able to dynamically change the size of an array during the run time, consider other Java ...

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