i just generate this methode to find max val in some matrix and somehowe i was able to change int val insdie Ternary Operator (java 8)
int max=0, indexToReturn=0;
int size= arr[0].length;
for (int i=1 ; i < size ; i++)
{
//
// ¯\_(ツ)_/¯
max = (!(arr[j][indexToReturn] > arr[j][i])) ? indexToReturn= i : arr[j][indexToReturn] ;
}
return max > 0 || indexToReturn==size-1 ? arr[j][indexToReturn] : null;
(the method compile and working)
im not realy sure evan how its compile from what i saw online Ternary Operator syntax :
variable = Expression1 ? Expression2: Expression3
can someone explain me what im missing here ?
The reason this works is because an assignment is an expression. The value of an assignment is the value assigned. This sounds theoretical, so let us look at an example:
int i, k;
i = (k = 5);
System.out.println(i);
System.out.println(k);
Ideone demo
The value of the expression k = 5 is the assigned value 5. This value is then assigned to i.
Armed with this knowledge, we see that indexToReturn= i is an expression that evaluates to the value of i. When we swap Expression2 and Expression3, the ternary operator breaks because the = i is not evaluated as part of the ternary operator (due to operator precedence). If we set parentheses around Expression2, it works as expected.
I would discourage using the fact that an assignment is an expression. (Ab)using this fact often leads to hard-to-understand code.
Related
Netbeans is saying that my ternary operator isn't a statement. How come?
int direction;
direction = (Math.random() < 0.5) ? 0 : 1; // direction is either L or R (0 or 1)
direction == 0 ? System.out.print('L') : System.out.print('R');
I tried it's if/then/else counterpart and it works fine:
int direction;
direction = (Math.random() < 0.5) ? 0 : 1; // direction is either L or R (0 or 1)
if(direction == 0){
System.out.print('L');
} else {
System.out.print('R');
}
The statements in the ternary operator need to be non-void. They need to return something.
System.out.println(direction == 0 ? 'L' : 'R');
A ternary operator is intended to evaluate one of two expressions, not to execute one of two statements. (Invoking a function can be an expression if the function is declared to return a value; however, System.out is a PrintStream and PrintStream.print is a void function.) You can either stick with the if...else structure for what you're trying to do or you can do this:
System.out.print(direction == 0 ? 'L' : 'R');
NOTE: The comment by #iamcreasy points out a bit of imprecision in how I phrased things above. An expression can evaluate to nothing, so what I should have said was that a ternary operator evaluates one of two non-void expressions. According to the Java Language Specification §15.25:
It is a compile-time error for either the second or the third operand
expression to be an invocation of a void method.
From the JLS section 15.25. Conditional Operator ?:
It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.
both the second and third operand expression here:
direction == 0 ? System.out.print('L') : System.out.print('R');
are void so this is a not a valid use of a ternary expression. You could either stick to the if else or use something similar to this alternative:
System.out.print( direction == 0 ? 'L' : 'R' );
Also the logic here is not correct:
direction = (int)(Math.random() * 1);
direction will always evaluate to 0 since Math.random() generates numbers in the range [0.0,1.0) which means it does not include 1.0 and casting a double to int will just drop the decimals. Using nextInt(2) is a good alternative.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Incrementing in C++ - When to use x++ or ++x?
I've seen things like i++ commonly used in, say, for loops. But when people use -- instead of ++, for some reason some tend to write --i as opposed to i--.
Last time I checked, they both work (at least in JavaScript). Can someone tell me if this is so in other C-family languages, and if it is, why do some people prefer --i to i--?
++i is faster than i++. Why? See the simple explication.
i++
i++ will increment the value of i, but return the pre-incremented value.
temp = i
i is incremented
temp is returned
Example:
i = 1;
j = i++;
(i is 2, j is 1)
++i
++i will increment the value of i, and then return the incremented value.
Example:
i = 1;
j = ++i;
(i is 2, j is 2)
This is simillar for --i and i--.
I don't believe the preference for prefix (++i) vs. postfix (i++) varies depending on whether it's an increment or a decrement.
As for why, I prefer prefix where possible because my native language is English, which has mostly a verb-before-object structure ("eat dinner", "drive car"), so "increment i" or "decrement i" is more natural for me than "i decrement". Of course, I'll happily use postfix if I'm using the result and I need the value prior to the increment in an expression (rather than the incremented value).
Historically the increment/decrement operator were motivated by stack management. When you push an element on the stack:
*(stackptr++) = value
when you pop:
value = *(--stackptr)
(these were converted to single ASM instructions)
So one gets used to increment-after and decrement-before.
You can see another idiomatic example in filling in direct and reverse order:
for (p=begin;p!=end;)
*(p++) = 42;
for (p=end;p!=begin;)
*(--p) = 42;
It's pretty much a preference thing, that only comes into play if you're doing the pre- or post-increment on types that are more complicated than primitives.
Pre-increment ("++i") returns the value of i after it has been incremented, and post-increment ("i++") returns the value before increment. So, if i was of a complicated type that had overloaded the pre-increment and post-increment operators, the pre-increment operator can just return the object, whereas the post-increment would have to return a copy of the object, which could well be less efficient if the object is substantial. And in most cases (for loop increments, etc.), the value is ignored anyways.
Like I said, most of the time, not a problem, and just a preference thing.
In C and C++,++ and -- operators have both prefix form: ++i and --i, and suffix form: i++ and i--. Former means evaluate-then-use and latter means use-then-evaluate. The difference is only relevant when either form is used as part of an expression. Otherwise it's a matter of preference or style (or lack thereof).
F.ex., in int i = 0; int n = ++i;, i is first incremented and then its value, now 1, is assigned to n. In n = i++ value of i, still 1, is assigned to n and is then incremented, with i == 2 now.
When used as a statement, that is: i++; ++i; both forms are equivalent.
The difference is pre-incrementing or post-incrementing (and likewise with decrementing).
Quoting the Wikipedia article on the topic that shows up as the second Google result for "c decrement":
int x;
int y;
// Increment operators
x = 1;
y = ++x; // x is now 2, y is also 2
y = x++; // x is now 3, y is 2
// Decrement operators
x = 3;
y = x--; // x is now 2, y is 3
y = --x; // x is now 1, y is also 1
So, it's not so much a matter of preference as a matter of difference of results.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the Java ?: operator called and what does it do?
In some code a ? is used to perform a mathematical equation.
What is it and how do you use it? Is it possible to provide an example and the reason for the final answer of an equation?
int count = getChildCount();
int top = count > 0 ? getChildAt(0).getTop() : 0;
Basically is the ternary operator:
String mood = (isHappy == true)?"I'm Happy!":"I'm Sad!";
if isHappy, then "I'm Happy!". "I'm Sad!" otherwise.
I presume you mean something like x = () ? y : z; notation? If that's the case, then the expression within the parentheses is evaluated as a boolean, if true x = y otherwise x = z
int count = getChildCount();
int top = count > 0 ? getChildAt(0).getTop() : 0;
Means that the top variable will contain the value of getChildAt(0).getTop() if the count variable is greater than 0, else it will equal to 0
My guess is you are referring to the ternary operator, which is used like this:
<some condition> ? <some value> : <some other value>;
For example:
int max = a > b ? a : b;
It's a shorthand for an if and is equivalent to:
int max;
if (a > b) {
max = a;
} else {
max = b;
}
but allows a one-line result in code.
When used well, it can make code much more clear due to its terseness. However caution is advised if the line becomes too long or complicated: The code only remains readable when the terms are brief.
The ? in an evaluative expression is called the ternary operator. It is essentially short-hand for an if() ... else block.
http://en.wikipedia.org/wiki/%3F:
I assume you're referring to the ternary operator. It's shorthand for certain kinds of if statements. Where you're making an assignment, like:
int dozen = (bakersDozen) ? 13 : 12;
Assuming bakersDozen is true, then dozen will be 13. If it's false, it will be 12.
int result = (a > b) ? 1 : 0;
is the same than
int result;
if (a > b)
result = 1;
else
result = 0;
? Is usually a ternary (or tertiary) operator. So let's explain what it is doing.
myValue = (a = b) ? 1 : 0;
The first part is your condition. "Does a equal b?"
The second part is the true response.
The third part is the false response.
So if a is equal to b, myValue will be 1. If a is not equal to b, myValue will be 0.
See http://en.wikipedia.org/wiki/Ternary_operation
I recently discovered the shorthand if statement and after searching online I couldn't find a definite answer.
Is it possible to execute 2 statements if the condition is true/false?
int x = (expression) ? 1 : 2;
for example
int x = (expression) ? 1 AND 2 : 3;
Seeing as i haven't comne across a example where they used it I guess it's not possible but I wouldn't want to miss out.
You're talking about conditional assignment. You should look at what is defined by what you've written:
int x = (expression) ? 1 AND 2 : 3;
That is evaluating 'expression' and if true executing '1 AND 2' then assigning the value to x. If 'expression' evaluated to false, '3' is evaluated and assigned to x. Hence you could definitely do something like this:
int x = (expression) ? GetInt1() + GetInt2() : 345;
What is important is that what you have found is not just a shorthand if. It is conditional assignment.
You can't have a statement return two values and that's all that ternary does. It is not a shorthanded if it is a method persay that returns values
I know that one of them is bitwise and the other is logical but I can not figure this out:
Scanner sc = new Scanner(System.in);
System.out.println("Enter ur integer");
int x=sc.nextInt();
if(x=0)//Error...it can not be converted from int to boolean
System.out.println("...");
The error means that x cannot be converted to boolean or the result of x=0 can not be converted to boolean.
== checks for equality.
= is assignment.
What you're doing is:
if( x = Blah ) - in Java this statement is illegal as you can not test the state of an assignment statement. Specifically, Java does not treat assignment as a boolean operation, which is required in an if statement. This is in contrast with C/C++, which DOES allow you to treat assignment as a boolean operation, and can be the result of many hair-pulling bugs.
When you write 'x = 0' you are saying "Store 0 in the variable x". The return value on the whole expression is '0' (it's like this so you can say silly things like x = y = 0).
When you write 'x == 0' it says "Does x equal 0?". The return value on this expression is going to be either 'true' or 'false'.
In Java, you can't just say if(0) because if expects a true/false answer. So putting if(x = 0) is not correct, but if(x == 0) is fine.
== is a comparison operator, and = is assignment.
== is an equality check. if (x == 0) // if x equals 0
= is an assignment. x = 0; // the value of x is now 0
I know the question has been answered, but this still comes up from time to time not as a programmer error but as a typographical error (i.e., the programmer knew what he meant, but failed). It can be hard to see, since the two look so similar.
I've found that a way to help avoid doing this is to put the constant expression on the left-hand-side, like so:
if (0 == x)
...
That way, if I accidentally use only one "=" sign, the compiler will fail with an error about assigning to a constant expression, whether or not the assignment operator is left-associative and whether the if conditional expects a strongly-typed Boolean.
if(x=0)
Here you're assigning the value of 0 to the variable x. The if statement in Java can't evaluate an integer argument as it can in many other languages. In Java, if requires a boolean. Try
if(x == 0)
to do a comparison.
Interpret the error to mean
"The expression
x=0
cannot be converted to Boolean."
Just to clarify about C/C++ - assignment is evaluated to the right operand
if(a = n)
is evaluated to n, so (n = 1) is true (n = 0) is false
One interesting note: Since assignment operator evaluates to the right operand, the following is valid in Java(albeit not pretty):
if (( x = blah ) > 0) ...
Parenthesis are needed because of operator precedence ( '>' binds stronger than '=').
As others have already said, '=' is assignment; '==' is compare.
in your program change
if(x=0)
to
if(x==0)
"==" checks for equality
"=" Is used for assignment.
It is giving you error cause you're assigning value to x in if(), where you're supposed to check for the equality. Try changing it to equality instead of assignment operator.
As others stated, = assigns while == compares.
However, these statements have their own values as well.
The = operator returns the value of its right-hand operand. This is how statements like a = b = c = 5 work: they are parsed as a = (b = (c = 5)), which evaluates to a = (b = 5) and then a = 5.
The == operator returns a boolean that is true if its operands are equal. The if statement runs its body if its argument is true. Thus, if headers like if (5 == 5) translate to if (true). This is why sometimes you see infinite while loops with header while (true); the while loop runs "while" toe argument is true.
If you had a boolean in your if statement, it would give no error and run the code if the value being assigned (or "compared to") was true. This is why it is so important to never mix up the = and == operators, especially when working with booleans.
Hope this helped!!