4. Working with Arrays and Strings in Java

In Java, working with text and collections is straightforward once you understand the fundamentals. This guide covers how to use strings and arrays, explores the built-in methods available for each, and explains the crucial difference between primitive types and reference types—all using Java 17’s API. With plenty of code examples and explanations, you’ll gain the confidence to work with these essential concepts in your own programs.


Understanding Strings in Java

A string in Java is a sequence of characters enclosed in double quotes, commonly used to store and manipulate text such as names, messages, or file paths. Strings are a core part of any program, and Java provides a range of methods to help you work with them efficiently.

Declaring and Initializing Strings

To declare and initialize a string, you write:

String greeting = "Hello, Java!";

In this example, the variable greeting holds the text "Hello, Java!". Notice the double quotes around the text.

You can also initialize a string with no content:

String emptyText = "";

Concatenating Strings

Joining strings together is a common task, and in Java, you can do this easily using the (+) operator. Consider the following examples:

// Concatenating directly:
String welcome = "Hello, " + "World!";
System.out.println(welcome); // Output: Hello, World!
// Using variables:
String firstName = "Alice";
String message = "Welcome, " + firstName + "!";
System.out.println(message); // Output: Welcome, Alice!

This method is useful for dynamically creating messages by combining strings and variables.


Common String Methods

Since a string in Java is an object of the String class, it comes with many built-in methods. Let’s explore some key methods with detailed examples.

Finding the Length of a String

The length() method returns the number of characters in a string (including spaces and punctuation).

String phrase = "Java Programming";
int lengthOfPhrase = phrase.length();
System.out.println("The length is: " + lengthOfPhrase);
// Output: The length is: 16

This method is particularly useful when validating user input or when you need to limit text length.

Converting Case

You can convert text to all uppercase or lowercase using toUpperCase() and toLowerCase() methods:

String mixedCase = "Java is Fun!";
String upper = mixedCase.toUpperCase();
String lower = mixedCase.toLowerCase();
System.out.println("Uppercase: " + upper); // Output: JAVA IS FUN!
System.out.println("Lowercase: " + lower); // Output: java is fun!

These methods are helpful in cases where you need case-insensitive comparisons or when formatting output.

Extracting Substrings

The substring() method lets you extract part of a string. There are two common forms:

Example A: Extract from a Given Index to the End

String text = "Beginner Java";
String subFromIndex = text.substring(8);
System.out.println(subFromIndex);
// Output: Java

In this example, the substring starts at index 8 and continues to the end of the string.

Example B: Extract Between Two Indices

Let’s look at a more detailed example:

String word = "Programming";
// We want to extract the characters from index 3 up to (but not including) index 7.
String segment = word.substring(3, 7);
System.out.println(segment);
// Explanation:
// Index positions: P(0) r(1) o(2) g(3) r(4) a(5) m(6) m(7) i(8) n(9) g(10)
// The segment from index 3 to index 6 is "gram"
// Output: Extracted segment: gram

This example illustrates that the first parameter is the starting index (inclusive) and the second is the ending index (exclusive).

Accessing a Specific Character

The charAt() method returns the character at a specific index:

String sample = "Hello!";
char letter = sample.charAt(1);
System.out.println(letter);
// Output: Character at index 1: e

Comparing Strings

Use the equals() method to compare two strings:

String str1 = "Java Tutorial";
String str2 = "Java Tutorial";
String str3 = "Coding Guide";
boolean same = str1.equals(str2);
boolean different = str1.equals(str3);
System.out.println("Are str1 and str2 equal? " + same); // true
System.out.println("Are str1 and str3 equal? " + different); // false

Splitting a String

The split() method divides a string based on a delimiter and returns an array of substrings:

String names = "Alice,Bob,Charlie,David";
String[] nameArray = names.split(",");
System.out.println("Names array: " + java.util.Arrays.toString(nameArray));
// Output: Names array: [Alice, Bob, Charlie, David]

In this example, the string is split at each comma.


Exploring Arrays in Java

An array is a collection of elements of the same type, stored in contiguous memory locations. Arrays are useful when you need to manage lists of data, such as numbers, names, or objects.

Declaring and Initializing Arrays

There are multiple ways to declare and initialize arrays in Java:

1. Declaration Followed by Initialization

int[] ages;
ages = new int[] {18, 21, 25, 30, 35};

2. Declaration and Initialization Combined

int[] scores = new int[] {90, 85, 75, 80, 95};

Or more succinctly:

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

3. Declaring an Array with a Fixed Size

int[] numbers = new int[5];
// Initially, numbers becomes {0, 0, 0, 0, 0} since the default value for int is 0.

Accessing and Modifying Array Elements

Arrays are zero-indexed, meaning the first element is at index 0. Here’s how to access and update elements:

int[] marks = {70, 80, 90, 100}
// Access the first element (index 0)
System.out.println(marks[0]); // Output: 70
// Update the third element (index 2)
marks[2] = 95;
System.out.println("Updated marks: " + java.util.Arrays.toString(marks));
// Output: Updated marks: [70, 80, 95, 100]

