Java Array Initialization
Static Initialization
Static initialization allows you to define array elements directly during declaration.
Complete syntax:
dataType[] arrayName = new dataType[]{element1, element2, element3, element4...};
int[] numbers = new int[]{11, 22, 33};
double[] values = new double[]{1.1, 2.2, 3.3};
Simplified syntax:
dataType[] arrayName = {element1, element2, element3, element4...};
int[] scores = {1, 2, 3, 4, 5};
double[] measurements = {1.1, 2.2, 3.3};
Key points:
- The data type determines what kind of elements the array can store
- Square brackets indicate an array declaration
- Array names should follow camelCase naming convention
- The
newkeyword allocates memory space for the array - Elements inside braces are separated by commas
Note: The data type must be consistent throughout the array. Once created, the array length cannot be modified.
Dynamic Initialization
Dynamic initialization specifies the array size while the system assigns default values.
Syntax:
dataType[] arrayName = new dataType[arraySize];
int[] ages = new int[3];
int[] grades = new int[10];
Array Address Values
When printing an array, Java displays its memory address:
int[] data = {1, 2, 3, 4, 5};
System.out.println(data); // [I@6d03e736
double[] values = {1.1, 2.2, 3.3};
System.out.println(values); // [D@568db2f2
These hexadecimal values represent the array's location in memory.
Array Indexing
In Java, array indices (also called subscripts or positions) are the numbered positions of elements in the array.
Characteristics:
- Indices start at 0
- Are consecutive and uninterrupted li>Increment by 1 sequentially
Accessing Array Elemnets
You can retrieve and modify elements using thier indices:
public class ArrayAccess {
/*
* Array element access format:
* arrayName[index];
*
* Functions:
* 1. Retrieve the element at the specified index
* 2. Modify the element at the specified index
*/
public static void main(String[] args) {
int[] data = {1, 2, 3, 4, 5};
// Retrieve the element at index 3
int value = data[3];
System.out.println(value);
System.out.println(data[3]);
// Modify the element at index 3 to 10
data[3] = 10;
System.out.println("After modification: " + data[3]);
}
}
Array Traversal
Traversal involves accessing every element in the array sequentially:
Basic traversal pattern:
for(int i = 0; i < array.length; i++) {
// Within the loop, i represents each index in the array
System.out.println(array[i]); // Outputs each element
}
Comparison of Initialization Methods
Static Initialization:
int[] values = {1, 2, 3, 4, 5}; // Manually specify elements, system calculates length
Dynamic Initialization:
int[] values = new int[3]; // Manually specify length, system provides default values
When to use each:
- Use dynamic initialization when you know the number of elements but not their values
// Using an array to store 5 integers from user input
int[] userInput = new int[5];
- Use static initialization when you know all the values beforehand
// Storing student test scores: 66, 77, 88, 99, 100
int[] scores = {66, 77, 88, 99, 100};
Common Array Issues
Index Out of Bounds
public class ArrayBounds {
public static void main(String[] args) {
int[] data = {1, 2, 3, 4, 5, 5, 5, 5, 5};
// Accessing elements by index
System.out.println(data[1]); // Valid
System.out.println(data[10]); // Throws ArrayIndexOutOfBoundsException
}
}
For any array, valid indices range from 0 to array.length - 1.
Code Blocks in Java
Static Code Blocks
Static code blocks are declared with the static keyword and execute when the class is loaded.
Syntax:
static {
// Code here executes once when the class is loaded
}
Characteristics:
- Execute automatically when the class is loaded
- Run only once during the program's execution
Local Code Blocks
public class LocalBlockExample {
public static void main(String[] args) {
{
int x = 10;
System.out.println(x);
}
// x is no longer accessible here
}
}
Use case: Local blocks can limit variable scope, helping with memory management by allowing early variable deallocation.
The 'this' Keyword
The this keyword refers to the current instance of a class, allowing you to distinguish between instance variables and parameters with the same name.
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name; // 'this.name' refers to the instance variable
this.age = age; // 'this.age' refers to the instance variable
}
}
When used within a class, this represents the current object instance.