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);
Related
I am obviously new to java. I have this assignment where I am supposed to write a program which performs arithmetic operations on numbers expressed as a character string.
I don't know where to start. I have tried googling, looking through my book, big java, in the relevant sections but can't seem to find helpful information.
I found a program that have completed the same assignment but I want to learn write my own and understand how to go about.
I can show you one of the methods that he used.
I have bolded a few comments where I get confused.
public static String add(String num1, String num2) {
while (num1.length() > num2.length()) {
num2 = "0" + num2;
}
while (num1.length() < num2.length()) {
num1 = "0" + num1;
}
int carry = 0; // whats the point of this?
String result = "";
// look at the for loop bellow. I don't understand why he is converting the strings to ints this
// way? this doesn't even return the correct inputed numbers?
for (int i = 1; i <= num1.length(); i++) {
int digit1 = Character.getNumericValue(num1.charAt(num1.length() - i));
int digit2 = Character.getNumericValue(num2.charAt(num2.length() - i));
int sum = digit1 + digit2 + carry;
carry = sum / 10;
result = (sum % 10) + result;
// why is he dividing the sum with 10? If the user inputs a 5, would't the result become 0.5
// which isn't a valid int value? this line is also confusing
}
if (carry > 0) {
result = carry + result;
}
return result;
}
Any explanation or even guidance to a page where I am trying to do is explained would be very appreciated.
I found a program that have completed the same assignment but I want to learn write my own and understand how to go about.
That is the right idea. I suggest that you stop looking at the code that you found. (I'm sure that your teachers don't want you to look up the answers on the internet, and you will learn more from your homework if you don't do it.)
So how to proceed?
(I am assuming that you are supposed to code the methods to do the arithmetic, and not just convert the entire string to a primitive number or BigInteger and use them to do the arithmetic.)
Here's my suggested approach:
What you are trying to program is the equivalent of doing long addition with a pencil and paper. Like you were taught in primary school. So I suggest that you think of that pencil-and-paper procedure as an algorithm and work out how to express it as Java code. The first step is to make sure that you have the steps of this algorithm clearly in your head.
Try to break the larger problem into smaller sub-problems. One sub-problem could be how to convert a character representing a decimal digit into an integer; e.g. how to convert '1' to 1. Next sub-problem is adding two numbers in the range 0 to 9 and dealing with the "carry". A final sub-problem is converting an integer in the range 0 to 9 into the corresponding character.
Write sample Java code fragments for each sub-problem. If you have been taught about writing methods, some of the code fragments could be expressed as Java methods.
Then you assemble the solutions to the sub-problems into a solution for the entire problem. For example, adding two (positive!) numbers represented as strings involves looping over the digits, starting at the "right hand" end.
As part of your program, write a collection of test cases that you can use to automate the checking. For example:
String test1 = add("8", "3");
if (!test1.equals("11")) {
System.out.println("test1 incorrect: expected '11' go '" +
test1 + "'");
}
Hints:
You can "explode" a String to a char[] using the toCharArray method. Or you could use charAt to get characters individually.
You can convert between a char representing a digit and an int using Character methods or with some simple arithmetic.
You can use + to concatenate a string and a character, or a character and a string. Or you can use a StringBuilder.
If you need to deal with signed numbers, strip off and remember the sign, do the appropriate computation, and put it back; e.g. "-123 + -456" is "- (123 + 456)".
If you need to do long multiplication and long division, you can build them up from long addition and long subtraction.
You can convert a number in String format to a number in numeric format by “long n = Long. parseLong(String)” or “Long n = Long.valueOf(String)”. Then just add 2 long variables using a + sign. It will throw NumberFormatException if the String is not a number but a character. Throw that exception back to the caller.
The first part of the code pads both numbers to equal lengths.
e.g. "45" + "789" will be padded to "045" + "789"
The for loop evaluates one character at a time, starting from the right hand most.
iteration 1 -> (right most)
5 + 9 -> 14
when you divide an integer with another integer, you will always get an integer.
hence carry = 14/10 = 1 (note: not 1.4, but 1, because an int cannot have decimal places)
and the remainder is 14 % 10 = 4 (mod operation)
we now concatenate this remainder into "result" (which is "" empty)
result = (14%10)+ result; // value of result is now "4"
iteration 2 -> (second right most)
4+8 + (carry) = 4 + 8 + 1 = 13
same thing, there is a carry of 13/10 = 1
and the remainder is 13%10 = 3
we concatenate the remainder into result ("4")
result = (13%10) + result = 3 +"4" = "34"
iteration 3->
0 + 7 + 1 = 8
this time 8/10 will give you 0 (hence carry = 0)
and 8%10 will give a remainder of 8.
result = 8 + "34" = "834"
after all the numbers have been evaluated, the code checks if there are anymore carry. if the value is more than 0, then that value is added to the front of the result.
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)
So I came across something that confused me when casting a byte to char, usually I would do this:
for (byte b:"ABCDE".getBytes()) {
System.out.println((char)b);
}
Which will print out
A
B
C
D
E
I accidentally left a + between the (char) and b and got the same result!?
Like so:
for (byte b:"ABCDE".getBytes()) {
System.out.println((char) + b);
}
Why exactly is this happening?
Am I essentially doing (char)(0x00 + b)? Because
System.out.println((char) - b);
yields a different result.
Note: Using Java version 1.8.0_20
Why exactly is this happening?
If you put a unary - operator before a number or expression it negates it.
Similarly, if you put a unary + operator before a number or expression it does nothing.
A safer way to convert a byte to a char is
char ch = (char)(b & 0xFF);
This will work for characters between 0 and 255, rather than 0 to 127.
BTW you can use unary operators to write some confusing code like
int i = (int) + (long) - (char) + (byte) 1; // i = -1;
b is a byte, and that be expressed as + b as well. For example, 3 can be written as +3 as well. So, ((char) + b) is same as ((char) b)
The + is the unary plus operator - like you can say that 1 is equivalent to +1, b is equivalent to +b. The space between + and b is inconsequential. This operator has a higher precedence than the cast, so after it's applied (doing nothing, as noted), the resulting byte is then cast to a char and produces the same result as before.
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
Can somebody explain me why the following piece of code fails to compile. The error is: "Possible loss of precision." :
byte a = 50;
byte b = 40;
byte sum = (byte)a + b;
System.out.println(sum);
Thank you.
Note that the cast has a higher precedence than the + operator. Your code does this:
byte a = 50;
byte b = 40;
byte sum = ((byte)a) + b;
System.out.println(sum);
The cast is redundant, since a is already a byte. You probably meant this:
byte a = 50;
byte b = 40;
byte sum = (byte) (a + b);
System.out.println(sum);
Because the two byte variables are operands to +, they are implicitly promoted to int. This is called Numeric Promotion. Because int is larger than byte, and the result of a + b yields int, casting to byte possibly chops off some bits, as int is larger than byte. Hence the "loss of precision"
Doc for implicit numeric promotion:
http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#170983
Doc for the size of types:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html
You did right by identifying that a cast is required, but unfortunately you did not apply it to the right expression due to precedence of operators.
Consider the following snippet:
static void f(char ch) {
System.out.println("f(char)");
}
static void f(int i) {
System.out.println("f(int)");
}
public static void main(String[] args) {
char ch = 'X';
f( (char) ch + 1 ); // prints "f(int)"
f( (char) (ch + 1) ); // prints "f(char)"
}
The cast has a higher precedence than the addition, which is why the snippet prints what it does. That is, the first call is equivalent to f( ((char) ch) + 1 );. The result of the addition is an int, which is why the f(int) overload is invoked.
The lesson here is that you should always use parenthesis unless you're doing a very simple cast. In general, always consider using parentheses to make the order of evaluation explicit, even if they're not necessary. They lead to a better, more readable code.
Bytes are added using "int" arithmetic; thus the result is an int and must be cast back from int to byte, which leads to the possibility of truncation.