Instance
Here are the code examples for both of these syntaxes:
Double[] myList; //preferred method or double myList[]; //effect is the same, but not the preferred method
Create an array
The Java language uses the new operator to create an array with the following syntax:
=New dataType[arraySize];
The above syntax statement does two things:
- First, an array was created using datatype[arraysize].
- Assign the reference of the newly created array to the variable Arrayrefvar.
The declaration of an array variable, and the creation of an array can be done with a single statement, as follows:
DataType[]=new dataType[arraySize];
//calculates the sum of all elements double= 0;for (int I = 0; I < Size; I++) { Total += myList [i]; or
Print all array elements For (int I = 0; I < Mylist.; I++) { system.. Println (mylist[i]< Span class= "PLN" > + "); /span>
< Span class= "PLN" >< Span class= "KWD" >< Span class= "PLN" >< Span class= "pun" >< Span class= "pun" >< Span class= "pun" >
System. Out. println("Sum of:"+ total);
Public Class Testarray { Public Static voidMain(String[]Args) { Double[]MyList= {1.9, 2.9, 3.4 3.5};//prints all array elements for (double Element: Mylist { system.. Printlnelement} }} /span>
Arrays as arguments to functions
An array can be passed as a parameter to a method. For example, the following example is a method for printing elements in an int array.
Public Static voidPrintArray(Int[]Array) { For (int I = 0 I < Array.; I++) { system.. (array[i] + "); }} /span>
The following example calls the PrintArray method to print out 3,1,2,6,4 and 2:
PrintArray(newint[]{3,1,2,6,4,2});
Declare an array variable///calculate sum of all elements/print all elements sum/output/foreach loop/array as parameter of function/Call PrintArray method to print