Return statement syntax - java

What do the symbols '?' and ':' mean in a return statement?
public boolean isItBigger(BigInteger num1, Long num2) {
return num1 == BigInteger.ONE || num2.intValue() > 0 ? true : false;
}
Also I think I have seen them in if statements.

Using ? and : is Java's ternary conditional operator (JLS 15.25). The result of the expression
aBoolean ? expr1 : expr2
is expr1 if aBoolean is true, else it's expr2.
In this case, it could be left off because it's unnecessary:
return num1 == BigInteger.ONE || num2.intValue() > 0;

It's a ternary operator. The following are equivalent
if (x == y)
x = 2;
else
x = 3;
and
x = (x == y) ? 2 : 3;
Your example code is silly though. First they're checking if the expression evaluates to true. Then, if it does, they return true. They could just as well return the result of expression itself, like so:
return num1 == BigInteger.ONE || num2.intValue() > 0;

this is called conditional/ternary operator
boolean-expression ? do-this-if-true : else-do-this
it is shortened form of
if (boolean-expression) {
do-this
} else{
do-this
}

Related

Convert this java method without using if/loops

Convert the following without if/loops. You can still use recursion, &&, || etc...
public boolean mystery(int n){
if(n == 0){
return false;
}
if(n%10 == 7){
return true;
}
return mystery(n/10)
}
I would like hints.
But I've been experimenting around.
We know that true && false == false and only true && true == true
So we must have that
return (n%10 == 7) && ....
Then for the second part, we could either get true or false, and if the second part is true, then our first part being true will result in everything being true, so I am thinking.
return (n%10 == 7) && ...
But I am thinking an issue might be that if n%10 isnt 7 right off that bat everything is false.
In my view, the ternary operator is still pretty much an 'if' statement - but that becomes a semantic debate. You can avoid using it entirely.
return (n % 10 == 7) || (n != 0 && mystery(n/10));
There are many ways: but to give you a start:
if(n == 0){
return false;
}
if(n%10 == 7){
return true;
}
return mystery(n/10)
}
is equivalent to
return n==0 ? false : n%10==7 ? true : mystery(n/10);
is equivalent to
return n!=0 ? n%10==7 ? true : mystery(n/10): false;
is equivalent to
return n!=0 && n%10!=7 ? mystery(n/10) : n!=0;
Was an interesting activity to solve. Solution below with proof of testing till 10k. mystery2 is the method of interest for you.
How I got the solution:
Started printing the results from 0 to 100 and identify the pattern - found the ones starting or ending with 7 would return true and all others false. The first if block which compares with zero is actually encountered by all the numbers which do not qualify reminder 7 rule in any position. Thus, reminder 7 is the only condition to get true result and everything else would enter recursion until it becomes 0 after the unit's position is complete. Equating to 0 is required as we should have a condition that ends the recursion (or ends in StackOverflowException).
public static void main(String[] args) {
for(int i = 0 ; i<=10000; i++){
if(mystery(i) != mystery2(i)){
System.out.println("Mismatch... "+i);
}
}
}
static boolean mystery(int n) {
if (n == 0) {
return false;
}
if (n % 10 == 7) {
return true;
}
return mystery(n / 10);
}
static boolean mystery2(int n) {
return n % 10 == 7 || (n != 0 && mystery2(n / 10));
}

How to check if all boolean are true or false in Java?

I'm trying to figure out how to check if three variables are all true or all false. So that the condition becomes true, when these variables have the same value and false, when they don't have the same value.
I thought something like (d == e == f) would help me here but the condition is only true when all variables are set to true. But when they're set to false, the condition doesn't work. Could anyone explain to me why? I know a very basic issue but I really can't figure it out myself.
You can try like this :
if((d && e && f) || (!d && !e && !f))
It will enter in loop either all will be true or all will be false.
It's because all expressions having relational operators return Boolean value.
So, first e == f is evaluated. As these both are false (both operators having same value) so, this expression return true value.
This true value is evaluated against d which is false. So that expression returns false (as both Operators have different values now) .
To know if the 3 variables are all true or all false; this what you can do:
boolean allTrue, allFalse;
if(a && b && c) allTrue = true; //a, b & c will evaluate to boolean and if all three vars are true the condition will be true and hence the if statement will be accessed
if(!a && !b && !c) allFalse = true; //if the not of the 3 is true, i.e (the 3 boolean vars are false), the whole condtion will be true and the if-statement will be accessed and the allFalse will be set to true means all 3 are false
boolean allTrue=false;
boolean allFalse=false;
boolean a,b,c;//your three variables
if(a && b && c)
{allTrue=true;}
else if(!a && !b && !c)
{allFalse=true;}
Try this, here i have two variable flags that are set to false initially, when one of the condition is true then only it woll be set to true so after the last line of code you can check if allFalse or allTrue has values true or false.
It should be possible to stay closer to the original formulation like this:
boolean eitherAllTrueOrAllFalse = (d == e) && (d == f)
If you only need to know if all are true or all false, then this will be more than enough:
boolean flagAllTrue = a && b && c;
No need to use a if else.
First think of the conditions separately:
boolean allTrue = a && b && c;
boolean allFalse = !(a||b||c);
Then combine them:
boolean eitherAllTrueOrAllFalse = allTrue|allFalse;
let sum = 0;
sum += a ? 1:0; sum += b ? 1:0; sum += c ? 1:0;
let allTrueOrAllFalse = ( sum === 0 || sum === 3 );

Java pow implementation with Integer.MIN_VALUE as exponent

I am implementing a pow function in Java, and I am wondering how do we deal with Integer.MIN_VALUE as a exponent ? Do we just treat it as a special case ?
Because I tried to compare the result with the standard Java.lang.Math API and I get a couple different result. The following is the list of comparison
//this will print "1.0 vs 0.0"
System.out.println(pow(2,Integer.MIN_VALUE) + " vs " + Math.pow(2,Integer.MIN_VALUE));
//this will print "1.0 vs 1.0"
System.out.println(pow(1,Integer.MIN_VALUE) + " vs " + Math.pow(1,Integer.MIN_VALUE));
public double pow(double base, int exp){
double result = 1.0;
boolean pos = false;
if(exp == 0) return result;
if(exp > 0){
pos = true;
exp *= -1;
}
while(exp > 0){
if((exp & 1) == 1){
result *= base;
}
base *= base;
exp /= 2;
}
if(!pos){
result = 1/result;
}
return result;
}
So I am wondering if Integer.MIN_VALUE is a special case where I have to have a if statement for checking it.
if(exp == Integer.MIN_VALUE && base > 1) return 0.0;
Based on this line:
exp *= -1;
it seems that it might have to be a special case. There are certainly ways to implement this without that special case, but because -1 * Integer.MIN_VALUE cannot be stored in an int, you will get a bug if you do not handle it separately.
Yeah, you've got the problem that Integer.MIN_VALUE * -1 == Integer.MIN_VALUE. You could either special-case it, or you could deal with it another way. Indeed, one possible solution would be to make exp negative when it's positive, instead of the other way around; you'd just use -exp instead of exp.
On my system I have
-2147483648
2147483647
For Integer.MIN_VALUE and Integer.MAX_VALUE respectively. So you should see the problem in the line
exp *= -1;
Well, the real issue is that, since the sign doesn't flip on the MIN_VALUE, the sign cascades to the exp/2. and the 'negative power' case applies. If we split it, it's easier:
public double myPow(double x, int n) {
double result = 1.00000;
boolean negative = false;
if(n <0) {
negative = true;
n= -n;
}
result=power(x,n);
if(negative) {
result = 1/result;
}
return result;
}
private double power(double a, int n) {
if(n ==0 || a==1) return 1;// a^0 = 1, 1^n = 1
double x=power(a,n/2);
if(n%2 == 0) return x*x;
else return a*x*x;
}

How to represent boolean expressions using if/else statement(s)? Is this right?

Is the expressions
!(a ==b) a!=b equivalent?
i have yes here
!a && b b &&!a
yes
!a || b b ||!a
no
And how to write an if/else statement that stimulates the following expression:
z=(100>y) ? z*2 : z/2;
if (100>y)
z=z*2;
else
z-z/2;
what is z= and y= in the end?
i have z=40 and y=12
How to expand the expression y+=2
y=10, z=20
public static void main(String args[]){
int a = 1;
int b = 2;
int y = 10;
int z = 12;
System.out.println(!(a ==b));
System.out.println(a!=b);
if (100 > y) z = z*2; else z = z/2;
System.out.println(z);
System.out.println(y);
y = y + 2;
System.out.println(y);
}
Output:
The value for !(a ==b) is: true
The value for (a!=b)) is:true
24
10
12
Additional:
Some times (?:) conditional operator is a bit tricky this means that it takes three operands. Together, the operands and the ?: symbol form a conditional expression. The first operand (to the left of the ?) is a boolean expression (i.e., a condition that evaluates to a boolean valuetrue or false), the second operand (between the ? and :) is the value of the conditional expression if the boolean expression is True and the third operand (to the right of the :) is the value of the conditional expression if the boolean expression evaluates to false. For example, the statement:
System.out.println( studentGrade >= 60 ? "Passed" : "Failed" );
Your first question is an instance of de Morgan's Laws which you would do well to look up.

Syntax Question IF ELSE (Java)

what is the java syntax for saying
if x is not equal to a or b
I am trying to write an if else statement .. if a certain value is not equal to say 2 or 3 then do something else do something else :) thats confusing lol
Try this:
if (x != a && x != b) {
// Something (action x)
} else {
// Something else (action y)
}
Note that it's an "and" condition even though you're asking whether x is equal to a or b because each condition is negative. The other way you could represent this (if you find it more readable) is:
if (!(x == a || x == b)) {
// Something (action x)
} else {
// Something else (action y)
}
And at that point you may find it more readable still to get rid of the negation, but switch round what you do in the blocks:
if (x == a || x == b) {
// Action y
} else {
// Action x
}
These three blocks of code all do the same thing, but I think I'd find the bottom one the most readable as the condition is simple.
if ((x != a) && (x != b)) {
// do stuff
} else {
// do other stuff
}
if( x != a && x != b )
Notice it's an &&, not an ||
The condition ( x != 2 || x != 3 ) is always true: if x = 2, then x != 3 and the condition is true. if x = 1, then x != 2 and the condition is true.
What you're really saying is: if x is not one of 2 or 3, which is, x is not in the array [2,3], which is "x is not 2 neither 3", which is x != 2 and x != 3.
directly mimics the english sentence: if x is not equal to a or b
if (!(x == a || x == b))
{
doSomething();
}
else
{
somethingElse();
}
but if the extra not operator and parentheses hurts your eyes, use this(note the absence of the word Or in this condition, not anymore parallel with english sentence):
if (x != a && x != b)
{
doSomething();
}
else
{
somethingElse();
}
see my answer on programmer's ignorance pet peeve and Is it acceptable to only use the ‘else’ portion of an ‘if-else’ statement?, why i advocate constructing simple conditions(directly mimics english sentence, i.e. without sticky ANDs and too much NOTs)
if(x!=a && x!=b){
//do...
}
in java if-else is a control statement which is used to test condition and transfer the control based on the evolution of condition.
if((x!='a')||(x!='b'))//if a,b is char use quotes else avoid
{
//if expression is true
}
else
{
//if expression is false
}
if you want that code should be executed when x=a and x=b both then use '&&' instead of '||'.
For more details:
http://java.meritcampus.com/t/60/If-else-if-ladder?tc=mm70

Categories

Resources