Working with Arrays and Strings in Java

Markdown

View as Markdown

Arrays and strings are among the most commonly used data structures in Java programming. Arrays allow you to store multiple values of the same data type in a single variable, while strings are used to store and manipulate text data.

In this article, you'll learn how to create and work with arrays, perform searching and sorting operations, and use the most common string methods for text processing.

Learning Objectives

  • Understand arrays and their purpose

  • Create one-dimensional and two-dimensional arrays

  • Read and display array elements

  • Search and sort arrays

  • Use the enhanced for loop with arrays

  • Work with Java strings

  • Compare and concatenate strings

  • Understand the differences between String, StringBuffer, and StringBuilder

What is an Array?

An array is a collection of elements of the same data type stored in contiguous memory locations. Each element is accessed using an index, starting from 0.

Example

int[] marks = {85, 90, 78, 92, 88};

In this example:

  • The array contains five integer values.

  • The first element is stored at index 0.

  • The last element is stored at index 4.

Creating an Array

Syntax

dataType[] arrayName = new dataType[size];

Example

int[] numbers = new int[5];

This creates an integer array capable of storing five values.

Initializing an Array

Values can be assigned individually.

int[] numbers = new int[5];

numbers[0] = 10;

numbers[1] = 20;

numbers[2] = 30;

numbers[3] = 40;

numbers[4] = 50;

Or during declaration.

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

Accessing Array Elements

Each element is accessed using its index.

Example

public class ArrayExample {

    public static void main(String[] args) {

        int[] marks = {75, 80, 85, 90};

        System.out.println(marks[0]);

        System.out.println(marks[2]);

 

    }

}

Output

75

85

One-Dimensional Arrays

A one-dimensional array stores data in a single row.

Example

public class OneDimensionalArray {

    public static void main(String[] args) {

        int[] marks = {80, 75, 90, 95, 88};

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

            System.out.println(marks[i]);

        }

    }

}

Output

80

75

90

95

88

Two-Dimensional Arrays

A two-dimensional array stores data in rows and columns.

Syntax

dataType[][] arrayName = new dataType[row][column];

Example

public class TwoDimensionalArray {

    public static void main(String[] args) {

        int[][] marks = {

                {80,85},

                {75,90},

                {95,88}

        };

        System.out.println(marks[1][0]);

    }

}

Output

75

Reading Array Elements Using Enhanced for Loop

The enhanced for loop simplifies iterating through arrays.

Example

int[] numbers = {5,10,15,20};

for(int value : numbers){

    System.out.println(value);

}

Output

5

10

15

20

Searching in an Array

The following example searches for a number within an array.

public class SearchArray {

    public static void main(String[] args) {

        int[] numbers = {15,25,35,45,55};

        int search = 35;

        boolean found = false;

        for(int number : numbers){

            if(number == search){

                found = true;

                break;

            }

        }

        if(found)

            System.out.println("Number Found");

        else

            System.out.println("Number Not Found");

    }

}

Output

Number Found

Sorting an Array

Java provides the Arrays.sort() method for sorting arrays.

Example

import java.util.Arrays;

public class SortArray {

    public static void main(String[] args) {

        int[] numbers = {40,15,60,25,10};

        Arrays.sort(numbers);

        for(int number : numbers){

            System.out.println(number);

        }

    }

}

Output

10

15

25

40

60

Introduction to Strings

A String represents a sequence of characters.

Example

String course = "Java Programming";

Strings are widely used for storing names, messages, email addresses, and other textual information.

 

Common String Methods

Java provides many built-in methods for manipulating strings.

length()

Returns the number of characters.

String text = "Java";

System.out.println(text.length());

Output : 4

toUpperCase()

Converts all characters to uppercase.

String language = "java";

System.out.println(language.toUpperCase());

Output

JAVA

toLowerCase()

Converts text to lowercase.

String language = "JAVA";

System.out.println(language.toLowerCase());

Output

java

charAt()

Returns the character at a specific position.

String word = "Programming";

System.out.println(word.charAt(3));

Output : g

substring()

Extracts part of a string.

String course = "Java Programming";

System.out.println(course.substring(5));

Output

Programming

Comparing Strings

Always use the equals() method to compare string values.

Example

String city1 = "Doha";

String city2 = "Doha";

System.out.println(city1.equals(city2));

Output

true

String Concatenation

Strings can be joined using the + operator.

Example

String firstName = "John";

String lastName = "David";

String fullName = firstName + " " + lastName;

System.out.println(fullName);

Output

John David

StringBuffer

StringBuffer is used when string modifications are required and thread safety is important.

Example

StringBuffer buffer = new StringBuffer("Java");

buffer.append(" Programming");

System.out.println(buffer);

Output

Java Programming

StringBuilder

StringBuilder is similar to StringBuffer but offers better performance in single-threaded applications.

Example

StringBuilder builder = new StringBuilder("Java");

builder.append(" Course");

System.out.println(builder);

Output

Java Course

Difference Between String, StringBuffer, and StringBuilder

Feature

String

StringBuffer

StringBuilder

Mutable

No

Yes

Yes

Thread Safe

No

Yes

No

Performance

Slower for repeated changes

Moderate

Faster

Best Used For

Fixed text

Multi-threaded applications

Single-threaded applications

Common Mistakes

Avoid these common mistakes when working with arrays and strings:

  • Accessing an array index outside its valid range.

  • Forgetting that array indexing starts at 0.

  • Comparing strings using == instead of equals().

  • Forgetting to import java.util.Arrays when using Arrays.sort().

  • Assuming String objects can be modified directly.

Practice Exercise

Create Java programs to:

  1. Store and display five student marks using a one-dimensional array.

  2. Create a two-dimensional array to store student marks for three subjects.

  3. Search for a number in an array.

  4. Sort an integer array in ascending order.

  5. Display array elements using the enhanced for loop.

  6. Compare two strings using the equals() method.

  7. Concatenate a student's first name and last name.

  8. Create examples using both StringBuffer and StringBuilder.

Was this article helpful?

Still need help?

Contact us