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
Related
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.
I am new to programming. I have difficulties understanding this bit of code:
public static boolean onCampus(String name)
{
boolean invalidResponse = true;
do{
System.out.println("Is "+name+ " living on campus? (yes/no)");
String response = in.nextLine();
if(response.equalsIgnoreCase("yes"))
return true;
else if (response.equalsIgnoreCase("no"))
return false;
else
System.out.println("Invalid response.");
} while(invalidResponse);
return false;
}
What I don't get is where is invalidResponse assigned false in case the user enter an acceptable response? And what is that last return false;? Why is it after the do-while statement?
This is somewhat of an anti-pattern - the loop is infinite, and will never terminate "properly". Instead, once you get a valid response, you'll simply call return, and exit the method, thus terminating the loop.
The return false after the loop is a compilation limitation. In java, if the method returns a value, every conceivable branch must contain a return statement (or a throw statement, to be precise). In compile time, Java doesn't "know" that the loop may never be terminated, so it forces you to have a return statement in that branch (i.e., assuming the loop terminates without the if or else if branches being executed).
The last "return false;" is just there so that the compiler will not complain, it is unreachable code. Because your return type is boolean, your code must return true or false for all cases. "invalidResponse" is never assigned to false so your loop will run infinitely until the user enters either yes or no in which case it returns the boolean and exits the function.
Assuming in represents a static Scanner variable.
The loop is intentionally infinite; invalidResponse will never be set false.
Instead, the return lines are the ways out of the loop, assuming the value of "yes" or "no" is entered.
The final return false; is necessary for compilation purposes, but will never be reached.
Of note, however, I'm a fan of a single return, using constants as the first half of an equals, and removing case sensitivity once, and would re-code this as:
public static boolean onCampus(String name) {
boolean response = false;
do {
System.out.println("Is " + name + " living on campus? (yes/no)");
String input = in.nextLine().toLowerCase();
response = "yes".equals(input);
if (response || "no".equals(input)) {
break; // exit the loop
} else {
System.out.println("Invalid response.");
}
} while (!response);
return response;
}
I am not sure how I could change the inside of my if statement in the code fragment below to reflect false.
matches is a boolean method
if (topPileCard.matches(super.getCardFromHand(i))) {
tempCardArray[i] = super.getCardFromHand(i);
}
The easiest way is to include an exclamation mark ! at the beginning of the condition statement:
if (!topPileCard.matches(super.getCardFromHand(i))) {
tempCardArray[i] = super.getCardFromHand(i);
}
In Java, ! can be used to mean false or not. For example, the != comparator means "not equal to", as opposed to == which means "equal to".
Just add a !:
if (!(topPileCard.matches(super.getCardFromHand(i)))) {
tempCardArray[i] = super.getCardFromHand(i);
}
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;
In my program below, I set the variable th as true in the second if statement.
I'm curious why it later returns as false.
public boolean nodeExist(TreeNode Tree, T value){
boolean th = false;
if(Tree.getValue()!= null){
if(value == Tree.getValue()){
th = true;
}else{
if(value.compareTo((T) Tree.getValue()) < 0){
nodeExist(Tree.getLeft(), value);
}else{
nodeExist(Tree.getRight(), value);
}
}
}else{
th = false;
}
return th;
}
You probably look at a recursive call which sets th to true. But when that call returns to its caller, that th is still at false, and that's then returned. You need to assign the recursive callee's result:
if(value.compareTo((T) Tree.getValue()) < 0){
th = nodeExist(Tree.getLeft(), value);
}else{
th = nodeExist(Tree.getRight(), value);
}
You already got your answer. In future, to prevent mistakes like this, it's better to just return the value right away if you can. IT'S OKAY to have multiple return; if used properly, it can read to more readable code.
public boolean nodeExist(TreeNode Tree, T value){
if (Tree.getValue() == null) return false;
if (value == Tree.getValue()) return true;
if (value.compareTo((T) Tree.getValue()) < 0) {
return nodeExist(Tree.getLeft(), value);
} else {
return nodeExist(Tree.getRight(), value);
}
}
See also
Should a function have only one return statement?
Additionally, I noticed that you used == instead of equals for object comparison (i.e. T can't be a primitive type). This is rarely correct; equals is almost always what is really intended.
See also
Difference Between Equals and ==
One more style advice, please follow naming convention for Java, where variable names start with lowercase letter, with upper case letter for internal words (so, somethingLikeThis).
Programming isn't about getting things right, it's also about getting things readable. Learn and adopt a good coding style, and follow established conventions.
In the section in which you're doing your compareTo where the th value is not set. If this conditional is met, th can never be set to true.