This question already has answers here:
What is the purpose of Java's unary plus operator?
(7 answers)
Closed 8 years ago.
I ran across this while reviewing a colleague's code. She'd left it in by accident (it used to be a String concatenation), and I assumed that it wouldn't compile. Turns out I was wrong, so I tried seeing what that operator did:
public static void main(String[] args) {
int i = -1;
System.out.println(String.format("%s", +i));
System.out.println(String.format("%s", +i));
}
As far as I can tell, it does nothing, but I'm curious if there is a reason it's allowed to compile. Is there some hidden functionality to this operator? It's similar to ++i, but you'd think the compiler would barf on +i.
That is the plus unary operator +. It basicaly it does numeric promotion, so "if the operand is of compile-time type byte, short, or char, it is promoted to a value of type int".
Another unary operator is the increment operator ++, which increments a value by 1. The increment operator can be applied before (prefix operator) or after (postfix operator) the operand. The difference is that the prefix operator (++i) evaluates to the incremented value, whereas the postfix operator (i++) evaluates to the original value.
int i = -1;
System.out.println(+i); // prints -1
System.out.println(i++); // prints -1, then i is incremented to 0
System.out.println(++i); // i is incremented to 1, prints 1
Related
This question already has an answer here:
What is the type of a ternary expression with int and char operands? [duplicate]
(1 answer)
Closed 2 years ago.
This subject is already asked but I didn't understand it.
You'll find my program below. When I run this program it prints X and 88. When I remove do the declaration of int i = 0 it returns X and X. I found some explanations here : Unexpected output when using a ternary operator and final variable but i didn't understand it so much. I don't understand why this program returns X and 88 instead of X and X.
public class Ternary {
public static void main(String[] args) {
char x = 'X';
int i = 0;
System.out.println(true ? x : 0);
System.out.println(false ? i : x);
}
}
please read the rules of ternary operator here
https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25
1st one is result of If one of the operands is of type T where T is byte, short, or char, and the other operand is a constant expression of type int whose value is representable in type T, then the type of the conditional expression is T. T being type char in this case and constant expression being 0
so the output is of type char which is x
2nd one is case for Otherwise, binary numeric promotion is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands.
read about binary numeric promotion here https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6.2
last case of point 2 applies here Otherwise, both operands are converted to type int. and converting char to int gives its ascii value which is 88
and hence the output is 88
This question already has answers here:
Why does the ternary operator unexpectedly cast integers?
(3 answers)
Closed 5 years ago.
In my java code I have
result.append((num%b2)>=10?((char)('A'+((num%b2)-10))):(num%b2));
Where num and b2 are both integers. When num%b2 is greater than or equal to 10
((char)('A'+((num%b2)-10)))
is appended to the stringbuilder result. However instead of appending a char it appends an int value with the ASCII number of the char I wanted to return. Why will it not return the char?
It's because (num%b2) is an int.
The type of a conditional expression is the common type by which the two operands can be represented. So, if the "true" operand is a char but the "false" operand is an int, the result of someCondition ? someChar : someInt is an int.
It's a lot clearer if you just write it as a plain old if-else statement:
if (num%b2 >= 10) {
result.append((char)('A'+((num%b2)-10)));
} else {
result.append(num%b2);
}
Just convert it to string, and it will append it as string:
(char)('A'+((num%b2)-10)) + "" // this will do nice and quick conversion
This question already has answers here:
Why do we usually use || over |? What is the difference?
(28 answers)
Closed 5 years ago.
A book I'm working from states :
The short-circuit operators are nearly identical to the logical operators,
& and |, respectively, except that the right-hand side of the expression may never be evaluated if the final result can be determined by the left-hand side of the expression
To test this out I tried
int y = 1;
boolean x = false | (y < 4);
System.out.print(x); //true
Which printed out true as expected.
however
int y = 1;
boolean x = false || (y < 4);
System.out.print(x); //true
also prints out true which seems to contradict the book "the right-hand side of the expression may never be evaluated if the final result can be determined by the left-hand side of the expression".
I was assuming x would take the value of false as the final result can be determined from the left hand side alone
I was assuming x would take the value of false as the final result can be determined from the left hand side alone
No, the final result cannot be determined by the left hand side alone - since the left operand is false, the right operand must be evaluated too (since false OR something == something).
On the other hand, if the left operand was true, the result of the OR operator would be true, and the right operand could be ignored.
You should understand that short-circuit operators should give the same result as their non-short circuited counterparts (except for cases where evaluating the right operand may throw an exception and the short-circuited operators can determine the result by the left operand alone).
There would be no scenarios in which the short circuited operator returns false and the corresponding non-short circuited operator returns true or vice versa.
This question already has answers here:
How can a Java variable be different from itself?
(11 answers)
Closed 5 years ago.
Recently I had an interview with a Software company where the following question was asked in the technical aptitude round:
Declare i in such a way that the condition is always true :
while(i != i) {
}
Is it technically possible in java to assign something of this sort??
NaN is not equal to itself, so
double i = Double.NaN;
But I don't think this is a good interview question.
Quote from the Java Language Specification:
NaN is unordered, so:
The numerical comparison operators <, <=, >, and >= return false if either or both operands are NaN (§15.20.1).
The equality operator == returns false if either operand is NaN. In particular, (x<y) == !(x>=y) will be false if x or
y is NaN.
The inequality operator != returns true if either operand is NaN (§15.21.1). In particular, x!=x is true if and only if x
is NaN.
This question already has answers here:
Why is ++i considered an l-value, but i++ is not?
(11 answers)
Closed 8 years ago.
What the title says. For C++, (++a)++ does compile. Strangely enough, though, ++(a++) does not:
int main() {
int a = 0;
++a++; // does not compile
(++a)++; // does compile
++(a++); // does not compile
}
But in Java, it does not for all three:
public class Test {
public static void main(String[] args) {
int a = 0;
++a++; // does not compile
(++a)++; // does not compile
++(a++); // does not compile
}
}
Is there any reason why C++ compiles this but not in Java?
None of the examples work in Java because both postfix and prefix increment operations return values not variables we can see this by going to the JLS section on Postfix Increment Operator ++ for an example and it says:
The result of the postfix increment expression is not a variable, but a value.
The JLS section for Prefix Increment Operator ++ says the same thing.
This would be like trying to increment a literal value (see it live):
2++ ;
++3 ;
which gives the following error:
required: variable
found: value
Which is the same error we receive for your examples.
In C++ prefix increment returns an lvalue but postfix increment returns an prvalue and both prefix and postfix increment in C++ require an lvalue. So your first and third C++ example:
++a++;
++(a++)
fails because you are attempting to apply prefix increment to a prvalue. While the second C++ example:
(++a)++;
is okay because prefix increment returns an lvalue.
For reference the draft C++ standard in section 5.2 Postfix expressions says:
The value of a postfix ++ expression is the value of its operand [...] The operand shall be a modifiable lvalue
and:
The result is a prvalue
and section 5.3 Unary expressions says:
The operand of prefix ++ is modified [...] The
operand shall be a modifiable lvalue
and:
The result is the updated operand; it is an lvalue