Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Monday, March 10, 2025

Array, List, and String in Java


Arrays, Lists, and Strings are fundamental data structures in Java. They are used to store and manipulate data efficiently. Let us understand each of these in detail.


📌 1. Arrays in Java

An array is a collection of elements of the same type stored in contiguous memory locations. Arrays are fixed in size and are indexed starting from 0.

Syntax:

dataType[] arrayName = new dataType[size];

Example:

public class ArrayExample {

    public static void main(String[] args) {

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

 

        // Accessing array elements

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

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

        }

 

        // Modifying an element

        numbers[2] = 35;

        System.out.println("Updated element at index 2: " + numbers[2]);

    }

}

Output:

Element at index 0: 10

Element at index 1: 20

Element at index 2: 30

Element at index 3: 40

Element at index 4: 50

Updated element at index 2: 35


Advantages of Arrays:

  1. Efficient Access: O(1) access time for elements.
  2. Memory Efficiency: Uses contiguous memory locations.

🚩 Limitations:

  1. Fixed Size: Cannot be resized once created.
  2. Homogeneous: Stores elements of the same type.

📌 2. Lists in Java

A List in Java is a part of the Collections Framework and can grow dynamically. It is an ordered collection that allows duplicate elements.

Common Implementations:

  • ArrayList - Dynamic array.
  • LinkedList - Doubly linked list.
  • Vector - Synchronized version of ArrayList.

Syntax:

List<dataType> listName = new ArrayList<>();

Example:

import java.util.*;

 

public class ListExample {

    public static void main(String[] args) {

        List<String> cities = new ArrayList<>();

 

        // Adding elements

        cities.add("New York");

        cities.add("London");

        cities.add("Tokyo");

        cities.add("New Delhi");

 

        // Accessing elements

        System.out.println("First city: " + cities.get(0));

 

        // Iterating using a for-each loop

        for (String city : cities) {

            System.out.println("City: " + city);

        }

 

        // Removing an element

        cities.remove("Tokyo");

        System.out.println("After removal: " + cities);

    }

}

Output:

First city: New York

City: New York

City: London

City: Tokyo

City: New Delhi

After removal: [New York, London, New Delhi]


Advantages of Lists:

  1. Dynamic Size: Can grow and shrink as needed.
  2. Rich Methods: Supports insertion, deletion, and iteration.
  3. Flexible: Can hold heterogeneous data (if using Object).

🚩 Limitations:

  1. Performance: Access time can vary (O(1) for ArrayList, O(n) for LinkedList).
  2. Memory Usage: Can consume more memory compared to arrays.

📌 3. Strings in Java

A String in Java is a sequence of characters. Strings are immutable, which means they cannot be changed after creation.

Creating Strings:

  1. Using String literal:

2.  String str1 = "Hello";

  1. Using new keyword:

4.  String str2 = new String("World");


Example:

public class StringExample {

    public static void main(String[] args) {

        String str1 = "Hello";

        String str2 = "World";

        String str3 = str1 + " " + str2;

 

        // Concatenation

        System.out.println("Concatenated String: " + str3);

 

        // String length

        System.out.println("Length of str3: " + str3.length());

 

        // Character at a specific index

        System.out.println("Character at index 1: " + str3.charAt(1));

 

        // Substring

        System.out.println("Substring (0, 5): " + str3.substring(0, 5));

 

        // String Comparison

        String str4 = "Hello";

        System.out.println("str1 equals str4: " + str1.equals(str4));

    }

}

Output:

Concatenated String: Hello World

Length of str3: 11

Character at index 1: e

Substring (0, 5): Hello

str1 equals str4: true


Advantages of Strings:

  1. Immutable: Ensures security and thread safety.
  2. Memory Efficiency: Uses the String Pool for reuse.
  3. Rich Methods: Supports various methods like concat(), substring(), equals(), etc.

🚩 Limitations:

  1. Memory Consumption: Creating many strings can cause memory issues.
  2. Performance: String concatenation using + is inefficient; use StringBuilder or StringBuffer.

📊 Comparison: Arrays, Lists, and Strings

Feature

Array

List

String

Size

Fixed

Dynamic

Immutable

Data Type

Homogeneous

Heterogeneous

Characters

Memory Efficiency

High

Moderate

High (if reused)

Access Time

O(1)

O(1) (ArrayList), O(n) (LinkedList)

O(1)

Flexibility

Low

High

Low

Mutability

Mutable

Mutable

Immutable

Usage

Data storage

Dynamic data manipulation

Text manipulation


📝 When to Use:

  • Array: When the size is fixed and efficient access is needed.
  • List: When the size changes dynamically or when using collection methods.
  • String: When storing and manipulating textual data.

Would you like me to explain more about StringBuilder, StringBuffer, or advanced list operations? Let me know! 😊

 

No comments:

Post a Comment