Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Came across this question in one of practice exam for OCA java certification:
Which statements about the output of the following programs are true?
int i = 0;
boolean bool1 = true;
boolean bool2 = false;
boolean bool = false;
bool = (bool2 & method1("1")); //1
bool = (bool2 && method1("2")); //2
bool = (bool1 | method1("3")); //3
bool = (bool1 || method1("4")); //4
}
public static boolean method1(String str) {
System.out.println(str);
return true;
}
The answer given is it prints 1 and 3
Can some one please explain me the solution?
2 and 4 are not printed because only the first part of the expression is evaluated in those cases.
For the && Operator it doesnt matter what the second expression is, if the first expression is already false. So it is not necessery to evaluate the second part.
if(false && true)
is the same as
if (false)
For the || Operator it is vice versa, if the first expression is already true it is not necessary to evaluate the second part. Therefore your method is not called.
if(true || false)
is the same as
if(true)
But keep in mind that if you switch your expressions, like so:
bool = (method1("2") && bool2);
Your method would be called. Thats because your first part of the Expression is true, so the whole expression could be true. Therefore the second part needs to be evaluated too.
Try
bool = (method1("2") && method1("2") );
bool = (method1("2") || method1("2") );
and see what´s happening.
& and | are bitwise comparators and therefore every part of your expression is evaluated. Therefore your method is called.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 12 days ago.
Improve this question
import java.util.\*;
class Example{
public static void main(String asrg\[\]){
boolean b = false;
System.out.println(10\>4 && true !=b==(10+3/2==8)==true); //Line 1
}
can anyone explain this expression?
expecting the steps how to calculate these
The code provided is missing a final curly brace ('}') and will not compile. There are also some backslashes ('\') strung about that will result in syntax errors. Additionally, 'args' is misspelled but it is not necessary in order for code to compile.
With the final brace added and backslashes removed, the code is:
import java.util.*;
class Example
{
public static void main(String args[])
{
boolean b = false;
System.out.println(10>4 && true !=b==(10+3/2==8)==true); //Line 1
}
}
Running the above code will display the answer in console. However the steps can be explained below.
First, we need to simplify our boolean expression into just terms of true and false. Since we declare that b = false, and the fact that10 > 4 == true and (10+3/2==8) == false, the expression that is printed can be simplified to (true && true != false == false == true).
The expression can then be evaluated according to Java's operator precedence, and will evaluate to false.
Your code won't compile; It's missing a } at the end of the class.
Also, did you copy and past this from a website? Why are there \ all over the place?
For better readability, use the Java-style array declaration: String[] args instead of String args[].
To check a boolean value, you don't have to compare it to true or false. This includes any actual booleans, or expressions outputting a boolean, such as: 10 + 3 / 2 == 8, which is false.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have this code...
class Test {
public static void main(String[] args) {
Boolean mySuperBoolean = Boolean.FALSE;
System.out.print("a");
if (mySuperBoolean = Boolean.TRUE) {
System.out.print("b");
}
System.out.print("c");
}
}
I am new to Java, but I knew single equal (=) is used to assign. And double equals (==) is used to check if object is referred to the same location in memory. However, in this case I do not understand how the 'b' is being printed with a single equals, but I understand changing it to a double equals sign will not print it out
if (mySuperBoolean = Boolean.TRUE) will assign Boolean.TRUE to your mySuperBoolean variable and the condition will evaluate to true, hence whatever is inside your if it will always execute
The result of the assignment operator = will be the assigned value. So if (mySuperBoolean = Boolean.TRUE) will always evaluate to true.
Assignment is an expression which resolves to whatever was assigned, in this case(mySuperBoolean = Boolean.TRUE) is an expression which resolves to Boolean.TRUE.
This is really only useful in a few specific situations. One such case is the following idiom:
String line;
while ((line = readLine()) != null) {
//...
}
Or even
i = j = k = 0; // equal to: i = (j = (k = 0))
It's a controversial feature because it allows probable bugs such as yours to compile successfully. To mitigate this, some people will invert the operands (a "yoda condition"):
if (Boolean.TRUE == mySuperBoolean)
This works because if I forget the second equals then the compiler will throw an error because Boolean.TRUE is final and cannot be assigned to.
In essence, what happens here boils down to:
if (Boolean.TRUE) {
System.out.print("b");
}
That assignment puts TRUE into the variable, the variable is boolean, and checked for its current value, end of story.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I just came up with a problem returning a Boolean value in accordance with a given condition. I thought in order to check the given condition for full possibilities I need to use for loop. But when I tried to compile it, it gives me error, possibly because there is uncertainty returning a Boolean value using for loop. Here is an original problem:
Return true if the given string contains a "bob" string, but where the middle 'o' char can be any char.
bobThere("abcbob") → true
bobThere("b9b") → true
bobThere("bac") → false
And here is my code:
public boolean bobThere(String str)
{
for(int i=0; i<str.length()-3; i++)
{
if (str.length()>=4): && str.charAt(i)=='b' && str.charAt(i+2)=='b')
{
return true;
}
else
return false;
else if (str.length()==4 && str.charAt(0)=='b' && str.charAt(2)=='b')
{
return true;
}
else
{
return false;
}
}
}
I just wanted to ask :
1. Can I fix the this code for returning a value. I mean, can I use for loop and return specific value for a given condition? If yes, please could you give me a sample.
2. Or are there any ways other than for loop to solve this problem.
Thanks in advance.
The compiler error is almost certainly because you have an elseif after an else. That's invalid.
Looking at your code, what you seem to want to do is loop through the string, and then return true if you're at the start of a b?b string. I'm not sure why you have your second if condition in there - at the moment your code would check the first and third characters of the string on every iteration of the loop, if the string happens to be exactly four characters long. Pointless, it doesn't need to be there. The check for length isn't necessary at all.
Additionally, your end condition for the loop is currently i < string.length()-3. This means that the final three characters of the string will not be checked. You would need to change this to either i <= string.length()-3 or i < string.length()-2 to solve this.
Your else return false stuff is going to give you a serious problem. Your code will enter the loop once, and then either return true or false, without ever going to the next phase of the loop. What you should do is loop through the string, and if you find what you're looking for, return true. Otherwise, don't return at all, and keep going with the loop. If you get to the end of the loop it means you never found what you were looking for, so you can at that point return false.
Taking those comments into account, your revised code would look like this (please note I haven't compiled or run this):
public boolean bobThere(String str)
{
for(int i = 0; i <= str.length() - 3; i++)
{
if (str.charAt(i) == 'b' && str.charAt(i + 2) == 'b')
{
return true;
}
}
return false;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to use this boolean method in my app. I want to use what it returns in an if statement so if it returns true I can do something. Something like
if(isNook() == True) {
//do something
}
I'm sure the answer is obvious but I couldn't find anything on how to do this.
Why don't you use:
if (isNook()) {
// do something
}
People are suggesting this:
if (isNook()) {
// do something
}
which is correct. However, we need to discuss your attempt. This was it:
if(isNook() == True) {
// do something
}
In Java, boolean variables are represented with true and false - NOT True and False - the values are case sensitive.
To contrast, for example, Python uses the values True and False
Your attempt should have been this:
if(isNook() == true) {
// do something
}
Try this:
boolean bool_result;
if(bool_result = isNook( )) {
// do stuff with bool_result here
}
result can actually be other data types (i.e. int/char/string) as long as it evaluates to true or false.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to figure out how to do something like:
int test = 1;
int test1 = 10;
if (value = test (though) test1) {
}
I've looked at oracles java operators but could not figure out how to do it.
The construct should check if value is between test and test1.
Can anybody tell me how to do this in Java?
if (value >= test && value <= test1)
{
//doSomething
}
Java does not support chained inequalities, ie test <= value <= test1, so instead you can just use two boolean expressions, connected via the boolean and operator, to get a logically equivalent conditional.
You should try something like with logical and operator
if (value > test && value < test1) {
// do something
}
or add >= to add equals comparison too.
It looks like you are looking for range operator that is common in a lot of programming languages, Java not being one of them, but the condition that you are trying to impose on the range will always be the same. You don't need to check every value in the range, merely the endpoints since it is contiguous:
if( value > test && value < test1 ) {
// do something
}
There is no through op in Java. You can do it with a simple if :
if (value >= test && value <= test1) {
// your code
}
This post begged to be clarified.
If you are checking that value is between test1 and test2 then you need:
if(value >= test && value <= test1){
// do stuff
}
Note that you should remove the = signs if value should be strictly between test and test1.
However, if you are checking that value is one of multiple tests from test0 "through" test10 for instance, then pack those tests in a set and check if value is among them:
import java.util.*;
Set tests = new HashSet();
tests.add(test);
tests.add(test1); // similarly for as many as you need
if(tests.contains(value)){
// do stuff
}