0

I am having a confusion here. I have String which I have assigned null to it. So when I concat a String anotherString="abc", it prints "nullabc". But if I try to do the same with a Character, as shown in code, I get a null pointer. I want to understand as to why its happening. I am new to Java and want to understand the nuances of the language.Any help appreciated. Thanks!

String nullString=null;
Character nullCharacter=null;
Character character=new Character('k');
Integer nullInteger=null;

System.out.println(nullString+"abcdefgh");//prints-"nullabcdefgh"
System.out.println(nullCharacter+character);// throws null pointer exception

2 Answers 2

2

The Character class is a wrapper class for the char primitive type, which is a 16-bit number.

If you add two primitive char variables together, it justs adds the numeric values.

    char a = 'a';
    char b = 'b';
    char c = (char)(a+b); // c == 'Ã'

The nullCharacter+character syntax using the Character wrapper object is only possible thanks to auto-unboxing (introduced in Java 1.5). It will implicitly convert it to a numeric addition:

    nullCharacter.charValue() + character.charValue() // throws NPE

On the other hand, adding two strings together nullString+"abcdefgh" is the String concatenation operation which was introduced at the very start of Java, and that operation handles null values differently. In theory it's compiler specific, but most compilers implement it as this:

new StringBuilder()
    .append(nullString)  // implicitly converts null to "null"
    .append("abcdefgh")
    .toString()
Sign up to request clarification or add additional context in comments.

2 Comments

"char c = a+b;" you need a cast in there. Also, it's charValue(), not toCharValue().
understood , didnt know there was auto-unboxing going on in there!
1

Java uses autoboxing (actually, in this case, unboxing) to convert the Character object to a char primitive and it fails since nullCharacter is null.

Autoboxing only affects classes that wrap primitives and so it does not apply to String.

If you convert the not-null Character (named character in your code) to a String, you will not get NullPointerException.

System.out.println(character.toString() + nullCharacter);

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.