Java - How to assign variables within evaluations? [duplicate] - java

This question already has answers here:
Is there a post-assignment operator for a boolean?
(3 answers)
Closed 5 years ago.
I'm trying to make a Java method close() which closes object if it is open, and which returns true if the action succeeded.
public boolean close() {
if (open) {
open = false;
return true;
} else {
return false;
}
}
I'm trying to find a way to write this down with less code. What I came up with is the following.
public boolean close() {
return (open && (open = false));
}
Eclipse doesn't give any errors when I write this down. The left hand side of the evaluation checks if open is true, and if so, the right hand side should set open to false and return true as well.
I've tested the code, and open does get set to false, but it doesn't return true. Is there a way to make this work?

Perhaps something like:
public boolean close () {
return open != (open = false);
}
but if I was reviewing this code I would reject it as unclear.
I would probably do it using maximal clarity as:
public boolean close () {
boolean wasOpen = open;
open = false;
return wasOpen;
}
and let the compiler optimise.

You could do it without conditional execution by preparing the return value before the assignment of false, like this:
boolean wasOpen = open;
open = false;
return wasOpen;

return open ? !(open = false) : open;
or
return open ? !(open = false) : false;
Though, I don't like the idea of making the first snippet shorter. You are killing readability where it's already absent.
Personally, I would go with the original method introducing a local variable wasOpen as #dasblinkenlight suggested.

Not really, the assignment is evaluated prior to the rest of the expression, so what you're essentially saying is:
true && false
Also known as false

Your expression will evaluated as the following true && false,so the result is false
public boolean close() {
if(!open) return open;
open=false;
return true;
}

You can try this
public boolean close()
{ return !open = (open == true) ? false: true; }

Related

How to catch Boolean returned value of a method from another method and do some operations?

I have two methods in the same class.
public Boolean pinValidation(Obj 1, Obj 2){
// Here i have to return Boolean true or false
boolean status = false;
/..... Some Code segments goes here ..
return true;
}
public Payment checkPayment(Obj 1, Obj2){
pinValidation();
// Here if the return value of first method true
if(status == true){
//set of instructions
}
}
What i want to how to catch above return boolean values and do the operation?
any help?
You could do something like:
boolean status = pinValidation();
Or you could simplify by using:
if (pinValidation()) {
//set of instructions
}
Note: use boolean everywhere. No need to mix boolean and Boolean.
First at all, you need to be aware on how to manage conditionals, so let me add some of code about conditionals:
if (true) { //if the condition is true, the code below will be executed
// code to execute here
}
Then you don't need to evaluate someBooleanValue == true simply you need to call it.
if (pinValidation()) {
// code to execute here
}
Second, you need to know differences between Boolean that is an Object which will help you with some methods and boolean that is primitive type and saves a lot of memory then you can use what one is better based on your problem.

Lock a boolean method (How to return nothing from a boolean method or discard)

I have a private boolean status; field.
I'm trying to lock a class methods in this way:
status == true means class is locked and status == false means class is unlock
if the class has been locked so methods cant invoke like:
protected void flip ()
{
if (locked()) return;
face = (int) (Math.random() * 2);
}
To understand the problem, consider this:
protected boolean isHeads ()
{
//if(!locked()) return false or true;
//if I write upper command then its true or false like the bottom command and its unclear that this false or true is for which of them
//if(!locked())
//if i write this command then i have to write another return and its the same problem too;
return (face == HEADS);
}
P.S: I have an interface so I can't change the method about locked() and lock and etc;
The correct design for such kind of programming is to throw an exception, so the code should be something like this:
protected boolean isHeads () throws ObjectIsLockedException
{
if(locked()) throw new ObjectIsLockedException();
return (face == HEADS);
}
Note that ObjectIsLockedExpception is not a Java exception: you have to declare it as a class in your code.
You can't return nothing from a boolean method. It has to be true or false. Return an int or enum or make the function wait.

A lock has an incorrect combination but since it was originally open it remains open

