Bytes
rocket

Your Success, Our Mission!

6000+ Careers Transformed.

Working with Arrays

Last Updated: 22nd March, 2026

4.1 Working with Arrays

4.1.1 Explanation

An array in Java is a collection of elements of the same data type stored in a contiguous block of memory. Arrays allow developers to manage fixed-size sequential data efficiently. Unlike dynamic collections, arrays have a fixed length once created, making them lightweight and performant for small-scale, predictable data operations.

Each element in an array is accessed by an index, starting at 0. Arrays can be single-dimensional (linear) or multidimensional (tables, matrices). Java also supports array copyingcloning, and utility methods from the java.util.Arrays class such as sort(), binarySearch(), and fill().

Internally, arrays are objects in Java — meaning they reside on the heap memory and can be passed by reference. When manipulated, their reference is copied, not the data itself. This is crucial to avoid unintentional mutations when arrays are passed as parameters.
While arrays are efficient for small, structured data, Collections (like ArrayList) are preferred for dynamic datasets.

4.1.2 Code

import java.util.Arrays;

public class ArrayDemo {

public static void main(String[] args) {

int[] numbers = {5, 3, 8, 1, 2}; // Declaration and initialization

System.out.println("Original Array: " + Arrays.toString(numbers));

Arrays.sort(numbers); // Sorting array

System.out.println("Sorted Array: " + Arrays.toString(numbers));

int index = Arrays.binarySearch(numbers, 3); // Searching element

System.out.println("Index of 3: " + index);

int[] copied = Arrays.copyOf(numbers, numbers.length); // Copy array

System.out.println("Copied Array: " + Arrays.toString(copied));

}

}

4.1.3 Example

Output:

Original Array: [5, 3, 8, 1, 2]

Sorted Array: [1, 2, 3, 5, 8]

Index of 3: 2

Copied Array: [1, 2, 3, 5, 8]

Explanation:
An integer array is declared and sorted using Arrays.sort(). The binarySearch() method efficiently finds the index of a given value (after sorting), while Arrays.copyOf() duplicates the entire array.
All these utility methods simplify complex operations while maintaining efficiency.

4.1.4 Use Cases

  • Handling small collections of data where size is known in advance.
  • Storing sensor readings, exam scores, or static datasets.
  • Implementing basic algorithms (sorting, searching, matrix manipulation).
  • Teaching memory management and reference concepts in education.

4.1.5 Relevant Table

Operation

Description

Example

Result

Declaration

Define array type

int[] a = new int[5];

Empty array

Initialization

Assign values

int[] b = {1,2,3};

Populated array

Sorting

Rearrange ascending

Arrays.sort(b);

[1,2,3]

Searching

Binary search value

Arrays.binarySearch(b,2)

1

Copying

Duplicate array

Arrays.copyOf(b,3)

[1,2,3]

4.2 String Handling

4.2.1 Explanation

Strings are among the most used objects in Java. A String is an immutable sequence of characters — once created, it cannot be modified. Every string literal in Java is stored in a String Constant Pool (SCP) to improve memory efficiency and reusability.

Operations such as concatenation, comparison, and substring extraction are done through methods of the String class.
Common methods include length(), charAt(), substring(), equals(), compareTo(), and replace().

Java also offers mutable alternatives like StringBuilder and StringBuffer for cases where frequent modifications are required. StringBuilder is faster but not thread-safe, while StringBuffer is synchronized and ideal for multi-threaded environments.

Understanding the immutability of String objects helps prevent bugs related to unintended changes and improves performance in memory-sensitive applications.

4.2.2 Code

public class StringExample {

public static void main(String[] args) {

String s1 = "Java";

String s2 = "Tutorial";

String combined = s1 + " " + s2;

System.out.println("Combined String: " + combined);

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

System.out.println("Substring: " + combined.substring(0, 4));

System.out.println("Uppercase: " + combined.toUpperCase());

System.out.println("Contains 'Java': " + combined.contains("Java"));

// Using StringBuilder

StringBuilder sb = new StringBuilder("Learning");

sb.append(" Java 2025");

System.out.println("StringBuilder Output: " + sb);

}

}

4.2.3 Example

Output:

