Home > Back-end >  How to cast an integer array to a String array without creating separate array of strings and adding
How to cast an integer array to a String array without creating separate array of strings and adding

Time:09-21

int[] locations = {ran1,ran2,ran3};
String positions = locations.toString();

When cast this way, it casts the int[] into a String but not to String[]. I tried casting individual integers ran1, ran2, ran3 into String primitives and then adding them to the different String[] to use in the code, but why an array got cast into only the primitive String but not into an array. Am I using the wrong syntax to cast an entire int[] to String[]? Is there any other method to cast an entire array?

CodePudding user response:

You cannot "cast" a int[] to a String[] (neither can you "cast" an int to a String): what you can and have to do is "convert".

To convert from int to String you can use Integer#toString() method.

To convert an array, there's no built-in method but you can do as suggested in a comment:

IntStream.of(locations).mapToObj(Integer::toString).toArray(String[]::new)

CodePudding user response:

  int arr[]= {1,2,3,4,5,6};
  String x= Arrays.toString(arr);
  • Related