John Smith John Smith - 2 months ago 9
Java Question

Java: IDE indicates that my if else statement is redundant and I need an explanation to why

I am a beginner in programming. The Netbeans IDE is indicating that the following if-else statement is redundant:

public boolean x = false;

private void add_labelMouseClicked(java.awt.event.MouseEvent evt) {

jPanel2.setVisible(x);
if(x==false){
x=true;
}else
x=false;
}


And if I correct this if-else statement using the IDE it turns the code into this:

public boolean x = false;

private void add_labelMouseClicked(java.awt.event.MouseEvent evt) {

jPanel2.setVisible(x);
x = x == false;
}


I need a simple explanation on the second code and how come it has a similar function to the first code.

EDIT: I think I understand it now its kinda looping and a an amazing trick, I learned something new today thanks for all the replies.

Answer
x = x == false;

explanation

if x is False, x == false is true and thus, x becomes true

if x is true, x == false becomes false and thus, x becomes false

x == false is a conditional operator, due to the presence of ==, just like if-condition and returns a value of true or false

== is equality checking conditional operator and is returning a value of true or false, as explained in answer. This returned value gets assigned to x.

You could also use x = !x to write even simple code

Comments