Which of the following is the best way to declare and initialize a char variable?

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.

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 Array

Declaration 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 Array

A 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 Array

To 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 Array

The length of the character array can be determined as follows:

char[] JavaCharArray = {'r', 's', 't', 'u', 'v'}; System.out.println(JavaCharArray.length);

Output:

5

We can even sort char array, let us checkout how,

Sorting A Char Array

To 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 Array

The 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 code

1: 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 Declaration

To 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';
  • The variable-name is the name of the char variable.
  • The value is the value to be assigned to the char variable.

Example 1:

#include <iostream> using namespace std; int main() { char grade = 'B'; cout << "I scored a: "<<grade; return 0; }

Output:

Which of the following is the best way to declare and initialize a char variable?

Here is a screenshot of the code:

Which of the following is the best way to declare and initialize a char variable?

Code Explanation:

  1. Including the iostream header file in our code to use its functions.
  2. Including the std namespace in our code in order to use its classes without calling it.
  3. Calling the main() function. The program logic should be added within the body of this function.
  4. Declare a character variable named grade. The variable has also been assigned a value of B. Notice the value of the variable is enclosed within single quotes.
  5. Print the value of the variable grade alongside other text on the console.
  6. The program must return value upon successful completion.
  7. End of the body of the main() function.

Printing ASCII Value

As 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:

Which of the following is the best way to declare and initialize a char variable?

Here is a screenshot of the code:

Which of the following is the best way to declare and initialize a char variable?

Code Explanation:

  1. Including the iostream header file into our code in order to use its functions.
  2. Including the std namespace into our code in order to use its classes without calling it.
  3. Calling the main() function. The program logic should be added within the body of this function.
  4. Declare a char variable named ch.
  5. Print some text on the console. The text asks the user to enter a value for the variable ch.
  6. Read the user input from the keyboard and store it in the variable ch.
  7. Print some text on the console. The text will include the character you entered for variable ch, the ASCII value of this character, and other text.
  8. The program must return value upon successful completion.
  9. End of the body of the main() function.

Printing Char Value

Given 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:

Which of the following is the best way to declare and initialize a char variable?

Here is a screenshot of the code:

Which of the following is the best way to declare and initialize a char variable?

Code Explanation:

  1. Including the iostream header file into the code. We will then use its functions without getting errors.
  2. Include the std namespace into the code. We will use its classes without calling it.
  3. Calling the main() function. The program logic should go into the body of this function.
  4. Declare three char variables x, y, and z. The three have been assigned integer values of 65, 66, and 67. These will be treated as ASCII values for characters.
  5. Print out the value of variable x on the console. Since x was declared as a char, the char with ASCII value of 65 will be returned, that is, A.
  6. Print out the value of variable y on the console. Since y was declared as a char, the char with ASCII value of 66 will be returned, that is, B.
  7. Print out the value of variable z on the console. Since z was declared as a char, the char with ASCII value of 67 will be returned, that is, C.
  8. The program must return value upon successful completion.
  9. The end of the body of the main() function.

Inputting Chars

We 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:

Which of the following is the best way to declare and initialize a char variable?

Here is a screenshot of the code:

Which of the following is the best way to declare and initialize a char variable?

Code Explanation:

  1. Including the iostream header file in our code to use its functions.
  2. Include the std namespace in our code to use its classes without calling it.
  3. Calling the main() function. The program logic should be added within the body of this function.
  4. Print some text on the console.
  5. Declare a character variable named ch.
  6. Read user input from the keyboard. The input will be stored in the variable ch. Since a user will type a character sequence like abc, only the first character, a, will be stored in variable ch.
  7. Printing the first character entered, its ASCII code and other text on the console. The ASCII code is determined by passing the character variable to the int() function.
  8. Read the next character that was entered by the user. The user won’t be required to enter a new character. It will instead read the second character that was entered, that is, b.
  9. Printing the second character entered, its ASCII code and other text on the console. The ASCII code is determined by passing the character variable to the int() function.
  10. The program must return value upon successful completion.
  11. End of the body of the main() function.

Converting Character to String

There 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 Class

This 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:

Which of the following is the best way to declare and initialize a char variable?

Here is a screenshot of the code:

Which of the following is the best way to declare and initialize a char variable?

