Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Programming Practice Method:public static char[] firstChars(String[] arr) Create

ID: 3738446 • Letter: P

Question

Programming Practice

Method:public static char[] firstChars(String[] arr)

Creates an array containing the first character of each entry in an array of Strings. If arr is null, returns null. Otherwise, it returns an array containing the first letter of each entry in arr. If an entry of arr is null or empty, the corresponding entry in the output should be ?. For example firstChars({"hello","world",null,"lol","","yolo"}) should return ['h','w','?','l','?','y'].

Parameters: arr — The input array.

Returns: An array containing the first character of each entry in arr if arr is not null, or null if arr is null.

Explanation / Answer

FirstCharsTest.java

import java.util.Arrays;

public class FirstCharsTest {

public static void main(String[] args) {

String s[]= {"hello","world",null,"lol","","yolo"};

System.out.println(Arrays.toString(firstChars(s)) );

}

public static char[] firstChars(String[] arr) {

if(arr == null) {

return null;

} else {

char c[] = new char[arr.length];

for(int i=0;i<c.length;i++) {

if(arr[i] == null||arr[i].length()==0) {

c[i]='?';

} else {

c[i]=arr[i].charAt(0);

}

}

return c;

}

}

}

Output:

[h, w, ?, l, ?, y]