Java inline int swap. Why does this only work in Java - java

I was asked to write a swap without using temp variables or using xor and i came up with this.
In Java, this works, but in C/C++ this does not work.
I was under the impression that this would always work since the value of 'a' on the left side of the '|' would be stored in a register and then the assignment to 'a' would occur negating the effect on the assigned value for 'b'.
int a = 5;
int b = -13;
b = a | (0 & (a = b));

You are modifying a variable and reading its value without an intervening sequence point.
b = a + 0 * (a = b);
// reading a's value modifying a
This is undefined behavior. You have no right to any expectations on what the code will do.

The C/C++ compiler optimizes the expression 0 * (a = b) to simply 0 which turns your code fragment into:
int a = 5;
int b = -13;
b = a;

In C/C++, assigment are performed in the order of expression. In Java, assignments occur last regardless of other expressions.
e.g. This increments in C but does nothing in Java.
a = a++;

Related

byte y=y+x; Results in error but y+=x; Compiles successfully. Why? [duplicate]

Until today, I thought that for example:
i += j;
Was just a shortcut for:
i = i + j;
But if we try this:
int i = 5;
long j = 8;
Then i = i + j; will not compile but i += j; will compile fine.
Does it mean that in fact i += j; is a shortcut for something like this
i = (type of i) (i + j)?
As always with these questions, the JLS holds the answer. In this case §15.26.2 Compound Assignment Operators. An extract:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
An example cited from §15.26.2
[...] the following code is correct:
short x = 3;
x += 4.6;
and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);
In other words, your assumption is correct.
A good example of this casting is using *= or /=
byte b = 10;
b *= 5.7;
System.out.println(b); // prints 57
or
byte b = 100;
b /= 2.5;
System.out.println(b); // prints 40
or
char ch = '0';
ch *= 1.1;
System.out.println(ch); // prints '4'
or
char ch = 'A';
ch *= 1.5;
System.out.println(ch); // prints 'a'
Very good question. The Java Language specification confirms your suggestion.
For example, the following code is correct:
short x = 3;
x += 4.6;
and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);
Yes,
basically when we write
i += l;
the compiler converts this to
i = (int)(i + l);
I just checked the .class file code.
Really a good thing to know
you need to cast from long to int explicitly in case of i = i + l then it will compile and give correct output. like
i = i + (int)l;
or
i = (int)((long)i + l); // this is what happens in case of += , dont need (long) casting since upper casting is done implicitly.
but in case of += it just works fine because the operator implicitly does the type casting from type of right variable to type of left variable so need not cast explicitly.
The problem here involves type casting.
When you add int and long,
The int object is casted to long & both are added and you get long object.
but long object cannot be implicitly casted to int. So, you have to do that explicitly.
But += is coded in such a way that it does type casting. i=(int)(i+m)
In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign:
byte -> short -> int -> long -> float -> double.
The same will not work the other way round. For example we cannot automatically convert a long to an int because the first requires more storage than the second and consequently information may be lost. To force such a conversion we must carry out an explicit conversion.
Type - Conversion
Sometimes, such a question can be asked at an interview.
For example, when you write:
int a = 2;
long b = 3;
a = a + b;
there is no automatic typecasting. In C++ there will not be any error compiling the above code, but in Java you will get something like Incompatible type exception.
So to avoid it, you must write your code like this:
int a = 2;
long b = 3;
a += b;// No compilation error or any exception due to the auto typecasting
The main difference is that with a = a + b, there is no typecasting going on, and so the compiler gets angry at you for not typecasting. But with a += b, what it's really doing is typecasting b to a type compatible with a. So if you do
int a=5;
long b=10;
a+=b;
System.out.println(a);
What you're really doing is:
int a=5;
long b=10;
a=a+(int)b;
System.out.println(a);
Subtle point here...
There is an implicit typecast for i+j when j is a double and i is an int.
Java ALWAYS converts an integer into a double when there is an operation between them.
To clarify i+=j where i is an integer and j is a double can be described as
i = <int>(<double>i + j)
See: this description of implicit casting
You might want to typecast j to (int) in this case for clarity.
Java Language Specification defines E1 op= E2 to be equivalent to E1 = (T) ((E1) op (E2)) where T is a type of E1 and E1 is evaluated once.
That's a technical answer, but you may be wondering why that's a case. Well, let's consider the following program.
public class PlusEquals {
public static void main(String[] args) {
byte a = 1;
byte b = 2;
a = a + b;
System.out.println(a);
}
}
What does this program print?
Did you guess 3? Too bad, this program won't compile. Why? Well, it so happens that addition of bytes in Java is defined to return an int. This, I believe was because the Java Virtual Machine doesn't define byte operations to save on bytecodes (there is a limited number of those, after all), using integer operations instead is an implementation detail exposed in a language.
But if a = a + b doesn't work, that would mean a += b would never work for bytes if it E1 += E2 was defined to be E1 = E1 + E2. As the previous example shows, that would be indeed the case. As a hack to make += operator work for bytes and shorts, there is an implicit cast involved. It's not that great of a hack, but back during the Java 1.0 work, the focus was on getting the language released to begin with. Now, because of backwards compatibility, this hack introduced in Java 1.0 couldn't be removed.

