0% found this document useful (0 votes)
38 views17 pages

Arrays Java

The document provides a comprehensive overview of arrays in Java, detailing their characteristics, benefits, and common operations. It explains the syntax for declaring, initializing, and accessing arrays, as well as the differences between one-dimensional and multi-dimensional arrays. Additionally, it covers best practices, common pitfalls, and advanced concepts such as array concatenation and slicing.

Uploaded by

suryajss11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views17 pages

Arrays Java

The document provides a comprehensive overview of arrays in Java, detailing their characteristics, benefits, and common operations. It explains the syntax for declaring, initializing, and accessing arrays, as well as the differences between one-dimensional and multi-dimensional arrays. Additionally, it covers best practices, common pitfalls, and advanced concepts such as array concatenation and slicing.

Uploaded by

suryajss11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

​ n array is a​​collection of elements of the same data​​type stored in contiguous​

a
​memory locations.​

​ rrays are a fundamental data structure in Java,​​allowing you to store and​


A
​manipulate multiple values​​of the same type.​

​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.​

​4.​​Homogeneous Elements:​​All elements must be of the same type.​

​Benefits​

​ . Efficient storage:​​Arrays store elements in contiguous memory locations, making​


1
​them efficient for storing large amounts of data.​

​2. Fast access:​​Array elements can be accessed quickly using their index.​

​ . Easy manipulation:​​Arrays can be easily manipulated using loops and other​


3
​control structures.​

​Common Array Operations​

​●​ ​Creation:​​Define the array's type and size​

​int[] scores = new int[5];​

​●​ ​Assignment:​​Store values into specific positions using their index​

​scores[0] = 90;​

​●​ ​Access:​​Retrieve values from specific positions using their index​

​[Link](scores[0]);​

​●​ ​Iteration:​​Loop through all elements, often using a for-each loop​

​for (int score : scores) { ... }​


​Types of Arrays​

​1. One-dimensional arrays:​​A single row of elements.​

​2. Multi-dimensional arrays:​​Arrays of arrays, used to represent matrices or tables.​

​1. One-dimensional arrays​

​dataType[] arrayName = {value1, value2, value3…};​

​Accessing Array Elements​

​●​ ​0 i.e., the first element of an array is stored at index 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];​

​Here, the​​index​​value must lie between​​0​​and​​n - 1​​while​​n​​is the size of the​


​array.​
​class Main {​
​public static void main(String[] args) {​
​int[] arr = {12, 4, 5, 2, 5};​

​[Link](arr[0]);​
​[Link](arr[1]);​
​[Link](arr[4]);​
​}​
​}​
​Declaration:​

​ atatype[] arrayName;​
d /​/ Preferred​
​datatype arrayName[]​​;​ ​// Valid but less common (C-style)​

​Initialization:​

​Method 1:​ ​Declare & initialize with size (default values)​

​int[] numbers = new int[5]; // [0, 0, 0, 0, 0]​

​Method 2:​​Declare & initialize with values​

​int[] numbers = {10, 20, 30, 40, 50};​

​Method 3:​​Dynamic initialization​

​int[] numbers = new int[]{10, 20, 30};​

​Arrays in Java: Key Points​

​1. Theory of Arrays​

​●​ 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.​

​●​ ​Key Concepts​​:​

​○​ ​Fixed Size (immutable after creation)​

​○​ ​Zero-Based Indexing (starts at​​0​)​

​○​ ​Homogeneous Elements (all same data type)​

​○​ ​Contiguous Memory Allocation​

​○​ ​Random Access (direct access by index)​

​2. Array Syntax & Types​

​A. One-Dimensional Arrays​


​●​ ​Declaration​​:​

​○​ ​datatype[] arrayName;​​(Preferred)​

​○​ ​datatype arrayName[];​​(Valid)​

​●​ ​Initialization​​:​

​○​ n
​ ew datatype[size];​​(with default values:​​int=0​​,​​double=0.0​​,​
​boolean=false​​,​​Object=null​​)​

​○​ ​{value1, value2, ...};​​(direct initialization)​

​○​ ​new datatype[]{value1, value2, ...};​​(dynamic initialization)​

​B. Multi-Dimensional Arrays​

​●​ ​2D Arrays (Matrix)​​:​

​datatype[][] arrayName = new datatype[rows][cols];​

​Example:​​int[][] matrix = new int[3][4];​

​●​ ​Jagged Arrays:​

​datatype[][] arrayName = new datatype[rows][];​

​(rows can have different column lengths)​

