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:
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:
Concatenating Strings
Joining strings together is a common task, and in Java, you can do this easily using the (+
) operator. Consider the following examples:
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).
Converting Case
You can convert text to all uppercase or lowercase using toUpperCase()
and toLowerCase()
methods:
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
Example B: Extract Between Two Indices
Let’s look at a more detailed example:
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:
Comparing Strings
Use the equals()
method to compare two strings:
Splitting a String
The split()
method divides a string based on a delimiter and returns an array of substrings:
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
2. Declaration and Initialization Combined
Or more succinctly:
3. Declaring an Array with a Fixed Size
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:
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:
Checking Array Equality
Copying a Range of an Array
The copyOfRange()
method copies a segment of an array into a new array:
Converting an Array to a String
Use toString()
to print an array’s contents:
Sorting Arrays
Sort an array in ascending order with sort()
:
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.
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:
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:
Reference Types
Reference types, like strings, arrays, and objects from classes, store the location (reference) where the data is actually held in memory:
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:
Explanation:
- When
original
is first assigned"Immutable"
, Java creates an object in memory to hold that value. - When you assign
"Modified"
tooriginal
, 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()
, andsplit()
. - 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.