Whats the difference between r += x and r = r + x [duplicate]

Until today, I thought that for example:
i += j;
Was just a shortcut for:
i = i + j;
But if we try this:
int i = 5;
long j = 8;
Then i = i + j; will not compile but i += j; will compile fine.
Does it mean that in fact i += j; is a shortcut for something like this
i = (type of i) (i + j)?
As always with these questions, the JLS holds the answer. In this case §15.26.2 Compound Assignment Operators. An extract:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
An example cited from §15.26.2
[...] the following code is correct:
short x = 3;
x += 4.6;
and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);
In other words, your assumption is correct.
A good example of this casting is using *= or /=
byte b = 10;
b *= 5.7;
System.out.println(b); // prints 57
or
byte b = 100;
b /= 2.5;
System.out.println(b); // prints 40
or
char ch = '0';
ch *= 1.1;
System.out.println(ch); // prints '4'
or
char ch = 'A';
ch *= 1.5;
System.out.println(ch); // prints 'a'
Very good question. The Java Language specification confirms your suggestion.
For example, the following code is correct:
short x = 3;
x += 4.6;
and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);
Yes,
basically when we write
i += l;
the compiler converts this to
i = (int)(i + l);
I just checked the .class file code.
Really a good thing to know
you need to cast from long to int explicitly in case of i = i + l then it will compile and give correct output. like
i = i + (int)l;
or
i = (int)((long)i + l); // this is what happens in case of += , dont need (long) casting since upper casting is done implicitly.
but in case of += it just works fine because the operator implicitly does the type casting from type of right variable to type of left variable so need not cast explicitly.
The problem here involves type casting.
When you add int and long,
The int object is casted to long & both are added and you get long object.
but long object cannot be implicitly casted to int. So, you have to do that explicitly.
But += is coded in such a way that it does type casting. i=(int)(i+m)
In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign:
byte -> short -> int -> long -> float -> double.
The same will not work the other way round. For example we cannot automatically convert a long to an int because the first requires more storage than the second and consequently information may be lost. To force such a conversion we must carry out an explicit conversion.
Type - Conversion
Sometimes, such a question can be asked at an interview.
For example, when you write:
int a = 2;
long b = 3;
a = a + b;
there is no automatic typecasting. In C++ there will not be any error compiling the above code, but in Java you will get something like Incompatible type exception.
So to avoid it, you must write your code like this:
int a = 2;
long b = 3;
a += b;// No compilation error or any exception due to the auto typecasting
The main difference is that with a = a + b, there is no typecasting going on, and so the compiler gets angry at you for not typecasting. But with a += b, what it's really doing is typecasting b to a type compatible with a. So if you do
int a=5;
long b=10;
a+=b;
System.out.println(a);
What you're really doing is:
int a=5;
long b=10;
a=a+(int)b;
System.out.println(a);
Subtle point here...
There is an implicit typecast for i+j when j is a double and i is an int.
Java ALWAYS converts an integer into a double when there is an operation between them.
To clarify i+=j where i is an integer and j is a double can be described as
i = <int>(<double>i + j)
See: this description of implicit casting
You might want to typecast j to (int) in this case for clarity.
Java Language Specification defines E1 op= E2 to be equivalent to E1 = (T) ((E1) op (E2)) where T is a type of E1 and E1 is evaluated once.
That's a technical answer, but you may be wondering why that's a case. Well, let's consider the following program.
public class PlusEquals {
public static void main(String[] args) {
byte a = 1;
byte b = 2;
a = a + b;
System.out.println(a);
}
}
What does this program print?
Did you guess 3? Too bad, this program won't compile. Why? Well, it so happens that addition of bytes in Java is defined to return an int. This, I believe was because the Java Virtual Machine doesn't define byte operations to save on bytecodes (there is a limited number of those, after all), using integer operations instead is an implementation detail exposed in a language.
But if a = a + b doesn't work, that would mean a += b would never work for bytes if it E1 += E2 was defined to be E1 = E1 + E2. As the previous example shows, that would be indeed the case. As a hack to make += operator work for bytes and shorts, there is an implicit cast involved. It's not that great of a hack, but back during the Java 1.0 work, the focus was on getting the language released to begin with. Now, because of backwards compatibility, this hack introduced in Java 1.0 couldn't be removed.

