0% found this document useful (0 votes)
3 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)
3 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
You are on page 1/ 17

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

​System.out.println(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};​

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

​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​​:​​array.length​​(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 < arr.length; i++) { ... arr[i] ... }​

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

​●​ ​Copying​​:​

​○​ ​System.arraycopy()​​:​​For efficient, low-level copying.​

​○​ ​Arrays.copyOf()​​:​​More convenient for full copies.​

​●​ ​Sorting​​:​​Arrays.sort(arr);​​(sorts in ascending order).​

​●​ ​Searching​​:​​Arrays.binarySearch(arr, key);​​(requires array to be sorted).​

​●​ ​Comparing​​:​​Arrays.equals(arr1, arr2);​​(checks for element-wise equality).​

​●​ ​Filling​​:​​Arrays.fill(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​​Arrays.copyOf()​​for array copying.​

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


​●​ U
​ se​​Arrays.toString()​​(1D) or​​Arrays.deepToString()​​(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};​


​System.out.println(numbers[0]);​ /​ / 10​
​System.out.println(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};​


​System.out.println(arr[3]);​ ​// Throws ArrayIndexOutOfBoundsException​

​5. Printing an Array​

​A. Using Arrays.toString() (Best for Debugging)​

​import java.util.Arrays;​

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


​System.out.println(Arrays.toString(arr));​ ​// [10, 20, 30]​

​B. Manual Printing (Using Loop)​

​for (int i = 0; i < arr.length; i++) {​


​System.out.print(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 arrayName.length (a​​field​​, not a method).​

​Example:​

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


​System.out.println(arr.length);​ ​// 3​

​9. Iterating Over an Array​

​A. Using for Loop​

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


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

​for (int num : arr) {​


​System.out.println(num);​
​}​

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

​Using Scanner​

​import java.util.Scanner;​

​public class Main {​


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

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

​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​ ​arrayName.length​ ​int len = arr.length;​

​Iteration (for Loop)​ f​ or (int i=0; i<arr.length;​ f​ or (int i=0; i<arr.length;​


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

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

​Printing Array​ ​Arrays.toString(arr)​ ​ ystem.out.println(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 Arrays.toString() 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.​
​●​ ​System.arraycopy() or manual copying can be used.​
​Example:​

i​mport java.util.Arrays;​
​import java.util.stream.IntStream; // 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[arr1.length + arr2.length];​

​ ystem.arraycopy(arr1, 0, result, 0, arr1.length);​


S
​System.arraycopy(arr2, 0, result, arr1.length, arr2.length);​

​System.out.println(Arrays.toString(result)); // [1, 2, 3, 4, 5, 6]​


​}​
​}​

​Alternative (Java 8+):​

/​ / 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]​

​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 Arrays.copyOfRange().​

​Example:​
​import java.util.Arrays;​

​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 = Arrays.copyOfRange(arr, 1, 4);​

​System.out.println(Arrays.toString(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 java.util.Arrays;​ ​// Required for deepToString()​

​// Using Arrays.deepToString() (best for multi-dimensional arrays)​

​System.out.println(Arrays.deepToString(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 < matrix1.length; i++) {​
​for (int j = 0; j < matrix1[i].length; j++) {​
​System.out.print(matrix1[i][j] + " ");​
​}​
​System.out.println();​ ​// 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​
​System.out.print(num + " ");​
​}​
​System.out.println();​
​}​
​/* Example Output for matrix1 after modification:​
​1 10 3​
​4 5 6​
​7 8 9​
​*/​

​Reading User Input:​

i​mport java.util.Scanner;​
​import java.util.Arrays;​ ​// Required for deepToString()​

​public class Main {​


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

​ ystem.out.println("Enter " + rows + "x" + cols + " matrix elements:");​


S
​for (int i = 0; i < rows; i++) {​
​for (int j = 0; j < cols; j++) {​
​System.out.print("Enter element at [" + i + "][" + j + "]: ");​
​matrix[i][j] = sc.nextInt();​
​}​
​}​

​ ystem.out.println("\nYour entered matrix:");​


S
​System.out.println(Arrays.deepToString(matrix));​

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

​ 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​ ​arr.length​ ​ atrix.length (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 Arrays.deepToString()​​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

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy