Lesson 5Java Syntax: Bits and Pieces
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. You also find out how to debug Java programs in Eclipse IDE and how to pass parameters to a program started from a command line.
Arrays
An array is 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 other 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
. Arrays in Java are zero-based. 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. ...
Get Java Programming 24-Hour Trainer, 2nd Edition 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.