Compilation error for the same statement? [duplicate]

Until today, I thought that for example:
i += j;
Was just a shortcut for:
i = i + j;
But if we try this:
int i = 5;
long j = 8;
Then i = i + j; will not compile but i += j; will compile fine.
Does it mean that in fact i += j; is a shortcut for something like this
i = (type of i) (i + j)?
As always with these questions, the JLS holds the answer. In this case §15.26.2 Compound Assignment Operators. An extract:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
An example cited from §15.26.2
[...] the following code is correct:
short x = 3;
x += 4.6;
and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);
In other words, your assumption is correct.
A good example of this casting is using *= or /=
byte b = 10;
b *= 5.7;
System.out.println(b); // prints 57
or
byte b = 100;
b /= 2.5;
System.out.println(b); // prints 40
or
char ch = '0';
ch *= 1.1;
System.out.println(ch); // prints '4'
or
char ch = 'A';
ch *= 1.5;
System.out.println(ch); // prints 'a'
Very good question. The Java Language specification confirms your suggestion.
For example, the following code is correct:
short x = 3;
x += 4.6;
and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);
Yes,
basically when we write
i += l;
the compiler converts this to
i = (int)(i + l);
I just checked the .class file code.
Really a good thing to know
you need to cast from long to int explicitly in case of i = i + l then it will compile and give correct output. like
i = i + (int)l;
or
i = (int)((long)i + l); // this is what happens in case of += , dont need (long) casting since upper casting is done implicitly.
but in case of += it just works fine because the operator implicitly does the type casting from type of right variable to type of left variable so need not cast explicitly.
The problem here involves type casting.
When you add int and long,
The int object is casted to long & both are added and you get long object.
but long object cannot be implicitly casted to int. So, you have to do that explicitly.
But += is coded in such a way that it does type casting. i=(int)(i+m)
In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign:
byte -> short -> int -> long -> float -> double.
The same will not work the other way round. For example we cannot automatically convert a long to an int because the first requires more storage than the second and consequently information may be lost. To force such a conversion we must carry out an explicit conversion.
Type - Conversion
Sometimes, such a question can be asked at an interview.
For example, when you write:
int a = 2;
long b = 3;
a = a + b;
there is no automatic typecasting. In C++ there will not be any error compiling the above code, but in Java you will get something like Incompatible type exception.
So to avoid it, you must write your code like this:
int a = 2;
long b = 3;
a += b;// No compilation error or any exception due to the auto typecasting
The main difference is that with a = a + b, there is no typecasting going on, and so the compiler gets angry at you for not typecasting. But with a += b, what it's really doing is typecasting b to a type compatible with a. So if you do
int a=5;
long b=10;
a+=b;
System.out.println(a);
What you're really doing is:
int a=5;
long b=10;
a=a+(int)b;
System.out.println(a);
Subtle point here...
There is an implicit typecast for i+j when j is a double and i is an int.
Java ALWAYS converts an integer into a double when there is an operation between them.
To clarify i+=j where i is an integer and j is a double can be described as
i = <int>(<double>i + j)
See: this description of implicit casting
You might want to typecast j to (int) in this case for clarity.
Java Language Specification defines E1 op= E2 to be equivalent to E1 = (T) ((E1) op (E2)) where T is a type of E1 and E1 is evaluated once.
That's a technical answer, but you may be wondering why that's a case. Well, let's consider the following program.
public class PlusEquals {
public static void main(String[] args) {
byte a = 1;
byte b = 2;
a = a + b;
System.out.println(a);
}
}
What does this program print?
Did you guess 3? Too bad, this program won't compile. Why? Well, it so happens that addition of bytes in Java is defined to return an int. This, I believe was because the Java Virtual Machine doesn't define byte operations to save on bytecodes (there is a limited number of those, after all), using integer operations instead is an implementation detail exposed in a language.
But if a = a + b doesn't work, that would mean a += b would never work for bytes if it E1 += E2 was defined to be E1 = E1 + E2. As the previous example shows, that would be indeed the case. As a hack to make += operator work for bytes and shorts, there is an implicit cast involved. It's not that great of a hack, but back during the Java 1.0 work, the focus was on getting the language released to begin with. Now, because of backwards compatibility, this hack introduced in Java 1.0 couldn't be removed.

