-1

I want to initialize a String variable and later assign a value to it using

if (){} else if(){} 

This is what I have done:

    String roleName;

    // A and B are string constants
    if (userRoleslist.contains(A)) {
           roleName = A;
    } else if (userRoleslist.contains(B)) {
                roleName = B;
    }
    if (!roleName.equals(null)) {
           audit.info("User: " + userName + " successfully authorized as " +
                        roleName + " to perform JMX operations.");

           return roleName;
     } else {
           String msg = "User: " + userName + " not authorized to perform JMX operations.";
           log.error(msg);
           throw new NullPointerException();
     }

The problem is that the error is not logged to the console. Only the NullPointerException is thrown and point the line if

(!roleName.equals(null)) {

Also, additionally can I leave out the NullPointerException and a log.error only?

4
  • null != roleName instead of rolename.equals(null), because you can not call null.equals
    – Jens
    Commented May 5, 2017 at 7:12
  • Info goes to audit, error goes to log in your code. Sure you have two different loggers? Commented May 5, 2017 at 7:13
  • 1
    @Jens: Well, roleName != null. The "null first in conditions" is pretty outdated, pointless in Java and widely regarded as less readable.
    – Jon Skeet
    Commented May 5, 2017 at 7:15
  • roleName.equals(null) can never return true. Well... not if implemented correctly.
    – shmosel
    Commented May 5, 2017 at 7:16

2 Answers 2

4
if (!roleName.equals(null)) {

must be

if (roleName != null) {

When you do a null check you should do like this. As roleName is null, calling a method on it will give you a null pointer exception.

2

roleName.equals(null) will give you nullpointer exception instead use roleName!=null .

Not the answer you're looking for? Browse other questions tagged or ask your own question.