0% found this document useful (0 votes)
28 views15 pages

Arrays in Java

about java arrays

Uploaded by

vasanthnvijay
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)
28 views15 pages

Arrays in Java

about java arrays

Uploaded by

vasanthnvijay
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/ 15

Arrays in Java

Part-1

Introduction

In Java, an array is a linear data structure that stores multiple values of the same type in a single
variable. Arrays are objects, and they implicitly inherit from java.lang.Object, allowing use of methods
like toString(), equals(), and hashCode().

Key Features

• Store Primitives & Objects: Arrays can store primitive types (int, char, etc.) and object references
(String, Student, etc.).

• Contiguous Memory Allocation: Elements are stored in continuous memory locations.

• Zero-Based Indexing: Index starts at 0.

• Fixed Length: Size is defined at creation and cannot be changed.

CoderBaba Page | 1
Basic Operations

1. Declaring Arrays

int[] arr1; // or

int arr2[];

2. Initializing Arrays

3. Using Array Literals

4. Changing an Element

5. Accessing Elements with Loop

CoderBaba Page | 2
Example: Integer Array

Arrays of Objects

CoderBaba Page | 3
Array Index Out of Bounds

Accessing an index beyond the array size throws:

ArrayIndexOutOfBoundsException

Passing Arrays to Methods

Returning Arrays from Methods

Advantages

• Fast Access: O(1) for accessing by index

• Structured Organization: Useful for grouping similar data

• Predictable Memory Use

Disadvantages

• Fixed Size: Cannot resize once created

• Type Restriction: Homogeneous element types

• Costly Insertions/Deletions: Shifting required

CoderBaba Page | 4
Basics Operation on Arrays in Java

1. Declaring an Array in Java

General Syntax:

Java allows two common ways to declare an array:

// Method 1:

int arr[];

// Method 2 (preferred):

int[] arr;

Both declarations are valid and functionally equivalent. The second form (int[] arr) is preferred for better
readability, especially when declaring multiple variables.

Element Type

The element type (e.g., int, char, String) determines what type of values the array will store.

You can declare arrays for:

• Primitive types: int[], char[], double[], boolean[], etc.

• Reference types (objects): String[], Student[], Object[], etc.

Important Note:

Declaring an array does not create the array in memory.

int[] arr; // Only declares a reference variable

At this stage, arr does not point to any actual array. You must use new to allocate memory before using
it.

CoderBaba Page | 5
2. Initialization of an Array in Java

• When you declare an array in Java, only a reference is created — no actual memory for elements
is allocated at that point.

Example:

int[] arr; // Declaration only (no memory allocated yet)

• To allocate memory, use the new keyword:

arr = new int[5]; // Allocates memory for 5 integers

• Or declare and initialize in one line:

int[] arr = new int[5];

Key Points

• Memory is always dynamically allocated (on the heap), unlike in C/C++ where static and
dynamic allocation are both possible.

• Once allocated using new, elements are automatically initialized:

o 0 for numeric types (int, float, etc.)

o false for boolean

o null for reference types (e.g., String, Object)

Example:

String[] names = new String[3]; // All elements are initialized to null

• Note: Arrays in Java are not dynamically resizable — size must be fixed at creation. For resizable
structures, use ArrayList.

CoderBaba Page | 6
Array Literals in Java

Definition:

An array literal in Java is a shorthand way to declare and initialize an array when both the size and the
values are known at the time of declaration.

Syntax:

// Using array literal with 'new':

int[] arr = new int[]{1, 2, 3, 4, 5};

// In modern Java, 'new int[]' can be omitted:

int[] arr = {1, 2, 3, 4, 5};

Both forms are valid. The second form is shorter and more commonly used.

Key Points:

• The size of the array is automatically determined by the number of elements in the literal.

• Array literals can only be used at the time of declaration.

• Works with both primitive and reference types:

String[] names = {"Alice", "Bob", "Charlie"};

Invalid Example:

You cannot use array literals after declaration like this:

int[] arr;

arr = {1, 2, 3}; // ❌ Compilation error

You must use new int[] in this case:

arr = new int[]{1, 2, 3}; // ✅ Valid

CoderBaba Page | 7
3. Changing an Array Element in Java

How It Works:

In Java, you can change the value of an array element by assigning a new value to a specific index.

Syntax:

arrayName[index] = newValue;

Example:

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

// Changing the first element (index 0) to 90

arr[0] = 90;

Key Points:

• Array indices in Java start at 0.

• The last element is at index length - 1.

• Always ensure the index is within bounds, or Java will throw an


ArrayIndexOutOfBoundsException.

CoderBaba Page | 8
4. Array Length in Java

Description:

In Java, every array has a built-in length property (not a method) that returns the number of elements in
the array.

Syntax:

int n = arr.length;

Example:

int[] arr = {10, 20, 30, 40};

// Getting the length of the array

int n = arr.length;

System.out.println("Length of array: " + n); // Output: 4

Key Point:

• Unlike strings (str.length()), arrays use .length without parentheses.

• The length value is fixed and equals the number of elements in the array.