Where I'm running in to problems is when a lock is already open, then pretty much an incorrect combination won't make a difference because it will remain open. This seemed easy when I read it and tried it, but the test case isn't passing. I marked the bit of code I created that isn't passing with a comment. Can someone help me figure out why it isn't working?
public void open(Combination opening){
Lock temp = new Lock(upper, opening);
if(opening.equals(unlock)){
cl = true;
}else {
//this if statement is what I came up with to find if it is open
if(temp.isOpen() == true){
cl = true;
}
cl = false;
}
}
public boolean isOpen() {
boolean op = true;
if(cl == false){
op = false;
}
return op;
}
public void close() {
cl = false;
}
There are several stylistic issues here, but I think the problem may lie with your temp Lock
if(temp.isOpen() == true){
I don't see why you need the temporary lock
public void open(Combination opening){
// If the combination is right open the lock
// if it was already open no change
if(opening.equals(unlock)){
opcl = true;
}
// no else, if combination was wrong
// leave the status as it was
}
Now as a stylistic issue the way you treat booleans is very bad. Never write
if ( bvalue == true )
just write
if ( bvlaue )
That's the whole point of booleans, they are true or false.
Hence your check is far more complex than needed, this is all you need.
// The method isOpen, which returns a
// boolean indicating whether the lock is opened or not.
public boolean isOpen() {
return opcl;
}
opcl's job is to hold the state of the lock, it's true or false, so just return that.

Error with return in Java?

I get an error in the code from this part of my code:
public boolean findCustomer(String inPersonalNumber){
// check if personal number already exist
for (int i=0; i<customerList.size();i++) {
if(customerList.get(i).getCustomerPersonalNumber().equals(inPersonalNumber)){
return true;
}
}
return true;
}
When I remove the first return true and instead to the last return true, it don't get the error in my eclipse code, but why can't I have the first place and would this be the same? Thanks!
EDIT: The error message from eclipse say: This method must return a result of type boolean. I'm confused because isn't that what I have done?!
Yes, a break must be in the code
Can I write the method in some other way?
EDIT NUMBER 2
Why isn't this code working?
public boolean findCustomer(String inPersonalNumber){
// check if personal number already exist
for (int i=0; i<customerList.size();i++) {
if(customerList.get(i).getCustomerPersonalNumber().equals(inPersonalNumber)){
return true;
}
else {
return false;
}
}
}
This method returns a boolean value so I don't understand why I get an error!? The code looks right to me?
Your edit #2 doesn't compile because there is a possibility that your code won't enter the for-loop. This will be the case if customerList.size() is 0. To fix this, you'll simply need to add a return statement after the for-loop as well:
// check if personal number already exist
for (int i=0; i<customerList.size();i++) {
if(customerList.get(i).getCustomerPersonalNumber().equals(inPersonalNumber)){
return true;
}
else {
return false;
}
}
return false;
Another point here is that this code doesn't logically make much sense: it will only return true or false based on the first item in your list. And this is probably not what you want. So take a closer look at several of the other answer here, many of which are good examples for how you can do this.
public boolean findCustomer(String inPersonalNumber){
boolean result = false;
// check if personal number already exist
for (int i=0; i<customerList.size();i++) {
if(customerList.get(i).getCustomerPersonalNumber().equals(inPersonalNumber)){
result = true;
break;
}
}
return result ;
}
When I remove the first return true and instead to the last return
true, it don't get the error in my eclipse code, but why can't I have
the first place and would this be the same?
If you remove the second return statement the code would be able to run and not return a value - this is not possible as you defined the method to have a return type of Boolean. So it must always return a value no matter what.
Just change the second return statement to false, should do what you want.
Looks like you have turned off the Build Automatically feature of eclipse. It maybe complaining about an error that used to be present when you still hadn't typed in your code fully! This can also happen if you have back-dated your system for some reason.
Also, shouldn't you be returning false if the condition doesn't satisfy?
public boolean findCustomer(String inPersonalNumber) {
// check if personal number already exist
for (int i = 0; i < customerList.size(); i++) {
if (customerList.get(i).getCustomerPersonalNumber().equals(inPersonalNumber)) {
return true;
}
}
return false;
}
First return will return only in case of all conditions satisfied, but this method should be returning boolean as per code. It would be expecting a return in failure case also.
Removing first return won't affect compilation as it has a return in second place which will work without any condtions.
Edit : Answer for your second question
This code has two return's, but what if your customerList is size 0, in that case also, method must return boolean. right? for that only, compiler is asking.
BTW, code doesn't have null checks.
Your final code could be this. Keeping multiple return statements in code in not a good practice.
public boolean findCustomer(String inPersonalNumber) {
boolean retVal = false;
if (!(inPersonalNumber == null || inPersonalNumber.trim().equals("")
|| customerList == null || customerList.size() == 0)) { // inputs are valid to run this check
// check if personal number already exist
for (int i = 0; i < customerList.size(); i++) {
if (inPersonalNumber.equals(customerList.get(i).getCustomerPersonalNumber()) { // to avoid NPE, kept inPersonalNumber in check
retVal = true;
break;
}
}
}
return retVal;
}
Because your for loop looses meaning if you're returning true anyway.
If you want to stop loop use break; instead of first return.

Cleanest way to toggle a boolean variable in Java?

Is there a better way to negate a boolean in Java than a simple if-else?
if (theBoolean) {
theBoolean = false;
} else {
theBoolean = true;
}
theBoolean = !theBoolean;
theBoolean ^= true;
Fewer keystrokes if your variable is longer than four letters
Edit: code tends to return useful results when used as Google search terms. The code above doesn't. For those who need it, it's bitwise XOR as described here.
There are several
The "obvious" way (for most people)
theBoolean = !theBoolean;
The "shortest" way (most of the time)
theBoolean ^= true;
The "most visual" way (most uncertainly)
theBoolean = theBoolean ? false : true;
Extra: Toggle and use in a method call
theMethod( theBoolean ^= true );
Since the assignment operator always returns what has been assigned, this will toggle the value via the bitwise operator, and then return the newly assigned value to be used in the method call.
This answer came up when searching for "java invert boolean function". The example below will prevent certain static analysis tools from failing builds due to branching logic. This is useful if you need to invert a boolean and haven't built out comprehensive unit tests ;)
Boolean.valueOf(aBool).equals(false)
or alternatively:
Boolean.FALSE.equals(aBool)
or
Boolean.FALSE::equals
If you use Boolean NULL values and consider them false, try this:
static public boolean toggle(Boolean aBoolean) {
if (aBoolean == null) return true;
else return !aBoolean;
}
If you are not handing Boolean NULL values, try this:
static public boolean toggle(boolean aBoolean) {
return !aBoolean;
}
These are the cleanest because they show the intent in the method signature, are easier to read compared to the ! operator, and can be easily debugged.
Usage
boolean bTrue = true
boolean bFalse = false
boolean bNull = null
toggle(bTrue) // == false
toggle(bFalse) // == true
toggle(bNull) // == true
Of course, if you use Groovy or a language that allows extension methods, you can register an extension and simply do:
Boolean b = false
b = b.toggle() // == true
The class BooleanUtils supportes the negation of a boolean. You find this class in commons-lang:commons-lang
BooleanUtils.negate(theBoolean)
Boolean original = null; // = Boolean.FALSE; // = Boolean.TRUE;
Boolean inverse = original == null ? null : !original;
If you're not doing anything particularly professional you can always use a Util class. Ex, a util class from a project for a class.
public class Util {
public Util() {}
public boolean flip(boolean bool) { return !bool; }
public void sop(String str) { System.out.println(str); }
}
then just create a Util object
Util u = new Util();
and have something for the return System.out.println( u.flip(bool) );
If you're gonna end up using the same thing over and over, use a method, and especially if it's across projects, make a Util class. Dunno what the industry standard is however. (Experienced programmers feel free to correct me)
Before:
boolean result = isresult();
if (result) {
result = false;
} else {
result = true;
}
After:
boolean result = isresult();
result ^= true;

Categories