Sonarqube : Boolean literals should not be redundant - java

I have the following nice one liner :
boolean outcome = count > 0 ? false : true;
But from sonaqube I get 'Remove the literal "false" boolean value'
The solution seems to assume you can re-write as a function
But even that function will have that simple one liner and put me in the same position, I don't quite understand how to fix ? Ideas ?

The issue is that you are doing extra gymnastics on an operation that already produces a boolean.
If I write out what you have coded in full syntax:
boolean outcome;
if(count > 0){
outcome = false;
} else {
outcome = true;
}
essentially, you are reversing the count > 0
So try
boolean outcome = !(count > 0)
or even better
boolean outcome = count <= 0

For reference to others I was being dumb and SonarQube correct in reporting the above as it's doing more than needed. Correct code is:
boolean outcome = count > 0;
you do not need the ternary statement the result of count > 0 is a true/false value...
So as stated above to reverse that outcome is simple
boolean outcome = !(count > 0);

Related

what is the meaning and use of line... int ct = count.containsKey(ch) ? count.get(ch) : 0; in the code? [duplicate]

This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 7 years ago.
Two questions about using a question mark "?" and colon ":" operator within the parentheses of a print function: What do they do? Also, does anyone know the standard term for them or where I can find more information on their use? I've read that they are similar to an 'if' 'else' statement.
int row = 10;
int column;
while (row >= 1)
{
column = 1;
while(column <= 10)
{
System.out.print(row % 2 == 1 ? "<" : "\r>");
++column;
}
--row;
System.out.println();
}
This is the ternary conditional operator, which can be used anywhere, not just the print statement. It's sometimes just called "the ternary operator", but it's not the only ternary operator, just the most common one.
Here's a good example from Wikipedia demonstrating how it works:
A traditional if-else construct in C, Java and JavaScript is written:
if (a > b) {
result = x;
} else {
result = y;
}
This can be rewritten as the following statement:
result = a > b ? x : y;
Basically it takes the form:
boolean statement ? true result : false result;
So if the boolean statement is true, you get the first part, and if it's false you get the second one.
Try these if that still doesn't make sense:
System.out.println(true ? "true!" : "false.");
System.out.println(false ? "true!" : "false.");
Thats an if/else statement equilavent to
if(row % 2 == 1){
System.out.print("<");
}else{
System.out.print("\r>");
}
a=1;
b=2;
x=3;
y=4;
answer = a > b ? x : y;
answer=4 since the condition is false it takes y value.
A question mark (?)
. The value to use if the condition is true
A colon (:)
. The value to use if the condition is false
Also just though I'd post the answer to another related question I had,
a = x ? : y;
Is equivalent to:
a = x ? x : y;
If x is false or null then the value of y is taken.
Maybe It can be perfect example for Android,
For example:
void setWaitScreen(boolean set) {
findViewById(R.id.screen_main).setVisibility(
set ? View.GONE : View.VISIBLE);
findViewById(R.id.screen_wait).setVisibility(
set ? View.VISIBLE : View.GONE);
}
They are called the ternary operator since they are the only one in Java.
The difference to the if...else construct is, that they return something, and this something can be anything:
int k = a > b ? 7 : 8;
String s = (foobar.isEmpty ()) ? "empty" : foobar.toString ();
it is a ternary operator and in simple english it states "if row%2 is equal to 1 then return < else return /r"

i want to understand the code that i show for java return statement

