Java Arrays
Arrays in Java are objects that store multiple values of the same type in a single variable. They are used to store collections of data, making it easy to manage large amounts of information.
Key Topics
1. Declaring Arrays
You can declare an array by specifying the data type followed by square brackets.
int[] myArray;
String[] myStrings;
2. Initializing Arrays
Arrays can be initialized in several ways:
2.1 Using the new
Keyword
int[] myArray = new int[5]; // Creates an array of 5 integers
2.2 Using Array Literals
int[] myArray = {1, 2, 3, 4, 5};
String[] myStrings = {"Apple", "Banana", "Cherry"};
3. Accessing Array Elements
Array elements are accessed using their index, which starts at 0.
int[] myArray = {10, 20, 30};
System.out.println(myArray[0]); // Outputs: 10
myArray[1] = 40; // Updates the second element to 40
4. Array Length
You can find the length of an array using the length
property.
int[] myArray = {1, 2, 3, 4, 5};
System.out.println("Array length: " + myArray.length); // Outputs: Array length: 5
Key Takeaways
- Arrays store multiple values of the same type.
- Use square brackets
[]
to declare and access arrays. - Array indices start at 0.
- The
length
property gives the size of the array.