​Example:​​jagged[0] = new int[2];​

​3. Rules & Characteristics​

​A. Rules​

​●​ ​Fixed Size​​: Cannot be resized after creation.​

​●​ I​ndex Bounds​​: Accessing invalid index throws​


​ArrayIndexOutOfBoundsException​​.​

​●​ D
​ efault Values​​: Elements initialized to type-specific defaults if not explicitly​
​set.​

​●​ ​Length Property​​:​​[Link]​​(a field, not a method, gives array size).​

​●​ N
​ o​​delete​​: Elements cannot be "deleted" to shrink the array (consider​
​ArrayList​​for dynamic needs).​
​B. Characteristics​

​●​ ​Memory Allocation​​: Contiguous (sequential).​

​●​ ​Access Time​​: O(1) (constant time).​

​●​ ​Type Safety​​: Stores only one data type.​

​●​ ​Dynamic?​​: No (fixed size).​

​●​ ​Null Allowed?​​: Only in object arrays (e.g.,​​String[]​​,​​Integer[]​​).​

​4. Common Operations​

​●​ ​Traversing​​:​

​○​ ​for-loop​​:​​for (int i = 0; i < [Link]; i++) { ... arr[i] ... }​

​○​ ​for-each loop​​:​​for (int element : arr) { ... element ... }​

​●​ ​Copying​​:​

​○​ ​[Link]()​​:​​For efficient, low-level copying.​

​○​ ​[Link]()​​:​​More convenient for full copies.​

​●​ ​Sorting​​:​​[Link](arr);​​(sorts in ascending order).​

​●​ ​Searching​​:​​[Link](arr, key);​​(requires array to be sorted).​

​●​ ​Comparing​​:​​[Link](arr1, arr2);​​(checks for element-wise equality).​

​●​ ​Filling​​:​​[Link](arr, value);​​(sets all elements to a specified value).​

​5. Common Pitfalls & Best Practices​

​Pitfalls​

​●​ ​Index Out of Bounds​​: Forgetting​​0​​to​​length - 1​​index range.​

​●​ N
​ ullPointerException​​: Accessing​​null​​elements in object arrays without​
​checks.​

​●​ ​Size Immutability​​: Trying to resize fixed-size arrays.​

​Best Practices​

​●​ ​Use​​for-each​​for simpler iteration when index isn't needed.​

​●​ ​Prefer​​[Link]()​​for array copying.​

​●​ ​Initialize object arrays properly to avoid​​null​​issues.​


​●​ U
​ se​​[Link]()​​(1D) or​​[Link]()​​(multi-D) for​
​debugging.​

​Detailed Notes on Arrays in Java​

​1. Declaration of an Array​

​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:​

i​nt[] numbers;​ /​ / Declares an integer array​


​String[] names;​ ​// Declares a String array​
​double[] prices;​ ​// Declares a double array​

​2. Creating and Initializing an Array​

​Arrays can be initialized in multiple ways.​

​A. Static Initialization (Direct Assignment)​

i​nt[] numbers = {10, 20, 30, 40, 50};​


​String[] fruits = {"Apple", "Banana", "Mango"};​

​B. Dynamic Initialization (Using new)​

i​nt[] numbers = new int[5];​ ​// Default values: [0, 0, 0, 0, 0]​


​String[] names = new String[3];​ ​// Default: [null, null, null]​

​C. Initialize Later​

i​nt[] numbers;​
​numbers = new int[]{1, 2, 3, 4, 5};​ ​// Must specify size implicitly​

​3. Accessing Array Elements​


​●​ ​Arrays are​​zero-indexed​​(first element is at index 0).​

​●​ ​Access elements using arrayName[index].​

​Example:​

i​nt[] numbers = {10, 20, 30, 40, 50};​


​[Link](numbers[0]);​ /​ / 10​
​[Link](numbers[2]);​ ​// 30​

​4. ArrayIndexOutOfBoundsException​

​●​ ​Occurs when trying to access an​​invalid index​​(negative or ge array length).​

​●​ ​Java does​​not​​allow negative indexing (unlike Python).​

​Example:​

i​nt[] arr = {1, 2, 3};​


​[Link](arr[3]);​ ​// Throws ArrayIndexOutOfBoundsException​

​5. Printing an Array​

​A. Using [Link]() (Best for Debugging)​

​import [Link];​

i​nt[] arr = {10, 20, 30};​


​[Link]([Link](arr));​ ​// [10, 20, 30]​

​B. Manual Printing (Using Loop)​

