-1

I'm trying to use String.valueOf() to replace the null when i'm calling some method.But it still shows nullpointerexception. This may be simple but i'm missing something.

I have statement like this

myvar = this.kind.name().toLowerCase()   

It is throwing java.lang.NullPointerException. Im trying to keep string "NULL" whenever i get NPE. so i tried this

myvar = String.valueOf(this.kind.name().toLowerCase()) -- not working

I have found from other posts that it may not work as we have overloaded method String.valueOf(char[]) and String.valueOf(object) and suggested to use below. But still it s not working. How do i assign string null in this case?

myvar = String.valueOf((this.kind.name().toLowerCase()) null))
Arun Palanisamy
  • 5,281
  • 6
  • 28
  • 53

2 Answers2

10

You should be using

myvar = String.valueOf(this.kind.name()).toLowerCase();

not

myvar = String.valueOf(this.kind.name().toLowerCase());

As documentation of valueOf() describes

if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned

So,String.valueOf(this.kind.name()) would return "null"

Ashishkumar Singh
  • 3,580
  • 1
  • 23
  • 41
4

If this.kind is null, you should be able to determine that from the stacktrace.

You can handle the situation by adding an if-condition or code like

String.valueOf(this.kind == null ? null : this.kind.name()).toLowercase()
rsp
  • 23,135
  • 6
  • 55
  • 69