A primitive data type specifies the size and type of variable values, and it has no additional methods. Show There are eight primitive data types in Java: Data Type Size Description`byte`1 byte Stores whole numbers from -128 to 127`short`2 bytes Stores whole numbers from -32,768 to 32,767`int`4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647`long`8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807`float`4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits`double`8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits`boolean`1 bit Stores true or false values`char`2 bytes Stores a single character/letter or ASCII values In this article, we’ll look at how to convert a string to an array of characters in Java. I'll also briefly explain to you what strings, characters, and arrays are. What is a Character in Java?Characters are primitive datatypes. A character is a single character enclosed inside single quotation marks. It can be a letter, a digit, a punctuation mark, a space or something similar. For example:
What is a String in Java?Strings are objects (reference type). A string is made up of a string of characters. It's anything inside double quotation marks. For example:
What is an Array in Java?Arrays are fundamental data structures which can store fixed number of elements of the same data type in Java. For example, let's declare an array of characters:
Now, we have a basic understanding about what strings, characters, and arrays are. Let's Convert a String to a Character Array1. Use toCharArray() Instance Method
Let's check out an example:
Output: When we convert a string to an array of characters, the length remains the same. Let's check the length of both
0 and
1 :
Output:
We can use various ways to print an array. I used the
2 static method from the
3 utility class. You can read more about the 2. Use charAt() Instance Method
5 is an instance method of the NOTE: a string is zero index based, similar to an array. Let's see how we can convert a string to an array of characters using
5 :
Output: You can read more about the
5 instance method in the . I just showed you another way of converting a string to a character array, but we can use the Please feel free to let me know if you have any suggestions or questions. Photo by Alex Alvarez on Unsplash. Please support freeCodeCamp in their Data Science Curriculum Pledge Drive. Connect with me on Medium. Thank you 😇 Happy Coding ❤️ More on Programming in Java
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started |