Java Reference
In-Depth Information
// This method signature includes two parameters with the same type
public static double dotProduct ( double [] x , double y []) { ... }
This compatibility syntax is extremely uncommon, and you
should not use it.
a x
Creating and Initializing Arrays
To create an array value in Java, you use the new keyword, just as you do to create an
object. Array types don't have constructors, but you are required to specify a length
whenever you create an array. Specify the desired size of your array as a nonnegative
integer between square brackets:
// Create a new array to hold 1024 bytes
byte [] buffer = new byte [ 1024 ];
// Create an array of 50 references to strings
String [] lines = new String [ 50 ];
When you create an array with this syntax, each of the array elements is automati‐
cally initialized to the same default value that is used for the fields of a class: false
for boolean elements, \u0000 for char elements, 0 for integer elements, 0.0 for
floating-point elements, and null for elements of reference type.
Array creation expressions can also be used to create and initialize a multidimen‐
sional array of arrays. This syntax is somewhat more complicated and is explained
later in this section.
Array initializers
To create an array and initialize its elements in a single expression, omit the array
length and follow the square brackets with a comma-separated list of expressions
within curly braces. The type of each expression must be assignable to the element
type of the array, of course. The length of the array that is created is equal to the
number of expressions. It is legal, but not necessary, to include a trailing comma fol‐
lowing the last expression in the list. For example:
String [] greetings = new String [] { "Hello" , "Hi" , "Howdy" };
int [] smallPrimes = new int [] { 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , };
Note that this syntax allows arrays to be created, initialized, and used without ever
being assigned to a variable. In a sense, these array creation expressions are anony‐
mous array literals. Here are examples:
// Call a method, passing an anonymous array literal that
// contains two strings
String response = askQuestion ( "Do you want to quit?" ,
new String [] { "Yes" , "No" });
Search WWH ::




Custom Search