​for (int i = 0; i < [Link]; i++) {​


​[Link](arr[i] + " ");​
​}​
​// Output: 10 20 30​
​6. Modifying Array Elements​

​●​ ​Change values by assigning new values to indices.​

​Example:​

i​nt[] numbers = {10, 20, 30};​


​numbers[1] = 25;​ ​// Now: [10, 25, 30]​

​7. Creating an Array Using new Keyword​

​●​ ​Useful when size is known but values are not.​

​Example:​

i​nt[] numbers = new int[5];​ /​ / [0, 0, 0, 0, 0]​


​String[] names = new String[3];​ ​// [null, null, null]​

​8. Length of an Array​

​●​ ​Use [Link] (a​​field​​, not a method).​

​Example:​

i​​nt[] arr = {10, 20, 30};​


​[Link]([Link]);​ ​// 3​

​9. Iterating Over an Array​

​A. Using for Loop​

i​nt[] arr = {10, 20, 30};​


​for (int i = 0; i < [Link]; i++) {​
​[Link](arr[i]);​
​}​
​B. Using for-each Loop (Enhanced for Loop)​

​for (int num : arr) {​


​[Link](num);​
​}​

​10. Reading & Storing User Input in an Array​

​Using Scanner​

​import [Link];​

​public class Main {​


​public static void main(String[] args) {​
​Scanner sc = new Scanner([Link]);​
​int[] numbers = new int[5];​

​ [Link]("Enter 5 numbers:");​
S
​for (int i = 0; i < [Link]; i++) {​
​numbers[i] = [Link]();​
​}​

​ [Link]("You entered:");​
S
​for (int num : numbers) {​
​[Link](num + " ");​
​}​

​[Link]();​
​}​
​}​

​Summary Table​

​Operation​ ​Syntax​ ​Example​


​Declaration​ ​datatype[] arrayName;​ ​int[] numbers;​

​Static Initialization​ ​ atatype[] arr = {v1, v2,​


d ​int[] arr = {1, 2, 3};​
​v3};​

​Dynamic Initialization​ ​ atatype[] arr = new​


d ​int[] arr = new int[5];​
​datatype[size];​

​Accessing Elements​ ​arrayName[index]​ ​arr[0] = 10;​

​Array Length​ ​[Link]​ ​int len = [Link];​

​Iteration (for Loop)​ f​ or (int i=0; i<[Link];​ f​ or (int i=0; i<[Link];​


​i++)​ ​i++)​

​Iteration (for-each)​ ​for (datatype var : arr)​ ​for (int num : arr)​

​Printing Array​ ​[Link](arr)​ ​ [Link](Arrays​


S
​.toString(arr));​

​Key Takeaways​

​✅ Arrays are fixed-size (use ArrayList for dynamic sizing).​

​✅ Zero-indexed (first element is at index 0).​

​✅ Contiguous memory allocation (fast access).​

​✅ Use [Link]() for printing.​

​✅ Loop with for or for-each.​

​✅ Watch for ArrayIndexOutOfBoundsException.​


​Advanced Array Concepts in Java​
​1. Array Concatenation​
​Combining two arrays into one.​

​Theory:​
​​ S
● ​ ince arrays are fixed-size, concatenation requires creating a new array.​
​●​ ​[Link]() or manual copying can be used.​
​Example:​

i​mport [Link];​
​import [Link]; // For the Java 8+ alternative​

​public class Main {​


​public static void main(String[] args) {​
​int[] arr1 = {1, 2, 3};​
​int[] arr2 = {4, 5, 6};​

​int[] result = new int[[Link] + [Link]];​

​ [Link](arr1, 0, result, 0, [Link]);​


S
​[Link](arr2, 0, result, [Link], [Link]);​

​[Link]([Link](result)); // [1, 2, 3, 4, 5, 6]​


​}​
​}​

​Alternative (Java 8+):​

/​ / Assuming arr1 and arr2 are already defined as in the example above​
​// import [Link]; and import [Link]; are needed​
​int[] combined = [Link]([Link](arr1),​
​[Link](arr2)).toArray();​
​// combined will be [1, 2, 3, 4, 5, 6]​

​2. Array Slicing​


​Extracting a portion of an array.​

​Theory:​

​●​ J ​ ava doesn't have built-in slicing like Python that creates a view; it creates a​
​new copy.​
​●​ ​Use [Link]().​

​Example:​
​import [Link];​

