Java primitive declaratiron - java

Given the following code snippet:
int i = 0;
int y = + ++i;
System.out.println(y);
The result is 1. Why is this a valid declaration? Can anyone explain what is =+?

int y = + ++i;
The first + in this line is simply the unary + operator (see: Assignment, Arithmetic, and Unary Operators). It does nothing. It's similar to the unary - operator. The line above is equivalent to:
int y = ++i;
which increments i and then assigns the new value of i to y.

Here + indicates the value is positive or not,i.e. unary operator and if you changes the value to - then the answer will be -1. i.e. int y = - ++i; will give -1.

The first plus after the equals sign is the sign of the value.
So it means it is a positive number.
int y = - ++i; would return -1

Java guarantees that it will be evaluated left-to-right. Specifically, ++ has higher precedence than +. So it first binds those, then it associates the addition operations left to right

Related

Does the minus symbol preceding a variable make the first variable negative?

We are asked to use for int variables to make the answer equal 20. We are only supposed to change the placement of the plus's and minuses. They have a minus in front of int a. Does that make int a negative?
I've googled the answer but my Googlefu isn't up to par.
public static int a = 1;
public static int b = 3;
public static int c = 9;
public static int d = 27;
public static void main(String[] args) {
int result = - a + b - c + d;
}
In the expression:
- a + b - c + d
there are 3 different operators, going left to right:
Unary minus operator
Binary plus operator
Binary minus operator
(Binary plus operator again)
In general, unary operators have higher precedence than binary operators, so this expression is equivalent to:
(( (- a) + b) - c) + d
So, the unary - applies to the a. From the linked specification above:
At run time, the value of the unary minus expression is the arithmetic negation of the promoted value of the operand.
So, it doesn't make a negative, it results in an expression whose value is the negation of a. This happens to be negative, because a has a positive value. However, it doesn't make a anything, a is left unchanged.
The only way to actually make a negative would be to reassign it:
a = -Math.abs(a);
For a more elaborate answer please have a look at the java language specification, where you can find detailed information on how operators and expressions are evaluated in java (in your case: https://docs.oracle.com/javase/specs/jls/se12/html/jls-15.html#jls-15.15.4)

Whats wrong with this expression? Is it evaluated from left to right meaning that the mistake is that a String is added to a double first?

If d1 and d2 are doubles with valid values, what is wrong with the following expression?
"answer = " + d1 < d2
The Java operators page shows that "additive" (+) operator are evaluated before "relational" (<) operators.
So the statement String + double < double will be seen like :
String + double < double == (String + double) < double --> String < double
The result will be String < double, that operation is not supported in java. So it will not compile.
Check the operator precedence array to find the exact order.
The closer to the top of the table an operator appears, the higher its precedence
Operators with higher precedence are evaluated before operators with relatively lower precedence
When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first :
All binary operators except for the assignment operators are evaluated from left to right;
assignment operators are evaluated right to left.

Negate int using XOR and addition

I have to write a method which converts an int value to the same negative int value. For example, if the user types in 5 the method should give back -5.
The whole story is:
The method has a transfer parameter which is either a positive or a negative int. Is it a positive int, we should change it to a negative int. If it is a negative int, do nothing.
It is also hard to check if the given int is positive or negative.
The regulations:
I'm only allowed to use the arithmetic operation + and all the boolean operations. But in this case I know that I have to use XOR.
It's not about writing the method and all the JAVA stuff. It's just the logic I struggle with.
How can I change a value to its negative value using only XOR and +?
ATTENTION:
The only operations allowed are:
!
^
&&
||
+
No *, no -, no ~
Edit:
The two solutions from CherryDT and MikeC are working well. Any ideas how to check if its a negative or a positive parameter with the same regulations? I thought this would be the easy part. Then realized it isn't.
(x ^ -1) + 1
Explanation: Basically, it's the same as ~x + 1. -1 has all bits set, and therefore inverts all bits when XORed with, just like NOT. And since, the other way round, inverting will always give you -x - 1, all you need to do is invert and add 1.
Here we go
public class Test {
public static void main(String []args){
int x = 245;
System.out.println(x);
x = (~x^x)*x;
System.out.println(x);
}
}

concatenating string and numbers Java

Why is the output different in these cases ?
int x=20,y=10;
System.out.println("printing: " + x + y); ==> printing: 2010
System.out.println("printing: " + x * y); ==> printing: 200
Why isn't the first output 30? Is it related to operator precedence ? Like first "printing" and x are concatenated and then this resulting string and y are concatenated ? Am I correct?
Its the BODMAS Rule
I am showing the Order of precedence below from Higher to Low:
B - Bracket
O - Power
DM - Division and Multiplication
AS - Addition and Substraction
This works from Left to Right if the Operators are of Same precedence
Now
System.out.println("printing: " + x + y);
"printing: " : Is a String"
"+" : Is the only overloaded operator in Java which will concatenate Number to String.
As we have 2 "+" operator here, and x+y falls after the "printing:" + as already taken place, Its considering x and y as Strings too.
So the output is 2010.
System.out.println("printing: " + x * y);
Here the
"*": Has higher precedence than +
So its x*y first then printing: +
So the output is 200
Do it like this if you want 200 as output in first case:
System.out.println("printing: "+ (x+y));
The Order of precedence of Bracket is higher to Addition.
Basic math tells you that adding numbers is done each at a time.
So "printing: " + x is computed first. As it s a string + int the result is "printing: 20". Then you add y so "printing: 20" + y equals "printing: 2010".
In the second case, multiplying is prioritary. So first x * y is calculated and equals 200. Then "printing: " + 200 equals "printing: 200".
The results that you observe are certainly related to operator precedence and also the order of evaluation. In the absence of another rule, i.e. an operator of higher precedence, operators are evaluated in order from left to right.
In the first expression, all operators have the same precedence, because they're the same operator: +, and so the first operation is evaluated. Since it involves a String, it is String concatenation, and the result is a String; similarly for the following +.
In the second expression, one of the operators is *, which has higher precedence than +, and so is evaluated first. You get the result of the multiplication, an integer, and then the concatenation of a String and an int due to the +.
This will print 30:
System.out.println("printing: " + (x + y))
You need the parentheses to express the precedence you wish for.
It is for operator precedence
System.out.println("printing: " + x * y);
here * operator has more precedence than + so first it calculate x * y.
System.out.println("printing: " + x + y);
Where as here all are same operator and it will be treated as String concatenation operation as there is one string value is there.
if you involve bracket into this - System.out.println("printing: " + (x + y));
Then bracket ( operator has more precedence than + so first it will calculate (x + y) and will print 30
check detail operator precedence order
In the first printing line, the + operator is applied first between the String and the int and the result is a String which is again concatenated with another int resulting a String.
In the second line, the order of the operations is: first the multiplication and the resulted int concatenated to the String.
System.out.println("2*("+a"+"+b"*"+c")")
How to print this

What is the difference between += and =+?

What is the difference between += and =+?
Specifically, in java, but in general also.
i += 4;
means
i = i + 4; // increase i by 4.
While
i =+ 4;
is equivalent to
i = +4; // assign 4 to i. the unary plus is effectively no-op.
(See http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.15.3 for what a unary + does.)
+= is an operator that increments the left-hand side of the assignment by the value of the right-hand side and assigns it back to the variable on the left-hand side. =+ is not an operator but, in fact, two operators: the assignment operator = and the unary plus + (positive) operator which denotes the value on the right-hand side is positive. It's actually redundant because values are positive unless they are negated with unary minus. You should avoid the =+ construct as it's more likely to cause confusion than do any actual good.
+= is get and increment:
a += 5; // adds 5 to the value of a
=+ isn't really a valid identifier on its own, but might show up when you're using the unary + operator:
a =+ 5; // assigns positive five to a
=+ is not an operator. The + is part of the number following the assignment operator.
int a = 4;
int b = 4;
a += 1;
b =+1;
System.out.println("a=" + a + ", b=" + b);
This shows how important it is to properly format your code to show intent.
+= is a way to increment numbers or String in java. E.g.
int i = 17;
i += 10; // i becomes 27 now.
There is no =+ operator. But if you do i =+ 10; it means i is equal to +10 which is equal to just 10.
Specifically, in java, but in general also.
In Java x += <expr>; is equivalent to x = x + ( <expr> ); where the + operator may be the arithmetical add operator or the string concatenation operator, depending on the type of x. On the other hand, x =+ <expr>; is really an ugly way of writing x = + <expr>; where the + is unary plus operator ... i.e. a no-op for numeric types and a compilation error otherwise.
The question is not answerable in the general case. Some languages support a "+=" operator, and others don't. Similarly, some languages might support a "=+" operator and others won't. And some languages may allow an application to "overload" one or other of the operators. It simply makes no sense to ask what an operator means "in general".
I don't know what you mean by "in general", but in the early versions of C language (which is where most of Java syntax came from, through C++), =+ was the original syntax for what later became +=, i.e. i =+ 4 was equivalent to i = i + 4.
CRM (C Reference Manual) is the document the describes C language with =+, =-, =>> and so on.
When you have a+=b, that means you're adding b to whatever's already in a. If you're doing a=+b, however, you're assigning +b to a.
int a=2;
int b=5;
a+=b;
System.out.println(a); //Prints 7
a=2;
b=5;
a=+b;
System.out.println(a); //Prints 5
The += operation as you said, is used for increment by a specific value stated in the R value.Like,
i = i+1;
//is equivalent to
i += 1;
Whereas, =+ is not any proper operation, its basically 2 different operators equal and unary plus operators written with each other.Infact the + sign after = makes no sense, so try not to use it.It will only result in a hocum.
i =+ 1;
//is equivalent to
i = +(1);

Categories