In Java, a character array is a data structure used to store a sequence of characters. The characters are stored in contiguous memory locations and can be accessed by their index, similar to an array of integers or any other data type.
Declaring a Character Array
A character array can be declared in the following way:
char[] charArray;
This declares a reference variable called charArray that can store the memory address of a character array. To initialize the array and allocate memory for it, you can use the new keyword:
charArray = new char[10];
This creates an array with a length of 10, which means it can store 10 characters. The elements of the array are initialized to the default value of the char data type, which is the null character ('\u0000').
Alternatively, you can declare and initialize a character array in a single line:
char[] charArray = new char[10];
You can also initialize a character array with a set of characters by using the curly braces {} notation:
char[] charArray = {'a', 'b', 'c', 'd', 'e'};
This creates an array with a length of 5 and assigns the characters 'a', 'b', 'c', 'd', and 'e' to the elements at indexes 0 through 4, respectively.
Accessing Elements in a Character Array
You can access the elements of a character array using the array name followed by the element's index in square brackets. For example:
charArray[0] = 'f';
This assigns the character 'f' to the element at index 0 of the charArray. You can also use the array elements to perform operations. For example:
System.out.println(charArray[0] + " " + charArray[1]);
This prints the characters at index 0 and 1 of the charArray, separated by a space.
Iterating Over a Character Array
You can use a for loop to iterate over the elements of a character array. For example:
Java
for (int i = 0; i < charArray.length; i++) {
System.out.println(charArray[i]);
}
This prints each element of the charArray on a new line.
Another way to iterate over a character array is to use the enhanced for loop (also known as the for-each loop):
Java
for (char c : charArray) {
System.out.println(c);
}
This also prints each element of the charArray on a new line.
Comparing Character Arrays
To compare two character arrays for equality, you can use the Arrays.equals() method:
Java
char[] charArray1 = {'a', 'b', 'c', 'd', 'e'};
char[] charArray2 = {'a', 'b', 'c', 'd', 'e'};
if (Arrays.equals(charArray1, charArray2)) {
System.out.println("The arrays are equal.");
} else {
System.out.println("The arrays are not equal.");
}
This compares the elements of charArray1 and charArray2, and if all the elements are identical, it prints "The arrays are equal." Otherwise, it prints "The arrays are not equal."
Converting a String to a Character Array
You can convert a String to a character array using the toCharArray() method:
Java
String str = "Hello World";
char[] charArray = str.toCharArray();
This creates a character array with the same characters as the string and assigns it to the charArray variable.
Converting a Character Array to a String
You can convert a character array to a String using the String constructor that takes a character array as an argument:
Java
char[] charArray = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};
String str = new String(charArray);
This creates a new String object with the same characters as the charArray, and assigns it to the str variable.
Note that, while you can use the "==" operator to compare the references of two arrays, it will not compare the elements of the arrays. So if you want to compare the two arrays, you should use the Arrays.equals(arr1, arr2) method, which returns true if the two arrays are equal, and false otherwise.
copyOf() method from the Arrays class: This method creates a new array with the same length as the original array and copies the elements from the original array to the new array. It can be used to make a copy of a character array, which is useful when you want to make changes to the original array without affecting the original data.
Example of copyOf() method:
Java
char[] originalArray = {'a', 'b', 'c', 'd', 'e'};
char[] copiedArray = Arrays.copyOf(originalArray, originalArray.length);
Here, the originalArray is copied to the copiedArray. Now, you can make changes to the copiedArray without affecting the originalArray.
copyOfRange() method from the Arrays class: This method creates a new array with the specified range of elements from the original array and copies the elements from the original array to the new array. It can be used to make a copy of a specific range of elements in a character array.
Example of copyOfRange() method:
Java
char[] originalArray = {'a', 'b', 'c', 'd', 'e'};
char[] copiedArray = Arrays.copyOfRange(originalArray, 1, 4);
Here, the elements of the originalArray are copied from index 1 to index 3 to the copiedArray.
When working with character arrays is that they are mutable, meaning their elements can be changed after they are created. Strings, on the other hand, are immutable, meaning their characters cannot be changed after they are created. If you need to change the characters in a string, you must create a new string with the desired characters.
Similar Reads
How to Convert Character Array to String in Java? Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character "\0". A character array can be converted to a string and vice versa. In this article, we will discuss how to convert a character array to a string
4 min read
Difference between String and Character array in Java Unlike C/C++ Character arrays and Strings are two different things in Java. Both Character Arrays and Strings are a collection of characters but are different in terms of properties. Differences between Strings and Character Arrays:PropertyStringCharacter ArrayDefinitionA sequence of characters is r
3 min read
CharsetDecoder Class in Java For encoding and decoding tasks, many methods are offered in Charset Encoder and Charset Decoder classes in Java. The Charset Decoder class is used for text handling to convert bytes to characters. The Charset decoder accepts a sequence of bytes as its input and displays Unicode characters as output
5 min read
Character.isSpaceChar() method in Java The java.lang.Character.isSpaceChar(char ch) is an inbuilt method in java which determines if the specified character is a Unicode space character. A character is considered to be a space character if and only if it is specified to be a space character by the Unicode Standard. This method returns tr
2 min read
Character.digit() in Java with examples The java.lang.Character.digit() is an inbuilt method in java which returns the numeric value of the character ch in the specified radix. It returns -1 if the radix is not in the range MIN_RADIX or if the value of ch is not a valid digit in the specified radix. A character is a valid digit if at leas
3 min read
Character.charValue() in Java with examples Java.lang.Character.charValue() is a built-in method in Java that returns the value of this character object. This method converts the Character object into its primitive data type char. Syntax: public char charValue() The function does not accepts any parameter. Return Type: This method returns the
2 min read
Convert a String to a List of Characters in Java In Java, to convert a string into a list of characters, we can use several methods depending on the requirements. In this article, we will learn how to convert a string to a list of characters in Java.Example:In this example, we will use the toCharArray() method to convert a String into a character
3 min read
Java CharArrayWriter Class | Set 1 The CharArrayWriter class in Java is part of the java.io package, and it is used to write data into a character array. This class is used when we want to store characters temporarily without dealing with files and other storage. Features of CharArrayWriter Class:,It is used to store characters in me
5 min read
Java CharArrayWriter Class | Set 2 In the Java.io.CharArrayWriter class in Java | Set 1, we have already discussed about which CharArrayWriter class and how it works. In this article, we are going to discuss some more methods of the CharArrayWriter class, which give us strong control over handling character data. Java CharArrayWriter
3 min read
CharMatcher Class | Guava | Java CharMatcher determines a true or false value for any Java char value. This class provides various methods to handle various Java types for char values. Declaration: The declaration for com.google.common.base.CharMatcher is as: @GwtCompatible(emulated = true) public final class CharMatcher extends Ob
3 min read