You can declare and initialize an array in Java using the array declaration syntax along with the array initializer. Here's how you can do it:
1. Declaring and Initializing an Array:
java
public class ArrayInitializationExample {
public static void main(String[] args) {
// Declare and initialize an array of integers
int[] numbers = {1, 2, 3, 4, 5};
// Declare and initialize an array of strings
String[] names = {"Alice", "Bob", "Charlie"};
// Declare and initialize an array of doubles
double[] values = {1.0, 2.5, 3.7};
// Accessing array elements
System.out.println("First number: " + numbers[0]);
System.out.println("Second name: " + names[1]);
System.out.println("Third value: " + values[2]);
}
}
In this example, arrays of integers (numbers
), strings (names
), and doubles (values
) are declared and initialized using the curly brace syntax. You can directly provide the initial values enclosed in curly braces, separated by commas.
Remember that array indices in Java are zero-based, meaning the first element is at index 0, the second at index 1, and so on.
2. Declaring and Initializing an Array with Specified Size:
java
public class ArrayInitializationExample {
public static void main(String[] args) {
// Declare an array of integers with a specific size
int[] array = new int[5];
// Initialize array elements
array[0] = 10;
array[1] = 20;
array[2] = 30;
array[3] = 40;
array[4] = 50;
// Accessing array elements
System.out.println("Second element: " + array[1]);
}
}
In this example, an array of integers is declared with a size of 5 using the new
keyword. The individual elements are then assigned values using array indexing.
Both approaches (with and without specified size) allow you to declare and initialize arrays in Java. The choice between them depends on whether you know the initial values upfront or not.
Comments
Post a Comment