Array Methods from java.util.Arrays

Java provides a utility class Arrays (found in the java.util package) that offers many static methods for working with arrays. To use these methods, include the import statement at the top of your file:

import java.util.Arrays;

Checking Array Equality

int[] listA = {1, 2, 3, 4};
int[] listB = {1, 2, 3, 4};
int[] listC = {4, 3, 2, 1};
boolean isEqualAB = Arrays.equals(listA, listB); // true
boolean isEqualAC = Arrays.equals(listA, listC); // false
System.out.println("listA equals listB: " + isEqualAB); // Output: listA equals listB: true
System.out.println("listA equals listC: " + isEqualAC); // Output: listA equals listC: false

Copying a Range of an Array

The copyOfRange() method copies a segment of an array into a new array:

int[] original = {10, 20, 30, 40, 50, 60};
int[] partial = Arrays.copyOfRange(original, 2, 5);
// This copies elements at indexes 2, 3, and 4 into partial.
System.out.println("Partial array: " + Arrays.toString(partial));
// Output: Partial array: [30, 40, 50]

Converting an Array to a String

Use toString() to print an array’s contents:

int[] data = {5, 10, 15, 20};
System.out.println("Data array: " + Arrays.toString(data));
// Output: Data array: [5, 10, 15, 20]

Sorting Arrays

Sort an array in ascending order with sort():

int[] unsorted = {42, 7, 19, 3, 28};
Arrays.sort(unsorted);
System.out.println("Sorted array: " + Arrays.toString(unsorted));
// Output: Sorted array: [3, 7, 19, 28, 42]

Searching in a Sorted Array

When you have a sorted array, you can efficiently search for values using the Arrays.binarySearch() method. It returns either the index of the value if found or a negative result indicating where the value would be inserted if it’s not present.

int[] sorted = {5, 10, 15, 20, 25};
int pos = Arrays.binarySearch(sorted, 20);
System.out.println("Position of 20: " + pos);
// Output: Position of 20: 3
// If the value is not found, a negative number is returned:
int notFound = Arrays.binarySearch(sorted, 12);
System.out.println("Position of 12 (not found): " + notFound); // Output: Position of 12 (not found): -4
Note: When a value isn’t found, the negative result indicates where the element would be inserted (with a slight adjustment).

When the value is not found, the method returns a negative result following the formula:

-(insertion point) - 1

In this example, searching for 12 gives us -4. To find where 12 would be inserted in the sorted array, reverse the formula:

insertion point = -(negative result) - 1
insertion point = -(-4) - 1 = 3

Determining the Array’s Length

Unlike strings (which use a method), arrays use a field to report their size:

int[] values = {2, 4, 6, 8, 10};
int arraySize = values.length;
System.out.println("Array size: " + arraySize);
// Output: Array size: 5

Primitive Types vs. Reference Types

Java data types are divided into primitive types and reference types.

Primitive Types

These include byte, short, int, long, float, double, char, and boolean. They store actual values. For example:

int count = 100;
// Here, count directly holds the value 100.

Reference Types

Reference types, like strings, arrays, and objects from classes, store the location (reference) where the data is actually held in memory:

String text = "Hello, world!";
// Although text appears to contain the string, it actually stores a reference to where "Hello, world!" is kept.

Understanding this distinction is crucial because it affects how data is passed and manipulated within your programs.


Immutability of Strings

A key characteristic of Java strings is that they are immutable. This means that once a string is created, its content cannot be changed. Instead, any operation that modifies a string creates a new string.

How Immutability Works

Consider the following example:

String original = "Immutable";
System.out.println("Original: " + original); // Output: Original: Immutable
// Changing the value of the string:
original = "Modified";
System.out.println("After modification: " + original); // Output: After modification: Modified

Explanation:

  • When original is first assigned "Immutable", Java creates an object in memory to hold that value.
  • When you assign "Modified" to original, Java does not change the existing object; it creates a new string object and updates the reference.
  • The original string remains unchanged in memory until the garbage collector reclaims it.

This immutability leads to better performance in multi-threaded environments and helps maintain data integrity.


Conclusion

This post has provided a comprehensive overview of Java strings and arrays:

  • Strings are sequences of characters that come with many methods for manipulation, such as substring(), charAt(), and split().
  • Arrays are collections of elements of the same type, with operations like sorting, copying ranges, and searching.
  • A clear understanding of primitive types vs. reference types is essential, as is knowing that strings are immutable.

With these detailed examples and explanations, you now have a solid foundation to explore further Java programming topics. Practice these examples by writing your own small programs and experimenting with variations to reinforce your learning.

Share this article
Shareable URL
Prev Post

Dynamic Spacetime Modulation Engine

Next Post

The Q-Cube Gravity Antenna: A Blueprint for Microgravity Wave Detection and Interstellar Communication

Leave a Reply

Your email address will not be published. Required fields are marked *

Read next

1. Introduction to Java

Welcome to Java programming!This series of posts is designed to be a refresher for experienced developers and a…