​public class Main {​


​public static void main(String[] args) {​
​int[] arr = {10, 20, 30, 40, 50};​

/​ / Slice from index 1 (inclusive) to 4 (exclusive)​


​int[] slice = [Link](arr, 1, 4);​

​[Link]([Link](slice)); // [20, 30, 40]​


​}​
​}​

​3. Multi-dimensional 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:​

i​nt[][] matrix;​ /​ / Preferred​


​int matrix[][];​ ​// Valid but less common​

​Creating & Initializing:​

​// Method 1: With values (direct initialization)​

​int[][] matrix1 = {​
​{1, 2, 3},​
​{4, 5, 6},​
​{7, 8, 9}​
​};​

​// Method 2: With new keyword (dynamic initialization, elements get default values)​

i​nt[][] matrix2 = new int[3][4];​ ​// Creates a 3x4 matrix (3 rows, 4 columns), all​
​elements are 0s​

​// Method 3: Jagged array (rows have different lengths)​

i​nt[][] 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:​

/​ / Assuming matrix1 from above​


​int value = matrix1[1][2]; // Gets 6 (element at row index 1, column index 2)​
​ atrix1[0][1] = 10; // Changes the element at row index 0, column index 1 from 2 to​
m
​10​

​Printing:​

​Java​

​import [Link];​ ​// Required for deepToString()​

​// Using [Link]() (best for multi-dimensional arrays)​

​[Link]([Link](matrix1));​

​// Example output for matrix1 after modification: [[1, 10, 3], [4, 5, 6], [7, 8, 9]]​

/​ / Using nested loops for custom printing format​


​for (int i = 0; i < [Link]; i++) {​
​for (int j = 0; j < matrix1[i].length; j++) {​
​[Link](matrix1[i][j] + " ");​
​}​
​[Link]();​ ​// New line after each row​
​}​
​/* Example Output for matrix1 after modification:​
​1 10 3​
​4 5 6​
​7 8 9​
​*/​

​Iterating:​

​// Using for-each loops (enhanced for loops)​


​for (int[] row : matrix1) { // Iterates through each inner array (row)​
​for (int num : row) { // Iterates through each element in the current row​
​[Link](num + " ");​
​}​
​[Link]();​
​}​
​/* Example Output for matrix1 after modification:​
​1 10 3​
​4 5 6​
​7 8 9​
​*/​

​Reading User Input:​

i​mport [Link];​
​import [Link];​ ​// Required for deepToString()​

​public class Main {​


​public static void main(String[] args) {​
​Scanner sc = new Scanner([Link]);​
​int rows = 2, cols = 3;​
​int[][] matrix = new int[rows][cols];​

​ [Link]("Enter " + rows + "x" + cols + " matrix elements:");​


S
​for (int i = 0; i < rows; i++) {​
​for (int j = 0; j < cols; j++) {​
​[Link]("Enter element at [" + i + "][" + j + "]: ");​
​matrix[i][j] = [Link]();​
​}​
​}​

​ [Link]("\nYour entered matrix:");​


S
​[Link]([Link](matrix));​

​[Link]();​
​}​
}​ ​
​/* 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​

​ our entered matrix:​


Y
​[[1, 2, 3], [4, 5, 6]]​
​*/​

​Key Differences: 1D vs 2D Arrays​

​Feature​ ​1D Array​ ​2D Array​

​Declaration​ ​int[] arr;​ ​int[][] matrix;​

​Initialization​ ​{1,2,3} or new int[3]​ {​ {1,2},{3,4}} or new​


​int[2][3]​

​Access​ ​arr[0]​ ​matrix[0][1]​

​Length​ ​[Link]​ ​ [Link] (number of​


m
​rows), matrix[0].length​
​(number of columns in​
​the first row)​

​Memory​ ​ ingle contiguous block​


S ​ rray of references to 1D​
A
​of elements​ ​arrays; each 1D array​
​(row) is a contiguous​
​block​

​When to Use Which?​

​●​ ​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​

​1.​ U ​ se [Link]()​​for convenient printing and debugging of​


​multi-dimensional arrays.​
​2.​ ​Prefer for-each loops​​when you only need to access the elements and do not​
​require their indices for logic.​
​3.​ ​Initialize jagged arrays carefully​​by creating each inner array explicitly to​
​avoid NullPointerException when trying to access elements of an uninitialized​
​inner array.​
​4.​ ​Remember that 2D arrays are "arrays of arrays"​​in Java, not a true single​
​block of memory like a matrix in C++. This distinction is important for​
​understanding memory layout and operations like jagged arrays.​

You might also like