Avoid NPE with strings

Report a typo

Your task is to fix the method concatStrings. The method should concat two strings and avoid NPE.

If both of the strings are null, you should return an empty string ("");
If only one string is null, you should return the other string.

Look at the examples:

Sample Input 1:

a
b

Sample Output 1:

ab

Sample Input 2:

a
null

Sample Output 2:

a

Sample Input 3:

null
null

Sample Output 3:

Write a program in Java 17
import java.util.Scanner;


public class Main {

public static String concatStrings(String str1, String str2) {
/* write your code here */

return str1.concat(str2);
}

/* Do not change code below */
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

String str1 = scanner.nextLine();
String str2 = scanner.nextLine();
str1 = "null".equalsIgnoreCase(str1) ? null : str1;
str2 = "null".equalsIgnoreCase(str2) ? null : str2;

System.out.println(concatStrings(str1, str2));
}
}
___

Create a free account to access the full topic