Sunday 5 January 2020

How to convert char[] to Character[] in Java?


Traverse through the array and convert.
public static Character[] getBoxedArray(char[] arr) {
 if (arr == null)
  return null;

 Character[] result = new Character[arr.length];
 int index = 0;
 for (char i : arr) {
  result[index] = Character.valueOf(i);
  index++;
 }
 return result;
}


App.java
package com.sample.app;

public class App {

 private static void printElements(Character[] arr) {
  for (Character i : arr) {
   System.out.print(i + " ");
  }
  System.out.println();
 }

 public static Character[] getBoxedArray(char[] arr) {
  if (arr == null)
   return null;

  Character[] result = new Character[arr.length];
  int index = 0;
  for (char i : arr) {
   result[index] = Character.valueOf(i);
   index++;
  }
  return result;
 }

 public static void main(String args[]) {
  char[] arr = { 'a', 'e', 'i', 'o', 'u' };

  Character[] result1 = getBoxedArray(arr);

  printElements(result1);

 }

}

Output
a e i o u


You may like

No comments:

Post a Comment