简体   繁体   中英

Compare Long in java facing some issues

Following is my code to compare the Long values (I am sure this might irritate some one )

Long userRole = new Long(-1);

    userRole = 8;

    if ( userRole !=8 || userRole != 7)

                    {               
                        showSave = false;
                        request.setAttribute("VIEW", "N");
                    }

if ( userRole == 8 || userRole == 7) // this fails

all the cases becomes success.. :(

what i want to do is if the userRole is not equal to 8 and 7 then set the follwoing

showSave = false;
request.setAttribute("VIEW", "N");

i really dont get what is the mistake i make here.

thanks

First of all this is not compile.

Long userRole = new Long(-1);
userRole = 8; // can't assign int to Long

You can change this to

serRole = (long) 8;

Or

userRole = 8L;

Then come to other part.

 Long userRole = new Long(-1);
 userRole = 9L;
 boolean showSave=true;
 if (userRole != 8&&userRole!=7) { // userRole is not equal to 8 and 7 then
     showSave = false;
 }
 System.out.println(showSave);

You should use && not ||

Out put:

 false

First of All, You cannot assign int values to Long variables directly. To do so, then you need to type cast to Long type or need to add 'L' symbol to int literal. Find the modified code below

serRole = (long) 8; or serRole = 8L;

Your question is " if the userRole is not equal to 8 and 7". We have to write the "userRole is not equal to 8 and 7" in java as (userRole != 8 && userRole != 7).

'&&' represents "And"

'||' represents "Or".

So, working functionality of your code is as follows,

Long userRole = new Long(-1);

userRole = 8L;

boolean showSave=true;

if (userRole != 8&&userRole!=7) {

 showSave = false;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM