Scanner
Scanner

Reputation: 73

What is the difference between boolean = true and just boolean

I'm doing a practice question which is:

We have a loud talking parrot. The "hour" parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return true if we are in trouble.

parrotTrouble(true, 6) → true parrotTrouble(true, 7) → false parrotTrouble(false, 6) → false

My code is:

`public boolean parrotTrouble(boolean talking, int hour) {
 if ((talking = true) && (hour < 7 || hour > 20)){
 return true;
 }
 else
 return false; 
}`

The correct answer is:

public boolean parrotTrouble(boolean talking, int hour) {
          return (talking && (hour < 7 || hour > 20));
          // Need extra parenthesis around the || clause
          // since && binds more tightly than ||
         // && is like arithmetic *, || is like arithmetic +

}

I am wondering what is the difference between talking = true and just talking.

Upvotes: 2

Views: 163

Answers (4)

Vishnu
Vishnu

Reputation: 375

In java if statement requires result of if condition = true // if(condition)
to be able to execute code inside curly bracket // {}
=> this true you can assign directly i.e if(true)
or it can generated as result of condition i.e if(val==true) now in your case
when you put talking = true it assign true to talking and return true
and in other code use talking directly which contains value true so it returns true

Upvotes: 0

Rajesh
Rajesh

Reputation: 2155

When you just use talking, it will have same value which is passed as parameter to parrotTrouble method. So value changes as per input.

Whereas talking = true is an assignment which will always evaluate to true.

Upvotes: 0

Raghav N
Raghav N

Reputation: 201

in Java , sign equal represents assignments, double equal represents comparison.

In your case you are assigning instead of comparing.

Upvotes: 1

Eran
Eran

Reputation: 394126

talking = true assigns true to talking and returns true.

if (talking == true) is the same as if (talking), since both return true.

Upvotes: 6

Related Questions