Let's look into some widely used conversions.
The code for converting the array of numbers to string will be as follows :
As you can notice in the output that the square brackets are replaced by quotation marks. This indicates that the given array is converted into a string.
The code for converting the array of strings to strings will be as follows :
There is no direct method present to do so. But if we take a closer look at the given scenario, then we will notice that the string contains all the elements of the array, and if we simply combine all the given elements into a single array, then we can get our array back.
Now let's look the code for above scenario :
As you can see integer values are also converted into the string. This is how the split method works, it cannot detect the previous type of string.
Working with Nested Arrays
There might be a situation when we have an array inside an array; such arrays are known as nested arrays. How to convert such an array into a string? toString() flattens the array. Thus all the elements of the array, including the nested array elements, get combined into a single array. And that's how we get the new array having all the elements separated by a comma.
Let's look into the code for this:
In the above example, the toString method flattens the array, and all the elements of the array, including the nested array elements, get combined into a single array.
- We can convert an array of numbers and an array of strings into strings using toString().
- We can also convert the nested array into string using toString().
- And in order to convert the string back to the array, we will use the split() method.