Monday, 5 June 2017

Can I pass null to append method of StringBuilder?

No, you can’t pass null as an argument to append method of StringBuilder. Let’s try to pass null argument and see what will happen.

Test.java
public class Test {
 public static void main(String args[]){
  StringBuilder builder = new StringBuilder();
  
  builder.append("First Name").append(null);
  
 }
}

Try to compile Test.java, you will end up in following error.
$javac Test.java
Test.java:5: error: reference to append is ambiguous
                builder.append("First Name").append(null);
                                            ^
  both method append(CharSequence) in StringBuilder and method append(char[]) in StringBuilder match
1 error

As you observe the error message, Java compiler is unable to get the proper append method that takes null argument, it is because append is overloaded in many forms, when you call the method append with null argument, it don’t know which one to call. One way to solve this problem is type cast the null to specific type.

builder.append("First Name").append((String)null);


Test.java
public class Test {
 public static void main(String args[]){
  StringBuilder builder = new StringBuilder();
  
  builder.append("First Name").append((String)null);
  
 }
}


No comments:

Post a Comment