-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?

Dominique
  • 1,080
  • 14
  • 29
Asma Zinneera Jabir
  • 801
  • 3
  • 13
  • 31
  • null != roleName instead of rolename.equals(null), because you can not call null.equals – Jens May 05 '17 at 07:12
  • Info goes to `audit`, error goes to `log` in your code. Sure you have two different loggers? – Daniel Alder May 05 '17 at 07: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 May 05 '17 at 07:15
  • `roleName.equals(null)` can *never* return true. Well... not if implemented correctly. – shmosel May 05 '17 at 07:16

2 Answers2

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.

Sezin Karli
  • 2,517
  • 19
  • 24
2

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

Rahul Rabhadiya
  • 430
  • 5
  • 19