Code Explanation:

  1. Including the iostream header file in our code to use its functions.
  2. Include the string header file in our code to use its functions.
  3. Include the std namespace in our code to use its classes without calling it.
  4. Calling the main() function. The program logic should be added within the body of this function.
  5. Convert the character “C” into a 1-length string and assign the resulting string to the variable st.
  6. Print the value of the string st on the console alongside other text.
  7. The program must return value upon successful completion.
  8. End of the body of the main() function.

#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:

Which of the following is the best way to declare and initialize a char variable?

Here is a screenshot of the code:

Which of the following is the best way to declare and initialize a char variable?

Code Explanation:

  1. Include the iostream header file in our code to use its functions.
  2. Include the string header file in our code to use its functions.
  3. Include the std namespace in our code to use its classes without calling it.
  4. Calling the main() function. The program logic should be added within the body of this function.
  5. Create a string variable named st.
  6. Create a character named b with a value of B.
  7. Assign a value of A to the string named st.
  8. Use the += operator to convert characters into a string.
  9. Print the value of the string st on the console alongside other text.
  10. The program must return value upon successful completion.
  11. End of the body of the main() function.

#3: Using std::string Methods

The std::string class comes with many overloaded functions that can help you convert characters into strings.

They include:

  • push_backThis function assigns a particular character to a string’s end. It is overloaded for characters.It takes the following syntax: void push_back(char ch)

    The parameter ch is the character that is to be changed to a string.

  • appendIt assigns many copies of a particular character to a string.The function takes the following syntax: string& append(size_t n,char ch)

    The parameter n denotes the times that the character will be appended.

    The parameter ch is the character to append to string.

  • assign This function replaces the current contents of the string with n copies of the specified character.It takes the following syntax: string& assign(size_t n,char ch);

    The parameter n denotes the total copies for the character.

    The parameter ch is the character to copy into the string.

  • insertThe insert function inserts n copies of a character at the starting position of the string, as specified in the arguments. It takes the following syntax: string& insert(size_t p,size_t n,char ch);

    The p parameter denotes the position from the start where characters will be inserted.

    The parameter n denotes the total copies for the character.

    The parameter ch is the character to be insert in the string.

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:

Which of the following is the best way to declare and initialize a char variable?

Here is a screenshot of the code:

Which of the following is the best way to declare and initialize a char variable?

  1. Include the iostream header file in our code to use its functions.
  2. Include the string header file in our code to use its functions.
  3. Include the std namespace in our code to use its classes without calling it.
  4. Calling the main() function. The program logic should be added within the body of this function.
  5. Create a string variable named st.
  6. Assign the character A to the end of the string.
  7. Print the value of the string st on the console alongside other text. The endl (end line) moves the cursor to the next line.
  8. Set the value of the string st to empty.
  9. Assign single character C to the string named st.
  10. Print the value of the string st on the console alongside other text. The endl (end line) moves the cursor to the next line.
  11. Set the value of the string st to empty.
  12. Replace contents for string st with single character D.
  13. Print the value of the string st on the console alongside other text. The endl (end line) moves the cursor to the next line.
  14. Insert single character E to the string named st from its first index.
  15. Print the value of the string st on the console alongside other text. The endl (end line) moves the cursor to the next line.
  16. The program must return value upon successful completion.
  17. End of the body of the main() function.

#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:

Which of the following is the best way to declare and initialize a char variable?

Here is a screenshot of the code:

Which of the following is the best way to declare and initialize a char variable?

Code Explanation:

  1. Include the iostream header file in our code to use its functions.
  2. Include the string header file in our code to use its functions.
  3. Include the sstream header file in our code to use its functions.
  4. Include the std namespace in our code to use its classes without calling it.
  5. Calling the main() function. The program logic should be added within the body of this function.
  6. Create a string variable named st.
  7. Create a stream variable named myst.
  8. Insert the character A into stream object named myst.
  9. Convert the stream object into a string.
  10. Print the value of the string st on the console alongside other text. The endl (end line) moves the cursor to the next line.
  11. The program must return value upon successful completion.
  12. End of the body of the main() function.

Summary:

  • A char is a C++ data type used for the storage of letters.
  • C++ Char is an integral data type, meaning the value is stored as an integer.
  • It occupies a memory size of 1 byte.
  • C++ Char only stores single character.
  • Char values are interpreted as ASCII characters.
  • ASCII is an acronym for American Standard Code for Information Interchange.
  • It states a specific way of representing English characters in the form of numbers.
  • To see the ASCII value of a character, we pass it to the int() function.
  • To see the corresponding char value of ASCII value, we define the ASCII as a character.