Combined String: Java Tutorial

Length: 13

Substring: Java

Uppercase: JAVA TUTORIAL

Contains 'Java': true

StringBuilder Output: Learning Java 2025

Explanation:
This code demonstrates String operations, immutability, and the mutable alternative StringBuilder. The original strings remain unchanged during concatenation, showing Java’s immutable string design.

4.2.4 Use Cases

  • Text processing in applications (input validation, user data).
  • File reading and manipulation (line parsing).
  • Building dynamic SQL queries or log messages.
  • Designing lightweight text editors or interpreters.

4.2.5 Relevant Table

Class

Mutable

Thread-Safe

Best Use Case

String

No

Yes (immutable)

Constant text or keys

StringBuilder

Yes

No

Single-threaded string concatenation

StringBuffer

Yes

Yes

Multi-threaded text operations

4.3 Wrapper Classes and Autoboxing

4.3.1 Explanation

Wrapper classes in Java provide object representations of primitive data types. They reside in the java.lang package and include classes like Integer, Double, Boolean, Character, etc.
They enable primitives to be used in Collections (which store objects) and provide useful methods for data conversion, comparison, and formatting.

For example:

  • int → Integer
  • char → Character
  • double → Double

Autoboxing automatically converts a primitive to its wrapper class, while unboxing converts it back. These were introduced in Java 5 to simplify conversions and enhance interoperability.

However, unnecessary boxing/unboxing can degrade performance, especially in loops, so developers should use them judiciously. Wrapper classes also provide utility methods such as parseInt(), toString(), and constants like Integer.MAX_VALUE.

4.3.2 Code

public class WrapperDemo {

public static void main(String[] args) {

int primitiveInt = 42;

Integer boxedInt = primitiveInt; // Autoboxing

int unboxedInt = boxedInt;       // Unboxing

Double boxedDouble = Double.valueOf(3.14159);

boolean isEqual = boxedInt.equals(42);

System.out.println("Primitive: " + primitiveInt);

System.out.println("Boxed: " + boxedInt);

System.out.println("Unboxed: " + unboxedInt);

System.out.println("Double Object: " + boxedDouble);

System.out.println("Equals 42: " + isEqual);

// Using Wrapper Utility Methods

String number = "100";

int parsed = Integer.parseInt(number);

System.out.println("Parsed int from String: " + parsed);

}

}

4.3.3 Example

Output:

Primitive: 42

Boxed: 42

Unboxed: 42

Double Object: 3.14159

Equals 42: true

Parsed int from String: 100

Explanation:
Autoboxing and unboxing simplify handling of primitives and objects. The program also shows parseInt() converting a String to an int — a common real-world conversion technique in data input or database parsing.

4.3.4 Use Cases

  • Storing primitive values in Collections (ArrayList<Integer>).
  • Performing numeric conversions from text input.
  • Handling nullable numeric values in enterprise applications.
  • Leveraging wrapper constants (MAX_VALUE, MIN_VALUE) for range validation.

4.3.5 Relevant Table

Primitive Type

Wrapper Class

Example

Conversion

int

Integer

Integer x = 5;

Autoboxing

double

Double

Double d = 3.14;

Autoboxing

boolean

Boolean

Boolean flag = true;

Autoboxing

char

Character

Character c = 'A';

Autoboxing

Module 4: Strings, Arrays, and Wrapper Classes Working with Arrays

Top Tutorials

Logo
Computer Science

CNN in Deep Learning 2026

A beginner-friendly guide to CNNs: understand deep learning essentials, create Python-based models, and explore advanced applications.

4 Modules12 Lessons151 Learners
Start Learning
Logo
Computer Science

Breaking The Limits: Scaling Databases with MySQL Partitioning

Learn MySQL partitioning with examples. Improve query performance, scalability, and data management using RANGE, LIST, HASH, KEY, and composite techniques.

7 Modules11 Lessons71 Learners
Start Learning
Logo

ML in Action: Hands-On Guide to Deploying and Serving Models

Learn model deployment and serving—from concepts to real-world architectures, tools, APIs, containers, and cloud workflows for production-ready ML.

4 Modules10 Lessons78 Learners
Start Learning
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2026 AlmaBetter