How to Edit Single Variables in an Array in Java
Arrays provide a way to store similar types of data in an indexed collection. In Java, arrays may only hold data of a certain type. If an array is initialized to store integers, it can only hold data of the "int" type, which is the data type that stores integers. Arrays may be populated with values upon initialization, or they can be populated after. The values of an array may be retrieved or changed by referencing the corresponding index. Each element of an array can be referenced with a numerical index, and the first element of an array starts at index "0."
Instructions
-
-
1
Create a new class called "test." In your text editor, enter the following code:
public class test{
}
-
2
Create an array.
public class test{
public static void main(String [] args){
int [] testarray = {1,2,3,4,5};
}
}
This creates an array populated with numbers one through five.
-
-
3
Change the contents the array. In your text editor, add the following code:
public class test{
public static void main(String [] args){
int [] testarray = {1,2,3,4,5};
System.out.println(testarray[0]);
testarray[0] = 11;
System.out.println(testarray[0]);
}
}
This will output the contents of the element at index 0, change the contents from "1" to "11" and then again output the contents of the element at index 0.
-
1
References
- Photo Credit Ablestock.com/AbleStock.com/Getty Images