Arrays Java
Arrays Java
a
memory locations.
Key Characteristics
1. Fixed size:Arrays have a fixed size, which is specified when the array is created.
2. Same data type:All elements in an array must be of the same data type.
3. Indexed:Array elements are accessed using an index, which starts from 0.
Benefits
2. Fast access:Array elements can be accessed quickly using their index.
scores[0] = 90;
System.out.println(scores[0]);
● the second element of an array is stored at index 1, and so on.
● If the size of an array is n, then the index of the last element of the array
will be n - 1
● We can access the elements of an array using these index values.
Syntax arrayName[index];
System.out.println(arr[0]);
System.out.println(arr[1]);
System.out.println(arr[4]);
}
}
Declaration:
atatype[] arrayName;
d // Preferred
datatype arrayName[]; // Valid but less common (C-style)
Initialization:
● D
efinition: Fixed-size, indexed data structure storing elements of the same
type in contiguous memory.
● Object: Arrays are objects in Java, even for primitive types.
● Random Access: Provides efficient O(1) time complexity for element access.
● Initialization:
○ n
ew datatype[size];(with default values:int=0,double=0.0,
boolean=false,Object=null)
A. Rules
● D
efault Values: Elements initialized to type-specific defaults if not explicitly
set.
● N
odelete: Elements cannot be "deleted" to shrink the array (consider
ArrayListfor dynamic needs).
B. Characteristics
● Traversing:
● Copying:
Pitfalls
● N
ullPointerException: Accessingnullelements in object arrays without
checks.
Best Practices
Arrays in Java must be declared with a type and square brackets [].
Syntax:
atatype[] arrayName;
d / / Preferred way (recommended)
datatype arrayName[]; // Valid but less readable (C-style)
Examples:
int[] numbers;
numbers = new int[]{1, 2, 3, 4, 5}; // Must specify size implicitly
Example:
4. ArrayIndexOutOfBoundsException
Example:
import java.util.Arrays;
Example:
Example:
Example:
Using Scanner
import java.util.Scanner;
ystem.out.println("Enter 5 numbers:");
S
for (int i = 0; i < numbers.length; i++) {
numbers[i] = sc.nextInt();
}
ystem.out.println("You entered:");
S
for (int num : numbers) {
System.out.print(num + " ");
}
sc.close();
}
}
Summary Table
Iteration (for-each) for (datatype var : arr) for (int num : arr)
Key Takeaways
Theory:
S
● ince arrays are fixed-size, concatenation requires creating a new array.
● System.arraycopy() or manual copying can be used.
Example:
import java.util.Arrays;
import java.util.stream.IntStream; // For the Java 8+ alternative
/ / Assuming arr1 and arr2 are already defined as in the example above
// import java.util.stream.IntStream; and import java.util.Arrays; are needed
int[] combined = IntStream.concat(Arrays.stream(arr1),
Arrays.stream(arr2)).toArray();
// combined will be [1, 2, 3, 4, 5, 6]
Theory:
● J ava doesn't have built-in slicing like Python that creates a view; it creates a
new copy.
● Use Arrays.copyOfRange().
Example:
import java.util.Arrays;
Arrays of arrays.
Theory:
C
● an have 2D, 3D, or higher dimensions.
● Memory is still contiguous for each individual array within the structure (e.g.,
each row in a 2D array is a contiguous block).
4. Two-dimensional Arrays (Matrix)
Declaration:
int[][] matrix1 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Method 2: With new keyword (dynamic initialization, elements get default values)
int[][] matrix2 = new int[3][4]; // Creates a 3x4 matrix (3 rows, 4 columns), all
elements are 0s
int[][] jagged = new int[3][]; // Declare rows, but not column sizes yet
jagged[0] = new int[2]; // Row 0 has 2 columns
jagged[1] = new int[3]; // Row 1 has 3 columns
jagged[2] = new int[1]; // Row 2 has 1 column
Accessing Elements:
Printing:
Java
System.out.println(Arrays.deepToString(matrix1));
// Example output for matrix1 after modification: [[1, 10, 3], [4, 5, 6], [7, 8, 9]]
Iterating:
import java.util.Scanner;
import java.util.Arrays; // Required for deepToString()
sc.close();
}
}
/* Example Console Interaction:
nter 2x3 matrix elements:
E
Enter element at [0][0]: 1
Enter element at [0][1]: 2
Enter element at [0][2]: 3
Enter element at [1][0]: 4
Enter element at [1][1]: 5
Enter element at [1][2]: 6
● 1D Arrays: Best for simple lists, sequences, or collections of homogeneous
ata where order matters.
d
2D Arrays: Ideal for representing matrices, grids, tables, or any data with a
●
clear row-column structure (e.g., game boards, image pixels).
● Jagged Arrays: Use when the number of columns varies per row, saving
memory if rows are naturally uneven (e.g., storing student scores where each
student has a different number of subjects).
● Higher Dimensions (3D, 4D, etc.): For more complex data structures like
volumetric data (e.g., 3D scans), or time-series data where each point in time
has a 3D structure.
Best Practices