5. Accessing and Updating All Array Elements in Java

Description:

You can access and update all elements of an array using a for loop by iterating through their indices.

Accessing Elements:

int[] arr = {10, 20, 30, 40};

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

System.out.println("Element at index " + i + " : " + arr[i]);

CoderBaba Page | 9
Updating Elements:

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

arr[i] = arr[i] + 5; // Increase each element by 5

Using Enhanced For Loop (Read-Only Access):

for (int value : arr) {

System.out.println(value);

Note: The enhanced for loop (for-each) is used only for reading values, not updating them directly.

Key Points:

• Array elements are accessed using zero-based indexing.

• Use a standard for loop for both reading and modifying elements.

• Use arr.length to avoid hardcoding the array size.

Here is a refined short note for:

Arrays of Objects in Java

Description:

In Java, you can create arrays of objects just like arrays of primitive data types. Each element in the array
holds a reference to an object, not the object itself.

CoderBaba Page | 10
Example: Array of Student Objects
class Student {
public int roll_no;
public String name;

Student(int roll_no, String name) {


this.roll_no = roll_no;
this.name = name;
}
}

public class Geeks {


public static void main(String[] args) {

// Declare an array of Student objects


Student[] arr = new Student[5];

// Initialize array elements


arr[0] = new Student(1, "Aman");
arr[1] = new Student(2, "Vaibhav");
arr[2] = new Student(3, "Shikhar");
arr[3] = new Student(4, "Dharmesh");
arr[4] = new Student(5, "Mohit");

// Access and print object data


for (int i = 0; i < arr.length; i++) {
System.out.println("Element at " + i + " : { "
+ arr[i].roll_no + " " + arr[i].name + " }");
}
}
}

Key Points:
• Object arrays store references to objects.
• Memory for the array is allocated using:
Student[] arr = new Student[5];
• Each element must be individually initialized using the constructor.
• You can then access object members using the dot (.) operator:

arr[i].roll_no, arr[i].name

CoderBaba Page | 11
Accessing Elements Outside Array Bounds in Java

What Happens?

If you try to access an element outside the valid index range of an array in Java, the JVM throws an
exception:

ArrayIndexOutOfBoundsException

This occurs when:

• The index is negative, or

• The index is greater than or equal to the array’s length.

Example:

public class Geeks {

public static void main(String[] args) {

int[] arr = new int[4];

arr[0] = 10;

arr[1] = 20;

arr[2] = 30;

arr[3] = 40;

System.out.println("Trying to access element outside the size of array");

System.out.println(arr[5]); // ❌ Invalid index

Output:

Trying to access element outside the size of array

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length


4 at Geeks.main(Geeks.java:9)

CoderBaba Page | 12
Key Points:

• Valid indices range from 0 to arr.length - 1.

• Java performs strict bounds checking to avoid unsafe memory access.

• Always use arr.length in loops and access logic to avoid this error.

Passing Arrays to Methods in Java

Description:

Just like variables, arrays can be passed to methods in Java. When an array is passed to a method, its
reference is passed, meaning any changes made to the array inside the method affect the original array.

Example: Passing Array to Method

public class Geeks {


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

// Passing array to method


sum(arr);
}

public static void sum(int[] arr) {


int sum = 0;
for (int i = 0; i < arr.length; i++)
sum += arr[i];
System.out.println("Sum of array values: " + sum);
}
}

Output

Sum of array values: 15

Key Points:

• Arrays are passed by reference, not by value.

• The method receives access to the original array in memory.

• You can pass both primitive type arrays and object arrays to methods.

CoderBaba Page | 13
Passing Arrays to Methods & Returning Arrays from Methods in Java

Passing Arrays to Methods

You can pass arrays to methods just like regular variables. The method receives a reference to the
original array.

Example:

public class Geeks {

public static void main(String[] args) {

int[] arr = {3, 1, 2, 5, 4};

sum(arr); // Passing array to method

public static void sum(int[] arr) {

int sum = 0;

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

sum += arr[i];

System.out.println("Sum of array values: " + sum);

Explanation:

• The array arr is declared and initialized in main().

• It is passed to the method sum().

• sum() calculates the total using a for loop.

• The final result is printed:


Output:
Sum of array values: 15

Returning Arrays from Methods

In Java, methods can return arrays. This is useful when you want to generate and send back a full array
from a method.

CoderBaba Page | 14
Example:

class Geeks {

public static void main(String[] args) {

int[] arr = m1(); // Receiving array from method

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

System.out.print(arr[i] + " ");

public static int[] m1() {

return new int[] {1, 2, 3}; // Returning an array

Output:

123

Advantages of Java Arrays

• Efficient Access: Accessing elements by index is fast (O(1) time complexity).

• Memory Management: Fixed size makes memory use predictable.

• Data Organization: Helps group related data together.

Disadvantages of Java Arrays

• Fixed Size: Can't be resized once created.

• Type Homogeneity: Can only store elements of the same data type.

• Costly Insertions/Deletions: Modifying elements in the middle requires shifting, which can be
inefficient.

CoderBaba Page | 15

You might also like