how to simplify
if ( this.something == false )
this boolean expression ?
Actually I want to ask is what is Simplify Boolean Expression?
You can simply do:
if (!this.something)
You can use boolean variables directly:
Example:
boolean flag = true;
if(flag) {
//do something
}
Use like following since if expression need a boolean value.
if (!this.something) {
//
}
You can use ternary operator for more simplification :
int someVariable = (this.something) ? 0:1;
someVariable will be 1 if this.something is false.
Hope this helps.
To simplify boolean expression is to reduce complexity of this expression, with preserving the meaning.
In your case:
if(!this.something)
has the same meaning but it's a little bit shorter.
To simplify more complex examples you can use truth tables or Karnaugh maps.
Generally the if statement wants to evaluate whatever is within it into a boolean
if
boolean something = true;
if(something == true) evaluates to true
if(something != true) evaluates to false
but you can also do
if(something) evaluates to whatever something is (true in this case)
if(!something) evaluates to opposite what something is (false in this example)
Also you can simplify if statements in certain cases by using a ternary operator:
boolean isSomethingTrue = (something == true) ? true : false;
boolean isSomethingTrue = something ? true : false;
type variable = (condition) ? return this value if condition met : return this value if condition is not met;
Related
What I am trying to perform: I am trying to reduce the conditional operators, Since Sonar is giving a error for it
if (!parseBooleanFromString(response.getBuy().getHasEligibleAccounts()) &&
(!parseBooleanFromString(response.getSell().getHasEligibleAccounts()) &&
(!parseBooleanFromString(response.getExchange().getHasEligibleAccounts()) &&
(!parseBooleanFromString(response.getWorkplaceRetirement().getHasPlansEligibleForChangeContributions()) &&
(!parseBooleanFromString(response.getWorkplaceRetirement().getHasPlansEligibleForChangeInvestments())))))) {
//Success
} else {
//Failure
}
private boolean parseBooleanFromString(String mStr) {
return Boolean.parseBoolean(mStr);
}
What i have tried:
I am trying to put all the boolean values in a list and check
Is that the best way to do or is there a more efficient way
You can also move these conditions into different functions which internally calls other functions and returns single boolean result. This way there will only one function in above if condition which will internally evaluate and returns result.
Since you're checking if each statement is false, how about you keep a global integer in memory: private int product = 1;. Make a separate method where you calculate the product (replaces the string to boolean parser):
private void updateProduct(String mStr){
if (Boolean.parseBoolean(mStr)) //If true, condition should fail
product *= 0;
else
product *= 1;
}
In essence, you are not running 'if statement' but multiplying the boolean:
product = 1;
updateProduct(response.getBuy().getHasEligibleAccounts());
updateProduct(response.getSell().getHasEligibleAccounts());
//etc
if (product > 0){
//success
} else {
//failure
}
Explanation: If at any point a condition was true, the product will always be 0. The only instance where the product is > 0 is when all statements were false
Not sure what sonar complains about, but you have alot of redundant parenthesis and confusing negations. Using DeMorgans law, you can at least simplify to:
boolean b = parseBooleanFromString(response.getBuy().getHasEligibleAccounts())
|| parseBooleanFromString(response.getSell().getHasEligibleAccounts())
|| parseBooleanFromString(response.getExchange().getHasEligibleAccounts())
|| parseBooleanFromString(response.getWorkplaceRetirement().getHasPlansEligibleForChangeContributions())
|| parseBooleanFromString(
response.getWorkplaceRetirement().getHasPlansEligibleForChangeContributions());
if (!b) {
or if you perfer more java 8 syntax
Stream<Boolean> bools = Stream.of(parseBooleanFromString(response.getBuy().getHasEligibleAccounts()),
parseBooleanFromString(response.getSell().getHasEligibleAccounts()),
parseBooleanFromString(response.getExchange().getHasEligibleAccounts()),
parseBooleanFromString(response.getWorkplaceRetirement().getHasPlansEligibleForChangeContributions()),
parseBooleanFromString(response.getWorkplaceRetirement().getHasPlansEligibleForChangeContributions()));
boolean c = ! bools.anyMatch(e -> e);
if (!c) {
I would do something like this:
private boolean checkEligibility(LaunchPoints response) {
final String trueStr = "true";
if (trueStr.equals(response.getBuy().getHasEligibleAccounts())) return true;
if (trueStr.equals(response.getSell().getHasEligibleAccounts())) return true;
[...]
return false;
}
The idea is, skip the parsing boolean, just check for "true" and make your conditions more readable.
This is always very confusing to me. Can someone please explain it? The confusion I have is - boolean default to false. So in the below example, does it enter the if loop when state is not turned on, i.e., it is TURNED OFF if (condition is false) OR does it enter the if loop when state is TURNED ON, in other words if (condition is true)?
boolean turnedOn;
if (turnedOn) {
//do stuff when the condition is false or true?
} else {
//do else of if
}
I know this is a very basic question, but if you could explain the answer in very basic language, that would be great. :) Feel free to point me to duplicate posts that have a very good explanation (I did not find one where I could clearly get it). Also feel free to change the subject of the post if you'd like to make it more generic.
Okay, so..
// As you already stated, you know that a boolean defaults to false.
boolean turnedOn;
if(turnedOn) // Here, you are saying "if turnedOn (is true, that's implicit)
{
//then do this
}
else // if it is NOT true (it is false)
{
//do this
}
Does it make more sense now?
The if statement will evaluate whatever code you put in it that returns a boolean value, and if the evaluation returns true, you enter the first block. Else (if the value is not true, it will be false, because a boolean can either be true or false) it will enter the - yep, you guessed it - the else {} block.
A more verbose example.
If I am asked "are you hungry?", the simple answer is yes (true). or no (false).
boolean isHungry = true; // I am always hungry dammit.
if(isHungry) { // Yes, I am hungry.
// Well, you should go grab a bite to eat then!
} else { // No, not really.
// Ah, good for you. More food for me!
// As if this would ever happen - bad example, sorry. ;)
}
In your example, the IF statement will run when it is state = true meaning the else part will run when state = false.
if(turnedOn == true) is the same as if(turnedOn)
if(turnedOn == false) is the same as if(!turnedOn)
If you have:
boolean turnedOn = false;
Or
boolean turnedOn;
Then
if(turnedOn)
{
}
else
{
// This would run!
}
ABoolean (with a uppercase 'B') is a Boolean object, which if not assigned a value, will default to null. boolean (with a lowercase 'b') is a boolean primitive, which if not assigned a value, will default to false.
Boolean objectBoolean;
boolean primitiveBoolean;
System.out.println(objectBoolean); // will print 'null'
System.out.println(primitiveBoolean); // will print 'false'
Citation
so in your code because boolean with small 'b' is declared it will set to false hence
boolean turnedOn;
if(turnedOn) **meaning true**
{
//do stuff when the condition is false or true?
}
else
{
//do else of if ** itwill do this part bechae it is false
}
the if(turnedon) tests a value if true, you didnt assign a value for turned on making it false, making it do the else statement :)
boolean turnedOn;
if(turnedOn)
{
//do stuff when the condition is true - i.e, turnedOn is true
}
else
{
//do stuff when the condition is false - i.e, turnedOn is false
}
boolean state = "TURNED ON";
is not a Java valid code. boolean can receive only boolean values (true or false) and "TURNED ON"is a String.
EDIT:
now you are talking about a loop and your code does not contain any. your var state is false because the boolean default value and you execute the else clause.
Suppose you want to check a boolean. If true, do something. Else, do something else. You can write:
if(condition==true){
}
else{ //else means this checks for the opposite of what you checked at if
}
instead of that, you can do it simply like:
if(condition){ //this will check if condition is true
}
else{
}
Inversely. If you were to do something if condition was false and do something else if condition was true. Then you would write:
if(condition!=true){ //if(condition=false)
}
else{
}
But following the simple path. We do:
if(!condition){ //it reads out as: if condition is not true. Which means if condition is false right?
}
else{
}
Think about it. You'll get it in no time.
Booleans default value is false only for classes' fields. If within a method, you have to initialize your variable by true or false. Thus for example in your case, you'll have a compilation error.
Moreover, I don't really get the point, but the only way to enter within a if is to evaluate the condition to true.
Assuming state is having a valid boolean value set in your actual code, then the following condition will succeed
if(state)
when state is boolean value is TRUE
If condition checks for the expression whether it is evaluated to TRUE/FALSE. If the expression is simple true then the condition will succeed.
This is how the if behaves.
if(turnedOn) // This turnedOn should be a boolean or you could have a condition here which would give a boolean result.
{
// It will come here if turnedOn is true (i.e) the condition in the "if" evaluates to true
}
else
{
// It will come here if turnedOn is false (i.e) the condition in the "if" evaluates to false
}
The syntax of if block is as below,
if(condition){
// Executes when condition evaluates to true.
}
else{
// Executes when condition evaluates to false.
}
In your case you are directly passing a boolean value so no evaluation is required.
if (turnedOn) {
//do stuff when the condition is false or true?
}
else {
//do else of if
}
It can be written like:
if (turnedOn == true) {
//do stuff when the condition is false or true?
}
else { // turnedOn == false or !turnedOn
//do else of if
}
So if your turnedOn variable is true, if will be called, if is assigned to false, else will be called. boolean values are implicitly assigned to false if you won't assign them explicitly e.q. turnedOn = true
Every time the condition "if (turnedOn)", always refers as "TRUE condition", unless the condition is "if (!turnedOn)" will refer as "FALSE condition".
In other case, if you want to compare two Boolean condition, for example;
Two boolean variable: turnedOn, switchedOn
Let's say current condition;
turnedOn=true
switchedOn=false
"if (turnedOn) || if (switchedOn)" will return TRUE
"if (turnedOn) && if (switchedOn)" will return FALSE
I am trying to evaluate the following from a string
boolean value = evaluate("false || true && true && false || true");
I need to get a boolean value of true for this one.
Any ideas on how to solve this problem in the most efficient way?
String value = ("false || true && true && false || true");
boolean result = false;
for (String conj : value.split("\\|\\|")) {
boolean b = true;
for (String litteral : conj.split("&&"))
b &= Boolean.parseBoolean(litteral.trim());
result |= b;
}
System.out.println(result); // prints true
If the only operators are && and ||, then I think this will work:
static boolean eval(String str) {
String s = str.replaceAll("\\s|\\|\\|false|false\\|\\|", "");
return !s.contains("false") || s.contains("||true");
}
For more complicated expressions, I found this library just for that.
Don't know how efficient it is though.
You'll need a small boolean expressions grammar. A bit of recursive parsing should do the trick.
If you don't know how to write such a parser, you may use JavaCC or something similar.
there are parsergenerators available for which you can define a grammar.
But if you only got || and && as operators and true and false as values you can easily do this by yourself, by implmenting a very simple finite state machine:
1.) Split the string into the tokens
2.) parse the left most value by using Boolean.parseBoolean(token) and safe it's value in some instance variable (your state)
3.) combine your instance variable with the next boolean token using the given operator
4.) Repeat step3 until you finished through the whole string
This seems to work although i havent thorougly tested it :)
public class BooleanFSParser {
private boolean parse(String data) {
String[] tokens=data.split("\\s");
boolean state=Boolean.parseBoolean(tokens[0]);
for (int i=1;i<(tokens.length / 2) + 1;i=i+2){
if (tokens[i].equals("&&")){
state=state && Boolean.parseBoolean(tokens[i+1]);
}else{
state=state || Boolean.parseBoolean(tokens[i+1]);
}
}
return state;
}
public static void main(String[] args) {
BooleanFSParser parser = new BooleanFSParser();
boolean val = parser.parse("true && true || false");
System.out.println(String.valueOf(val));
}
}
thats should give you a cirrectly parsed value, but it will get a bit more complex if you allow brackets for example ;)
have fun and check here for the theory
Finite-state_machine
I did a little search on this but couldn't find anything useful.
The point being that if String value is either "true" or "false" the return value should be true. In every other value it should be false.
I tried these:
String value = "false";
System.out.println("test1: " + Boolean.parseBoolean(value));
System.out.println("test2: " + Boolean.valueOf(value));
System.out.println("test3: " + Boolean.getBoolean(value));
All functions returned false :(
parseBoolean(String) returns true if the String is (case-insensitive) "true", otherwise false
valueOf(String) ditto, returns the canonical Boolean Objects
getBoolean(String) is a red herring; it fetches the System property of the given name and compares that to "true"
There exists no method to test whether a String encodes a Boolean; for all practical effects, any non-"true"-String is "false".
return "true".equals(value) || "false".equals(value);
Apache commons-lang3 has BooleanUtils with a method toBooleanObject:
BooleanUtils.toBooleanObject(String str)
// where:
BooleanUtils.toBooleanObject(null) = null
BooleanUtils.toBooleanObject("true") = Boolean.TRUE
BooleanUtils.toBooleanObject("false") = Boolean.FALSE
BooleanUtils.toBooleanObject("on") = Boolean.TRUE
BooleanUtils.toBooleanObject("ON") = Boolean.TRUE
BooleanUtils.toBooleanObject("off") = Boolean.FALSE
BooleanUtils.toBooleanObject("oFf") = Boolean.FALSE
BooleanUtils.toBooleanObject("blue") = null
if ("true".equals(value) || "false".equals(value)) {
// do something
} else {
// do something else
}
Here's a method you can use to check if a value is a boolean:
boolean isBoolean(String value) {
return value != null && Arrays.stream(new String[]{"true", "false", "1", "0"})
.anyMatch(b -> b.equalsIgnoreCase(value));
}
Examples of using it:
System.out.println(isBoolean(null)); //false
System.out.println(isBoolean("")); //false
System.out.println(isBoolean("true")); //true
System.out.println(isBoolean("fALsE")); //true
System.out.println(isBoolean("asdf")); //false
System.out.println(isBoolean("01truefalse")); //false
The methods you're calling on the Boolean class don't check whether the string contains a valid boolean value, but they return the boolean value that represents the contents of the string: put "true" in string, they return true, put "false" in string, they return false.
You can surely use these methods, however, to check for valid boolean values, as I'd expect them to throw an exception if the string contains "hello" or something not boolean.
Wrap that in a Method ContainsBoolString and you're go.
EDIT
By the way, in C# there are methods like bool Int32.TryParse(string x, out int i) that perform the check whether the content can be parsed and then return the parsed result.
int i;
if (Int32.TryParse("Hello", out i))
// Hello is an int and its value is in i
else
// Hello is not an int
Benchmarks indicate they are way faster than the following:
int i;
try
{
i = Int32.Parse("Hello");
// Hello is an int and its value is in i
}
catch
{
// Hello is not an int
}
Maybe there are similar methods in Java? It's been a while since I've used Java...
Actually, checking for a Boolean type in a String (which is a type) is impossible. Basically you're asking how to do a 'string compare'.
Like others stated. You need to define when you want to return "true" or "false" (under what conditions). Do you want it to be case(in)sensitive? What if the value is null?
I think Boolean.valueOf() is your friend, javadoc says:
Returns a Boolean with a value represented by the specified String. The Boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".
Example: Boolean.valueOf("True") returns true.
Example: Boolean.valueOf("yes") returns false.
Can also do it by regex:
Pattern queryLangPattern = Pattern.compile("true|false", Pattern.CASE_INSENSITIVE);
Matcher matcher = queryLangPattern.matcher(booleanParam);
return matcher.matches();
Yes, but, didn't you parse "false"? If you parse "true", then they return true.
Maybe there's a misunderstanding: the methods don't test, if the String content represents a boolean value, they evaluate the String content to boolean.
String value = "True";
boolean result = value.equalsIgnoreCase("true") ? true : false;
Well for this, also have a look at org.apache.commons.lang.BooleanUtils#toBoolean(java.lang.String), along with many other useful functions.
return value.equals("false") || value.equals("true");
Something you should also take into consideration is character casing...
Instead of:
return value.equals("false") || value.equals("true");
Do this:
return value.equalsIgnoreCase("false") || value.equalsIgnoreCase("true");
I suggest that you take a look at the Java docs for these methods. It appears that you are using them incorrectly. These methods will not tell you if the string is a valid boolean value, but instead they return a boolean, set to true or false, based on the string that you pass in, "true" or "false".
http://www.j2ee.me/javase/6/docs/api/java/lang/Boolean.html
See oracle docs
public static boolean parseBoolean(String s) {
return ((s != null) && s.equalsIgnoreCase("true"));
}
function isBooleanString(val) {
if (val === "true" || val === "false"){
return true
} else {
return false
}
}
isBooleanString("true") // true
isBooleanString("false") // true
isBooleanString("blabla") // false
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;