A good programming language should be adept to handle all data types. Lot of the data processed these days, also has characters in it. Java which is one of the best programming languages makes use of char array to hold data. In this article we would exploring everything that is there to know about them. Show
Following pointers will be discussed in this article, Let us start with a quick introduction to Char array, Char Arrays are highly advantageous. It is a noted fact that Strings are immutable i.e. their internal state cannot be changed after creation. However, with char arrays, character buffers can be manipulated. While the data structures List and Set are also acceptable, arrays prove to be simplistic and efficient. Furthermore, Char arrays are faster, as data can be manipulated without any allocations. Let us start this article on Char Array In Java, by understanding how to declare arrays in Java. though start with Java installation. If you don’t have it. Declaring Char ArrayDeclaration of a char array can be done by using square brackets: char[] JavaCharArray;The square brackets can be placed at the end as well. char JavaCharArray[];The next step is to initialize these arrays Initializing Char ArrayA char array can be initialized by conferring to it a default size. char[] JavaCharArray = new char[4];This assigns to it an instance with size 4. We use the following code to assign values to our char array: char[] JavaCharArray = new char[5]; JavaCharArray[0] = 'r'; JavaCharArray[1] = 's'; JavaCharArray[2] = 't'; JavaCharArray[3] = 'u';Loops play a very important role when it comes to avoiding repetitive code, this is the next bit of this Char Array in Java article, Loops In Char ArrayTo iterate through every value present in the array, we make use of for loop. char[] JavaCharArray = {'r', 's', 't', 'u', 'v'}; for (char c:JavaCharArray) { System.out.println(c); }Output: r s t u v We can also implement the following method: char[] JavaCharArray = {'r', 's', 't', 'u', 'v'}; for (int i=0; i<JavaCharArray.length; i++) { System.out.println(JavaCharArray[i]); }This produces the same output as the previous code. Let us see how to find out the length of Char Array Length Of Char ArrayThe length of the character array can be determined as follows: Output: 5 We can even sort char array, let us checkout how, Sorting A Char ArrayTo sort the arrays, we can implement Arrays.sort() as shown below: char[] JavaCharArray = {'r', 't', 'u', 's', 'v'}; Arrays.sort(JavaCharArray); System.out.println(Arrays.toString(JavaCharArray));Ouput: [r, s, t, u, v] The final bit of this Char Array in Java will talk about following pointers, Converting A String Array Into Char ArrayThe following code converts a string into a char array. public class Main { public static void main(String[] args) { String value = "hello"; //Convert string to a char array. char[] array = value.toCharArray(); array[0] = 'j'; //Loop over chars in the array. for(char c : array) { System.out.println(c); } } }Output: j e l l o While Strings are usually preferred, char arrays grant to us an efficient approach. Thus we have come to an end of this article on ‘Char Array in Java’. If you wish to learn more, check out the Java Certification Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring. If you’re just beginning, then watch at this Java Tutorial to Understand the Fundamental Java Concepts. Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible or you can also join our Java Training in Riyadh.
You can only initialize a variable when you define it. For instance char ch = 'a';defines ch as a char and initializes it with the character literal 'a'. If you had char ch; //... ch = 'a';then you are no longer initializing ch but instead you are assigning to it. Until you reach ch = 'a'; ch has some unspecified value1 and using its value before you reach ch = 'a'; would be undefined behavior. Ideally you should always initialize a variable so it has a known state and since you can declare a variable at any point you can hold off on declaring the variable until you know what you are going to initialize it or when you are going to set it immediately. Example //some code // oh, I need to get a char from the user std::cout << "Yo, user, give me a character: "; char ch; // no initialization but it is okay as I set it immediately in the next line cin >> ch; // now ch has a value // more code1: There are places will it will be initialized for you. For instance, if ch was declared in the global scope then it would be zero initialized for you
Char is a C++ data type designed for the storage of letters. Char is an abbreviation for an alphanumeric character. It is an integral data type, meaning the value is stored as an integer. A char takes a memory size of 1 byte. It also stores a single character. In this C++ tutorial, you will learn: What is ASCII?The char value is interpreted as an ASCII character. This is similar to how Boolean values are interpreted as being true or false. ASCII is an acronym for American Standard Code for Information Interchange. It defines a specific way of representing English characters as numbers. The numbers range between 0 and 127. For example, the character ‘a’ is equivalent to ASCII code 97. Char DeclarationTo declare a char variable in C++, we use the char keyword. This should be followed by the name of the variable. The variable can be initialized at the time of the declaration. The value of the variable should be enclosed within single quotes. Syntax:Here is the syntax for char declaration in C++: char variable-name;The variable-name is the name to be assigned to the variable. If a value is to be assigned at the time of declaration, you can use this syntax: char variable-name = 'value';
Example 1:#include <iostream> using namespace std; int main() { char grade = 'B'; cout << "I scored a: "<<grade; return 0; }Output: Here is a screenshot of the code: Code Explanation:
Printing ASCII ValueAs stated above, each character is interpreted as ASCII character. It’s possible for you to get the ASCII value of any character. You simply pass the character to the int() function. This process is called type casting. Let’s demonstrate this: Example 2:#include <iostream> using namespace std; int main() { char ch; cout << "Enter any character: "; cin >> ch; cout << "The ASCII Value of " << ch << " is " << int(ch); return 0; }Output: Here is a screenshot of the code: Code Explanation:
Printing Char ValueGiven an ASCII value, the C++ compiler can return the corresponding character. You declare a char variable and assign it an integer value. It will be converted to the corresponding character value. Example 3:#include <iostream> using namespace std; int main() { char x = 64, y = 66, z = 71; cout << x; cout << y; cout << z; return 0; }Output: Here is a screenshot of the code: Code Explanation:
Inputting CharsWe can use the std::cin function to read a char entered by the user via the keyboard. The std::cin will allow you to enter many characters. However, the character variable can hold only one character. This means only the first character entered will be extracted and stored in the character variable. The rest will remain in the buffer used by std::cin. To extract it, make subsequent calls to the std::cin. Example 4:#include <iostream> using namespace std; int main() { cout << "Type a sequence of characters: "; char ch; cin >> ch; cout <<"The ASCII code of "<< ch << " is "<< int(ch) << '\n'; cin >> ch; cout <<"The ASCII code of " << ch << " is "<< int(ch) << '\n'; return 0; }Output: Here is a screenshot of the code: Code Explanation:
Converting Character to StringThere exist a number of ways that we can use to convert characters to strings. Let’s discuss them: #1: Using Constructor given by a String ClassThis can be done using the following syntax: string st(int n,char x);The parameter n denotes the size of the string that is to be generated. The parameter x is the character to convert to a string. The function returns a string. Example 5:#include<iostream> #include <string> using namespace std; int main() { string st(1, 'C'); cout << "The resulting string is : " << st; return 0; }Output: Here is a screenshot of the code: Code Explanation:
#2) Using the std::string Operators = and +=The = and += operators are already overloaded with characters. The two can be used to convert a particular character to a string. Example 6:#include<iostream> #include <string> using namespace std; int main() { string st; char b = 'B'; st = 'A'; st += b; cout << "The resulting string is : " << st; return 0; }Output: Here is a screenshot of the code: Code Explanation:
#3: Using std::string MethodsThe std::string class comes with many overloaded functions that can help you convert characters into strings. They include:
Example 7:#include<iostream> #include <string> using namespace std; int main() { string st; st.push_back('A'); cout << "push_back A returns : " << st << endl; st = ""; st.append(1, 'C'); cout << "append C returns : " << st << endl; st = ""; st.assign(1, 'D'); cout << "assign D returns : " << st << endl; st.insert(0, 1, 'E'); cout << "insert single character returns : " << st << endl; return 0; }Output: Here is a screenshot of the code:
#4: Using std::stringstream To use this class to convert character to a string, insert the character into stream. They’ll be written to the string. Example 8:#include<iostream> #include <string> #include <sstream> using namespace std; int main() { string st; stringstream myst; myst << 'A'; myst >> st; cout << "The conversion of the single character returns the string: " << st; return 0; }Output: Here is a screenshot of the code: Code Explanation:
Summary:
|