This question I found on my class work and I got confused
I haven't tried anything
public static String evenOrOdd(int num) {
return num%2==0?"Even":"Odd";
}
The code runs fine; I just wanna know how it works.
Ternary operator is just like if else statement.
if (num % 2 == 0) {
return "Even";
} else {
return "Odd";
}
If the part before ? mark is true then you will get the result before : .
If false then after :
It is basically an if elsestatement.
If the condition is true, it will return the first option. If not (if it is false), it will return the second:
num%2==0?"Even":"Odd";
If num%2==0then it is Even. If not, then it is Odd.
It is a one-liner to:
if(num%2==0) return "Even";
else return "Odd";
look for ternary operator
above code is short form of
public static String evenOrOdd(int num) {
if(num%2==0){
return "even";
}else{
return "Odd";
}
}
This is called a ternary operator and its logic works as follows
a question ? positive answer : negative answer
or, using more formal terms
boolean expression ? return value for true : return value for false
So, your question is about num % 2 == 0 which means if a remainder for the num divided by two is zero. If this is the case – it's an even number, if not – it's an odd number, and that is why a corresponding string value is returned.

Boolean always returns false possibly due to values not increasing

This method, moreVowels, is intended to be able to count the amount of vowels and consonants in the String entered, and return true if the amount of vowels is greater than the amount of consonants. Sadly this code always returns false, and I cannot understand why. Here is the method stated:
public Boolean moreVowels()
{ vowelCount = 0;
consonantCount = 0;
for(int i = 0; i < word.length(); i++)
{
if ("AEOIUY".contains(word.substring(i,i++)) || "aeoiuy".contains(word.substring(i,i++)))
{
vowelCount++;
}
if ("BCDFGHJKLMNPQRSTVWXZ".contains(word.substring(i,i++)) || "abcdefghijklmnopqrstuvwxyz".contains(word.substring(i,i++)))
{
consonantCount++;
}
}
if (vowelCount > consonantCount)
{
return true;
}
else
{
return false;
}
}
I believe it is always returning false due to the loop not actually increasing the counts, but I'm not quite sure why not. Thank you for reading, I'm sure the answer is something silly that I failed to recognize.
First, you should not use substring(i,i++), but substring(i,i+1). Otherwise, you'll increase i, making your code skip letters.
"abcdefghijklmnopqrstuvwxyz".contains(word.substring(i,i+1)) looks like a mistake. It will cause consonantCount to increase in each loop for every lowercase letter.
If you're only dealing with words (no spaces etc.), then every word is either a consonant or a vowel, so you don't need the second if. You could get consonant count by subtracting vowelCount from length.
Furthermore, if you convert the i-th character to uppercase, you can omit the || "aeoiuy".contains(...) part.
The other answer and comment already show the problems with your code. I just want to add a possible stream based solution that can reduce the possibilty for errors by repacing the index based looping and local variables:
private static boolean moreVowels(String word)
{
return word.chars()
.mapToObj(c -> Character.toString((char) c).toUpperCase())
.mapToInt(c -> "AEIOUY".contains(c) ? 1 : "BCDFGHJKLMNPQRSTVWXZ".contains(c) ? -1 : 0)
.sum() > 0;
}
You can apply the use of toUpperCase() to your own implementation as well to make the if statements a bit shorter (again avoiding possible errors).

Operation to "Get and AND" boolean variable in Java

