Char Array in Java | Java Character Array

Introduction

Most of the data we process today has characters in it, a programming language will be said flexible if it is familiar to a programmer and provides a way to handle character data.

Char arrays in java are very useful and easy to use, strings are immutable in java but we can manipulate the entries in the char array. Char arrays are faster when compared to lists and sets and even simple than sets and lists.

Let’s explore the working of char arrays now!

Declaration and Initialization

Declaration of a char array is similar to the declaration of a regular array in java. “char[] array_name” or “char array_name[]” are the syntaxes to be followed for declaration.

After declaration, the next thing we need to do is initialization. “array_name = new char[array_length]” is the syntax to be followed. Anyways we can do both declaration and initialization in a single by using “char array_name[] = new char[array_length]” syntax. The length of the array should be declared at the time of initialization in a char array.

public class Test{

    public static void main(String args[]) 

    {

      //declaration-1

      char arr[];

      arr=new char[4];

      //declaration-2

      char arr2[]=new char[4];

      //assigning-1

      char arr1[]=new char[]{a,b,c,d};

      //assigning-2

      arr[0]=a;

      arr[1]=b;

      arr[2]=c;

      arr[3]=d;

      System.out.println(arr);

      System.out.println(arr1);

    } 

}

In the above snippet, declaration-1 and declaration-2 are both ways of declaration and initialization. And assigning-1 and assigning-2 are both ways of pushing entries to an array. Remember that when we print a char array it prints all the characters merged as a string, in the above case output will be “abcd”.

Learn more: Event Handling in Java: What is that and How Does it Work?

Looping over a char array

Looping over a char array is a fun task in java, we can use a regular “for loop” or a “for: each” loop for looping over the array.

//loop-1

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

   System.out.print(arr[i]);

//loop-2

for(char c:arr)

   System.out.print(c);

In the above snippet, loop-1 is a regular for loop and the final output of loop one will be “abcd”. And loop-2 is a for: each loop and the final output of loop-2 will be “abcd”.

Lenght of a character array can be attained using the length attribute. “Array_name.length” is the syntax to be followed.

char array[]=new char[]{h,e,l,l,o};

System.out.println(array.length);

The above snippet prints 5, as expected.

Sorting a Char Array

Arrays in java can be sorted using “Arrays.sort(array_name)”. This will sort the passed character array lexicographically.

char[] array = {h, e, l, l, o};

Arrays.sort(array);

System.out.println(Arrays.toString(array)); //line1

System.out.println(array);  //line2

Note that we need to import java.util.Arrays inorder to get Arrays.sort() and Arrays.toString() worked.

In the above snippet, the char array gets sorted lexicographically and printing the array prints the characters merged as a string. The output of “line2” will be “ehllo” if you don’t the output as a merged string instead you want to print the whole array with square brackets at the ends, then Arrays.toString() does the job. The output of “line1” will be [e, h, l, l, o].

In the previous code snippets, we’ve declared the char arrays by filling the entries in the array, but what if we want to convert a string to a char array?

Anyways we initialize a char array with string length, loop over the string, and append each character into the array will do the job.

String s=hello;

char[] arr=new char[s.length()];

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

  arr[i]=s.charAt(i);

System.out.println(Arrays.toString(arr));

Above snippet will print [h, e, l, l,o] as expected.

The above snippet will do the art of converting a string to a char array, but do we need to write this long code every time we want to convert a string to a char array?. Well, the answer would be NO.

Java provides a beautiful method called toCharArray() which has to be applied on a string and returns the char array.

String s = aejou;

char[] arr = s.toCharArray();

System.out.println(Arrays.toString(arr));  //line1

arr[2]=i;

System.out.println(Arrays.toString(arr));  //line2

As expected, “line1” prints [a, e, j, o, u] as output. And as already discussed, unlike a string we can edit or manipulate the entries of a char array. So the output of the line2 will be [a, e, i, o, u].

Now that we’ve seen a method for converting a string to char array in java, what if we want a vice-versa task?

Never mind java also has a method for doing such tasks.

char[] arr = {h, e, y, , t, h, e, r, e};

String s1 = new String(arr); //method1

System.out.println(s1);

String s2 = String.valueOf(arr); //method2

System.out.println(s2);

In the above snippet, we can see both methods for converting a char array to a string. The output of the above snippet will be “hey there”, as expected.

Also Read: 17 Interesting Java Project Ideas & Topics For Beginners

Conclusion

We came to know what are char arrays, learned various ways of initializing and declaring char arrays. Walked through a snippet for looping over a char array. Sorted a char array using predefined Arrays.sort() method.

And observed a naive and predefined implementation of string to char array conversion, also observed a vice-versa implementation using various methods. Now that you are well versed with the concepts of char arrays, start implementing them!

If you’re interested to learn more about Java, OOPs & full-stack software development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Prepare for a Career of the Future

INDUSTRY TRUSTED LEARNING - INDUSTRY-RECOGNIZED CERTIFICATION.
Learn More

Leave a comment

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

×