JAVA logical operations - java

I really don't understand this kind of "operations" or what are they called :
System.out.println((1<2) ?5: (3<4) + " ");
Is the same with this code ?
if(1<2)
return 5;
else if (3<4)
But after ':' it says Dead code . Why is that ?

Compiler evaluates constant expressions at compile time. Because of that, the expression 1<2 is fully equivalent to the expression true, making the initial part of your conditional expression look like this:
System.out.println((true) ? 5 : (3<4) + " ");
// ^^^^^^^^^^ ^^^^^
// Important code |
// |
// Useless code -----------+
The compiler does not stop at evaluating 1<2, it goes on to evaluating the rest of the expression, which produces 5.

Your code is weird, I really do not understand what are you trying to achieve. I think it is wrong, it should be like this:
return 1 < 2 ? 5 : 3 < 4 ? 1 : 2;
You can rewrite it into if-else form:
if (1 < 2)
return 5;
if (3 < 4)
return 1;
return 2;
Since return causes the program to jump out of function, else is not needed in this particular example.

Related

ternary operator do nothing in else part

I have tried to leave the else part empty for ternary operator ( for int variables ), but I can't do it what is the problem?
here is the code
int FemaleCounter=0, MaleCounter =0, StateCounterIn =0 , StateCounterOut =0;
if(arr[0].equals("male") ) {
MaleCounter ++;
}
if(arr[0].equals("female") ) {
FemaleCounter ++;
}
if(arr[1].equals("in")) {
StateCounterIn++;
}
if(arr[1].equals("out") ) {
StateCounterOut++;
}
here is the ternary operator form :-
MaleCounter = arr[0].equals("male") ? MaleCounter++ : ;
FemaleCounter = arr[0].equals("female") ? FemaleCounter++ : ;
StateCounterIn = arr[1].equals("in") ? StateCounterIn++ : ;
StateCounterOut = arr[1].equals("out") ? StateCounterOut++ : ;
Thanks for your answers .
MaleCounter += arr[0].equals("male") ? 1 : 0;
FemaleCounter += arr[0].equals("female") ? 1 : 0;
StateCounterIn += arr[1].equals("in") ? 1 : 0;
StateCounterOut += arr[1].equals("out") ? 1 : 0;
A ternary expression must deliver a result. Also ++ inside and then assigment is overkill.
As its name indicates, the ternary operator takes three operands. You cannot omit any of them any more than you can omit either operand of any of the binary operators (*, /, ., etc.), or the one operand of a unary operator (++, --, among others).
The fact that an expression using the ternary operator is in some ways analogous to an if / then / else statement is irrelevant here, but the key distinction is important: an expression in the ternary operator evaluates to a value. It is necessary to designate that value for each alternative.
Observe, further, that your analogy is false anyway. You might consider fixing the syntax issue by using forms similar to this ...
// useless
MaleCounter = arr[0].equals("male") ? MaleCounter++ : MaleCounter;
..., but that does not have the same effect as your corresponding if statement, because in the case where the increment is performed, the pre-increment value is afterward assigned back to MaleCounter.
I find your original code pretty clear, but if for some reason you insist on using the ternary operator, then one of these is the model I would follow:
MaleCounter = arr[0].equals("male") ? MaleCounter + 1 : MaleCounter;
FemaleCounter += (arr[0].equals("female") ? 1 : 0);

How to write nested ?: statements

I would like to shorten my code by the use of the ?: (if-else-then) comparative operator instead of using the traditional if{}else{} blocks that inconveniently tend to take over the screen. I was never taught about this operator, and I would greatly appreciate any help regarding how to nest multiple comparisons within one line.
This is the code that I would like to shorten:
if(y<0)
y=0;
else
if(y+h>s.getHeight())
y = s.getHeight()-h;
I managed to condense each condition to this (not nested):
y = (y<0) ? 0 : y;
y = (y+h>s.getHeight()) ? s.getHeight()-h : y;
Is this the correct way to nest it?
y = (y<0) ? 0 : ((y+h>s.getHeight()) ? s.getHeight()-h : y);
Thank you!
EDIT: I was given a link to another post pertaining to the ?: operator. Link. However, my question has to do with nesting instead of just a simple if statement. Therefore, my question is not a duplicate of that post.
Yes, this is correct syntax but it's not readable.
You can check by yourself this in Java. Like this:
int a = 3;
int b = 5;
String s = (a < b) ? "Less than b" : (a > b) ? "More than b" : "Equal as b";
System.out.println(s);
But code is much more readable if you use if and if else statements. This ? and : is just for basic if statement.
For example:
int a = 3;
int b = 5;
String s = (a == b) ? "Equal" : "Not equal"
System.out.println(s);
But even in this case, I would rather use if statement. I really don't like to see ? and : instead of if statement :)
Regards,
golobic
You have correctly used ternary operator. However you could have avoided repeated method invocations for s.getHeight().
y = y < 0 ? 0 : y+h > s.getHeight() ? s.getHeight() - h : y;
Use the ?: (ternary) operator instead of an if-then-else statement if that makes code more readable.
ex. result = someCondition ? value1 : value2;
This can be nested further if value1, value2 are also ternary expressions.

JAVA - While loop exiting when it shouldn't be?

ive been trying to fix this problem for myself for about 2 hours. I'm guessing someone is going to instantly spot out my problem. So my problem is that a while loop(or .equals is giving an incorrect result). Here's the code:
Integer i = 0;
while(!type.equals(questionArray.get(i).questionType) && Questions.hasQuestionBeenUsed(i)) {
i++;
}
System.out.println(i + " type=" + type + " - questionType" + questionArray.get(i).questionType);
usedQuestionIndexes.add(i); //if question index has not been used - add it to used indexes
So the problem here is its exiting when the variable "type (string)" when it doesn't equal "questionArray.get(i).questionType (string)" which it shouldn't be. So lets say "type = 'hello'" and "questionArray.get(i).questionType = 'hi'" it is coming out of the loop?
The output from the code from the code above is this:
1 type=general - questionType=sport
So what is the problem here? Why is it saying the first condition is true when its not? the second condition is saying false(which is correct) heres the code for the method "hasQuestionBeenAsked":
public static Boolean hasQuestionBeenUsed(Integer questionIndex) {
for(Integer usedQuestionIndex : usedQuestionIndexes) {
if(questionIndex.equals(usedQuestionIndex)){
return true; //if index is found in usedQuestionIndexes array it will return that the index has been used
}
}
return false;
}
Thanks! If you need any extra info just tell me!
It's very simple - it's because you are negating the false by using the negation operator - (!). So even though you have false, you are ending up with true because (not) false = true. In your case, use
// Remove the negation - !
while(type.equals(questionArray.get(i).questionType) && Questions.hasQuestionBeenUsed(i)) {
i++;
}

Compere if statement short form

ı want to use short form for if statement. How can ı write if statement at one line? and how can ı compare them ı know there is same question at here. but my statement do not have else so ı could not do it without else statement.
public int compareTo(Uyum u) {
if (uyum < u.uyum)
return -1;
if (uyum > u.uyum)
return 1;
return 0;
}
You can use a ternary operator :
return uyum < u.uyum ? -1
: uyum > u.uyum ? 1
: 0;
You perhaps want:
return a < b ? -1 : (a > b ? 1 : 0);
you may simply write this:
public int compareTo(Uyum u) {
return uyum - u.uyum;
}
Inline if statement (question mark) are normally only desired if you have two states. Readability of your code is very important.
In your case you have 3 states (0, 1 and -1); I would not recommend using the inline if statement.
Example inline if statement:
String value = variable==null?"defaultvalue":variable;
This if statement notation is called ternary operator
It seems to me that u.uyum is an int, in which case, why is the following not satisfactory?
return Integer.compare(uyum, u.uyum)
If you really must use a ternary operator, you can do as everybody else is suggesting:
return uyum > u.uyum ? 1 : uyum == u.uyum ? 0 : -1
This tends to be frowned upon though, as it's not terribly legible.
return (uyum-u.uyum)==0?0:((uyum-u.uyum)<0?-1:1)

Is there a way to pre increment by more than 1 in Java?

In Java you can do a post increment of an integer i by more that one in this manner:
j + i += 2.
I would like to do the same thing with a pre increment.
e.g j + (2 += i) //This will not work
Just put the increment statement in parentheses. For example, the following will output pre: 2:
int i = 0;
System.out.println(
((i+=2) == 0)
? "post: " + i : "pre: " + i);
However, writing code like this borders on obfuscation. Splitting up the statement into multiple lines will significantly improve readability.
Not sure if there is a confusion in terminology going on, but += is not a post or pre-increment operator! Java follows the C/C++ definition of post-increment/pre-increment and they are well defined in the standard as unary operators. += is a shortcut for a binary operator. It evaluates to this:
lvalue1 += 5 ;
// is really (almost)
lvalue1 = lvalue1 + 5;
The assembler for the instruction doesn't look exactly like the binary version but at the level your using Java you do not see that.
The post-increment/pre-increment are unary operators that function kind of like this:
i++ ; // is something like _temp = i; i = i + 1; return temp;
++i; // is something like i = i + 1; return i;
This is just an example of how it works, the byte code doesn't translate too multiple statements for the post-increment case.
In your example, you could say a post-increment occurs but really, its just an increment. which is why I believe you have made the (incorrect) leap that it might be possible to have a pre-increment version of the same operation. But such a thing does not exist in C, C++, or Java.
Something like:
int increment = 42;
int oldI = i;
i += increment;
result = myMethod(oldI);
// Rest of code follows.
But why would you want to do this?
The += is pre increment. If you want post increment simply create wrapper with postInc method which will do this. If you really need this it would be more readable than parenthesis.

Categories

Resources