An array is the ability to combine multiple values.
When dealing with arrays, assign the array to an array type variable. Array variable definition int type and String type
int[]
String[]
The int type is an array that has a numerical value as an element. String type is an array that has a character string as an element. The first letter of String is uppercase. Example of int type array
Main.java
int[] numbers = {1,5,10};
Example of an array of type String
Main.java
String[] names = {"Sato","Suzuki","Takahashi"};
Numbers such as "0, 1, 2 ..." are assigned to the elements of the array in order from the front. Each element of the array can be obtained by using the array name [index number]. [Example]
Main.java
String[] names = {"Sato","Suzuki","Takahashi"};
System.out.println("Name is"+names[0]+"is");
Main.java
String[] names = {"Sato","Suzuki","Takahashi"};
System.out.println("Name is"+names[0]+"is");
names[0] = "Ueno";
System.out.println("Name is"+names[0]+"is");
It can be overridden with names [index] = "element" ;. In the above example, the output result of the console will be Sato and Ueno.
Iterative processing can be performed using the for statement. [Example]
Main.java
String[] names = {"Sato","Suzuki","Takahashi"};
for (int x = 0;x < 3;x++){
System.out.println("Name is"+names[x]+"is");
}
In the above example, the three indexes 0 to 2 are called from names. length length is a function that counts the number of elements. You can iterate using the for statement and length above. It can be rewritten by changing the conditional expression x <3 of the for statement to the array .length. [Example]
Main.java
String[] names = {"Sato","Suzuki","Takahashi"};
for (int x = 0;x < names.length;x++){
System.out.println("Name is"+names[x]+"is");
}
If you write as above, you don't have to worry about the number of elements in the array. So I think this is easier to use. However, there is also a simpler for statement. It's an array extension for statement.
The for statement has an extended for statement for arrays. If you use this, you can write the for statement more simply.
Main.java
for (Data type variable name:Array name) {
Repeated processing;
}
[Example]
Main.java
String[] names = {"Sato","Suzuki","Takahashi"};
for (String name:names){
System.out.println("Name is"+name+"is");
}
In the above example, String is the data type, name is the variable name, and names is the array name. Compared to the for statement that used length, the extended for statement assigns the array element itself to the variable. I wrote it loosely for my understanding, but I think this is the easiest to use.
Recommended Posts