Java variable may not have been initialized

I'm working on Project Euler Problem 9, which states:
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
Here's what I've done so far:
class Project_euler9 {
public static boolean determineIfPythagoreanTriple(int a, int b, int c) {
return (a * a + b * b == c * c);
}
public static void main(String[] args) {
boolean answerFound = false;
int a, b, c;
while (!answerFound) {
for (a = 1; a <= 1000; a++) {
for (b = a + 1; b <= 1000; b++) {
c = 1000 - a - b;
answerFound = determineIfPythagoreanTriple(a, b, c);
}
}
}
System.out.println("(" + a + ", " + b + ", " + c + ")");
}
}
When I run my code, I get this error:
Project_euler9.java:32: error: variable a might not have been initialized
System.out.println("The Pythagorean triplet we're looking for is (" + a + ", " + b + ", " + c + ")");
Note: I get this for each of my variables (a, b, and c) just with different line numbers.
I thought that when I declared a, b, and c as integers, the default value was 0 if left unassigned.
Even if this weren't the case, it looks to me like they all do get assigned, so I'm a bit confused about the error.
Why is this happening?
Instance variables (in your case, they would be integers) are assigned to 0 be default. Local variables not. (From Java Docs)
If the loop is not entered, then your variables won't be initialized, that's the reason of the error.
What you can do is initialize them when declaring:
int a=0, b=0, c=0;
Your problem is this line:
System.out.println("(" + a + ", " + b + ", " + c + ")");
which is after the while (!answerFound) {...} loop. The compiler thinks that there may be a case where one or more of the variables a, b or c isn't initialised.
Use this line:
int a=0, b=0, c=0;
when declaring the variables, so that they are initialised when declared, and the error should go away.
Do this, at the beginning of the method after the local variables are declared:
a = b = c = 0;
The error is basically stating that Java can't be sure that the variables have a value assigned when they reach the System.out.println(). Remember: in Java only attributes have default values, all local variables must be explicitly initialized at some point.
You're right and wrong in your thinking:
Where you're right:
Yes, uninitialized variables may be assigned a value by the compiler, but a) it is considered bad style, b) You shouldn't depend on it, c) That does not apply to local variables (as declared in a method)
Where you are wrong:
Local variables are not assigned a default value, only instance variables.
For reference, take a look at The docs:
Default Values
It's not always necessary to assign a value when a field is declared.
Fields that are declared but not initialized will be set to a
reasonable default by the compiler. Generally speaking, this default
will be zero or null, depending on the data type. Relying on such
default values, however, is generally considered bad programming
style.
The following chart summarizes the default values for the above data
types.
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d char '\u0000' String (or any object) null
boolean false
Local variables are slightly different; the compiler never assigns a
default value to an uninitialized local variable. If you cannot
initialize your local variable where it is declared, make sure to
assign it a value before you attempt to use it. Accessing an
uninitialized local variable will result in a compile-time error.
When you declare local variables in a method, you have to assign them values before use them.
The Java compiler has to be convinced that when we get to the line HERE, it can prove that a, b, and c have been set to something:
boolean answerFound = false;
int a, b, c;
while (!answerFound) {
for (a = 1; a <= 1000; a++) {
for (b = a + 1; b <= 1000; b++) {
c = 1000 - a - b;
answerFound = determineIfPythagoreanTriple(a, b, c);
}
}
}
// HERE
From the compiler's point of view, if the loop is executed zero times, then it will get to HERE without the variables being initialized; therefore, you can't use them. We know that this is impossible, because we know that answerFound is initialized to false and therefore the loop will be executed at least once, and also that each for loop will be executed at least once. But the language has to have consistent rules to determine which programs are legal and which ones aren't; in order to keep things from being overly complex, the compiler isn't required to make the kinds of deductions that would be necessary to prove that a, b, and c are always initialized. I haven't looked at the actual "definite assignment" rules in detail, but I think they're already fairly complex.
So even though you know that the variables will be initialized, you can't convince the compiler of that. So just initialize them when they're declared.
int a = 0, b = 0, c = 0;
By the way, since the while is outside the for loops, this code will not exit right away when answerFound becomes true. It still executes the for loops until they're done, and only then does it test to see whether to leave the while loop. You'll need to solve that.
P.S. If you want to cheat, note that every Pythagorean triple has the form a = m2 - n2, b = 2mn, c = m2 + n2, for some m and n. You could actually get the answer without a computer, using algebra. But go ahead and finish the program you started--it's great practice.
As others have pointed out your variables a, b, c may not have been initialized by the time you get to System.out.println. There are several ways to avoid this.
Initialize variables explicitly, so:
int a = 0;
Use a do...while loop, which ensures your loop is run at least once, so:
do {
[...]
} while (!answerFound);
Use loop-scoped variables, which avoid local-scoped variables hanging around, so:
for (int a = 1; a <= 1000; a++) {
[...]
}

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

