5

I'd like to pass a String parameter as "null"

However, this is for the super method in a constructor - so i cannot do

String s = null;
super(s);

I cannot just do

super(null)

as this will result in an ambiguous method call. I don't want to have an instance variable that is null for this either, that seems inelegant.

Is there a way to create a null String?

NB

 new String(null) //does not compile
3
  • 17
    super((String)null) Commented Dec 14, 2012 at 11:42
  • 5
    @AndrewThompson: that should be an answer (as simple as it might look to you). Commented Dec 14, 2012 at 11:45
  • @JBNizet Ehh.. (shrugs) I'm a bit late coming back to this. Now it's been put as an answer by others, it seems redundant. Commented Dec 14, 2012 at 12:05

3 Answers 3

5

Just do this

super((String)null);
Sign up to request clarification or add additional context in comments.

Comments

3

CodeMan posted the correct answer, another solution, move away from null, and consider initializing with Empty string

super("");

this would avoid a null check later.

2 Comments

this is true - there is a null check though, and in case we ever do want to do something with a non-null and empty string i thought i'd stay away from this.
this conversation I like the bug with the string concatenating but i also like the fact null doesn't go on the heap (though being efficient in java seems a bit pointless).
1

The problem you have is that the compiler do not know which constructor should be used.

String has various single parameter constructor.

 String(String)
 String(char value[])
 String(StringBuffer)
 String(StringReader)

When you use String(null), it is unknown which should be used.

Remember when you use a null as argument (in a method or constructor), you should always forward it with cast to desired type.

new String((String) null);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.