Is it possible in Java to use syntax like (i++, ++i) for boolean logic operators?
I have a boolean variable that is true only for the first iteration of a foreach loop. That iteration has to be skipeed.
Full syntax is
for (...)
{
if (bool)
{
bool &= false;
continue;
}
}
I wonder if there is any way to shorten the syntax without using AtomicBoolean. For example construct if (bool &= false) is syntactically correct but I think it will compare the final result and not the original value.
Google is not my friend because the search query is misleading
Personally I would simplify your current code to:
for (...)
{
if (bool)
{
bool = false;
continue;
}
// Rest of code
}
... but if you really want to do it in the if condition as a side-effect, you could use:
for (...)
{
if (bool && !(bool = false))
{
continue;
}
// Rest of code
}
Here the first operand of the && operator covers subsequent operations, and !(bool = false) will always evaluate to true and set bool to false.
Another option, from comments:
for (...)
{
if (bool | (bool = false))
{
continue;
}
// Rest of code
}
This performs the assignment on each iteration, but it still gives the right result each time.
I really, really wouldn't use either of these last two options though.
Your code is the usual thing to do. However, there's an alternative:
for (SomeType thing : Iterables.skip(things, 1)) {
// process thing
}
This uses Google Guava's Iterables.skip() method and produces your expected output - a for-each loop iterating over the collection and skipping the first element.
Alternatively, just use an integer variable and use ++ to post-increment it.
int iter = 0;
for (...) {
if (iter++ == 0) {
continue;
}
...
}
If you want to skip the first iteration, this might even be easier to understand.
Don't use increments for boolean types If you must use a boolean, either toggle it, such as !bool, or just set it to false:
for (...){
if (bool) {
bool = false;
continue;
}
}
Ideally, if all you want is to skip the first, last or nth iteration, do not use a boolean at all but an int instead ...
int skipIndex = 0;
for(int index=0; index < 5; index++){
if(index != skipIndex) {
System.out.println(index);
}
}
... or the following to only skip the first iteration:
int[] values = new int[]{0, 1, 2, 3, 4};
for (int index = 1; index < values.length; index++) {
System.out.println(values[index]);
}
If (and only if) you are really so certain that you will always need to continue on the first iteration, why not just skip that iteration? Instead of starting with i=0, start with
for(i=1....
I've been struggling to see why the OP is trying to use bool &= false; when bool = false will obviously do. In that sense, Jon Skeet's answer is (unsurprisingly) correct.
What I think the OP actually wants to do is set the variable to false and test it in one step. That's the reason for the reference to AtomicBoolean. It's nothing per-se to do with loops. IE he wants to do the same as:
int a=0;
for ( ... ) {
if (a++ == 0 ) { // works if we aren't doing too many iterations
continue;
}
...
}
i.e. he wants the equivalent of a post-increment operator.
If I'm right, it's not the loop he's worried about, it's the fact that a here is being read once, then separately read again.
This is a case of premature optimisation. The Java compiler is very likely (no I haven't tested it) to produce a single read and test and of the code with
boolean a=false;
for ( ... ) {
if (!a) {
a = true;
continue;
}
}
as Jon Skeet suggested.
The answer (for completeness) is that there is no post-increment operator that works on boolean and I couldn't work out how to define a function that does that without at least mentioning the variable twice. However, that should not be a design consideration.
Note in a real for loop you can just do:
int i;
boolean skip;
for (i=0, skip=true; i<10; i++, skip=false) {
if (skip)
continue;
}
for (int i = 0, boolean doIt = false; i < 10; i++, doit = true) {
if (doIt) {
doStuff();
}
}

Java boolean not behaving with breakpoints in if statement

Basically, this peice of code seems to behaving differently when I move the breakpoints
int checker = something.length(); /* something is the value of an edittext */
boolean badInput = false;
if(checker == 0)
{
badInput = true;
}
if(checker > 12)
{
badInput = true;
}
*1 if(badInput = false)
{
*2 /* A lot of
code to do
if the
input is GOOD */
}
else
{
/* Alert that the input is BAD */
}
When I enter a 2 digit number into the edittext with the first breakpoint (1), badInput gives false, as it should.
Here is the problem: when I do exactly the same with only the second breakpoint (2), the code goes onto the else statement, and alerts, even though the input is exactly the same.
Anybody know why this might be?
This:
if(badInput = false)
Should be:
if(badInput == false)
Or preferrably:
if (!badInput)
The first is performing an assignment, not a comparison. The overall result of the expression badInput = false is also the value assigned (false) so it will never enter the body of that if.
It's not really clear what you mean by entering data "with" a breakpoint, but fundamentally the problem is in your code.
You should have:
if(!badInput)
or
if(badInput==false)
(the first one is better)
Simple typo error,
if(badInput = false)
should be
if(badInput == false)
you want a compare not assign.
What you check boolean variable with == operator ?!!
You have to check as following :
if(!badInput) //for false value
or
if(badInput) //for true value

Categories