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!
Check out our free courses to get an edge over the competition.
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.
Check out upGrad’s Advanced Certification in DevOps
Explore Our Software Development Free Courses
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”.
upGrad’s Exclusive Software and Tech Webinar for you –
SAAS Business – What is So Different?
Check out upGrad’s Advanced Certification in Cyber Security
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.
Explore our Popular Software Engineering Courses
char array[]=new char[]{‘h‘,‘e‘,‘l‘,‘l‘,‘o‘};
System.out.println(array.length); |
The above snippet prints 5, as expected.
Enroll in Software Engineering Courses from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
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.
In-Demand Software Development Skills
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
Read our Popular Articles related to Software Development
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 Executive PG Program 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.
Why do people use character arrays?
An array is a data structure in computer science that allows components of the same data type to be indexed and accessed using integer indexes. An array is a group of data elements, each of which is identified by an index. The position of the data item in the array is indicated by an index, which is an integer number. A character array is a collection of characters, each of which has a unique number assigned to it. A character array is similar to a string, but it can be any length, whereas a string is confined to a set amount of characters. They are simple to use. They can also store a lot of information.
Which is the most used loop in codes? Why?
The for loop is the most commonly used loop in programming. The for loop is a control flow statement in the C programming language that allows you to run a block of code a set number of times. The syntax for the for loop is for(initialization; condition; increment). The initialization statement is executed first, and it sets the value of the loop control variable to its default value. After that, the condition statement is checked, and if it is true, the code in the block is run. The increment line is then executed, incrementing the loop control variable by the desired amount. After that, the loop continues until the condition statement evaluates to false. When you need to cycle through a list of items or repeat a set of code a specific number of times, you'll want to use a for loop.
How do I choose the best course for me to learn?
The best course for you depends on your learning style, your objectives, and your budget. You should also think about the type of learning environment you prefer. Smaller classes appeal to certain people, but more engagement with the lecturer appeals to others. Some people like to study independently, while others want more guidance. You may start narrowing down your options once you've studied all of these aspects. To gain an understanding of what each course covers, start by glancing at the course descriptions online. Then you may compare the several institutions that offer the courses to find which one best suits your needs.