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
CodePudding user response:
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);
CodePudding user response:
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()