Until today, I thought that for example:
i += j;
Was just a shortcut for:
i = i + j;
But if we try this:
int i = 5;
long j = 8;
Then i = i + j; will not compile but i += j; will compile fine.
Does it mean that in fact i += j; is a shortcut for something like this
i = (type of i) (i + j)?
As always with these questions, the JLS holds the answer. In this case §15.26.2 Compound Assignment Operators. An extract:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
An example cited from §15.26.2
[...] the following code is correct:
short x = 3;
x += 4.6;
and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);
In other words, your assumption is correct.
A good example of this casting is using *= or /=
byte b = 10;
b *= 5.7;
System.out.println(b); // prints 57
or
byte b = 100;
b /= 2.5;
System.out.println(b); // prints 40
or
char ch = '0';
ch *= 1.1;
System.out.println(ch); // prints '4'
or
char ch = 'A';
ch *= 1.5;
System.out.println(ch); // prints 'a'
Very good question. The Java Language specification confirms your suggestion.
For example, the following code is correct:
short x = 3;
x += 4.6;
and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);
Yes,
basically when we write
i += l;
the compiler converts this to
i = (int)(i + l);
I just checked the .class file code.
Really a good thing to know
you need to cast from long to int explicitly in case of i = i + l then it will compile and give correct output. like
i = i + (int)l;
or
i = (int)((long)i + l); // this is what happens in case of += , dont need (long) casting since upper casting is done implicitly.
but in case of += it just works fine because the operator implicitly does the type casting from type of right variable to type of left variable so need not cast explicitly.
The problem here involves type casting.
When you add int and long,
The int object is casted to long & both are added and you get long object.
but long object cannot be implicitly casted to int. So, you have to do that explicitly.
But += is coded in such a way that it does type casting. i=(int)(i+m)
In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign:
byte -> short -> int -> long -> float -> double.
The same will not work the other way round. For example we cannot automatically convert a long to an int because the first requires more storage than the second and consequently information may be lost. To force such a conversion we must carry out an explicit conversion.
Type - Conversion
Sometimes, such a question can be asked at an interview.
For example, when you write:
int a = 2;
long b = 3;
a = a + b;
there is no automatic typecasting. In C++ there will not be any error compiling the above code, but in Java you will get something like Incompatible type exception.
So to avoid it, you must write your code like this:
int a = 2;
long b = 3;
a += b;// No compilation error or any exception due to the auto typecasting
The main difference is that with a = a + b, there is no typecasting going on, and so the compiler gets angry at you for not typecasting. But with a += b, what it's really doing is typecasting b to a type compatible with a. So if you do
int a=5;
long b=10;
a+=b;
System.out.println(a);
What you're really doing is:
int a=5;
long b=10;
a=a+(int)b;
System.out.println(a);
Subtle point here...
There is an implicit typecast for i+j when j is a double and i is an int.
Java ALWAYS converts an integer into a double when there is an operation between them.
To clarify i+=j where i is an integer and j is a double can be described as
i = <int>(<double>i + j)
See: this description of implicit casting
You might want to typecast j to (int) in this case for clarity.
Java Language Specification defines E1 op= E2 to be equivalent to E1 = (T) ((E1) op (E2)) where T is a type of E1 and E1 is evaluated once.
That's a technical answer, but you may be wondering why that's a case. Well, let's consider the following program.
public class PlusEquals {
public static void main(String[] args) {
byte a = 1;
byte b = 2;
a = a + b;
System.out.println(a);
}
}
What does this program print?
Did you guess 3? Too bad, this program won't compile. Why? Well, it so happens that addition of bytes in Java is defined to return an int. This, I believe was because the Java Virtual Machine doesn't define byte operations to save on bytecodes (there is a limited number of those, after all), using integer operations instead is an implementation detail exposed in a language.
But if a = a + b doesn't work, that would mean a += b would never work for bytes if it E1 += E2 was defined to be E1 = E1 + E2. As the previous example shows, that would be indeed the case. As a hack to make += operator work for bytes and shorts, there is an implicit cast involved. It's not that great of a hack, but back during the Java 1.0 work, the focus was on getting the language released to begin with. Now, because of backwards compatibility, this hack introduced in Java 1.0 couldn't be removed.

Categories