explain why difference in the same code [duplicate] - java

This question already has answers here:
why same code in two technology behaving different [duplicate]
(3 answers)
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 9 years ago.
my code is :
code(){
int x=7;
x=x++;
output x; //prints 8 in C, prints 7 in Java
}
Guys the above code: prints 8 in C, and 7 in Java !!
Why is this so? please explain.

That will print 7 in Java. x=x++; is equivalent to :
int temp = x;
x = x + 1;
x = temp;
The result would have been different if you would have used prefix operator , ++x .
See for yourself over here: java code; C code.
Read Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…) to comprehend the output in C.

In Java, x=x++, is evaluated as:
int temp = x;
x = x + 1;
x = temp;
So, basically there is no change is x after that expression.
In C however, that expression is an Undefined Behaviour. Also see Sequence Points Wiki

This code cause undefined behaviour in C so the result may be any, 7, 8, 15 or Page fault. Why this code give 7, is compiler matter.

In the Java background, something like the following occurs (for the i = i++ statement):
int temp = i; // store current value of i
i = i + 1; // increase i because of i++
i = temp; // assign to i

x=x++;
This gives arbitrary results in C, mainly depending on compiler. Read about sequential points in C. You may refer to C Programming by Dennis ritchie.

it is because of operator precedence. = has more precedence in C than Java.

Related

Why are the precedence and associativity rules different in C and Java? [duplicate]

This question already has answers here:
Undefined behavior and sequence points
(5 answers)
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 9 months ago.
I found that the precedence and associativity rules are different in C, C++ and Java.
Have a look at this code snippet:
#include<stdio.h>
void main(){
int k = 5;
int x = ++k*k--*4;
printf("%d",x);
}
The above C program gives the output as 120
Look the following Java code:
class Main
{
public static void main(String args[])
{
int k = 5;
int x = ++k*k--*4;
System.out.println(x);
}
}
This Java code gives 144 as output.
Why this difference?
I think the Java evaluation strategy is correct because it is evaluated as (pre increment)6 * 6 (post decrement) *4 = 144
Then what's wrong with C and C++? C and C++ both give 120.
In Java, left to right evaluation of most operands, including side effects, is guaranteed.
C and C++ make no such guarantee. Except for ||, &&, ?: (the ternary operator) and , (the comma operator), the evaluation order of operands is unspecified, as is any side effects that may result.
In this case:
int x = ++k*k--*4;
The variable k is written to more than once without an intervening sequence point. This triggers undefined behavior.

What does * in front of = mean? [duplicate]

This question already has answers here:
Meaning of *= in Java
(4 answers)
Closed 4 years ago.
Hello everyone I have a very simple question that I just don't understand. I've tried googling it but haven't found a clear answer.
What is x after the following statements?
int x = 2;
int y = 1;
x *= y + 1;
I know that the answer is 4 but I don't understand why it is 4. Just need some clarity on what x* means exactly. Thanks!
I think this line is the one why you ask
x *= y + 1;
This is a shorthand for
x = x * (y + 1);
This works also with other operators like - and +, when the first variable is the same as the variable on the left side (which will be assigned).
Of course x is 4, if you don't understand the last statement, you can read it like this
x = x * y + 2
The x*= symbol means x=x* the result of whatever you put after the equals symbol.
x*= y+1 will turn to x = x * (y+1). The expresion you put after equals is evaluated first and then multiplied with x. The result will be cast to the type of the assignment variable (x).

Is there a post increment by more than one?

Just had an interesting thought. In languages like C# and Java, I know that when it comes to incrementing and decrementing, you can do a post, or pre-increment/decrement. Like this:
int a = 5;
Console.WriteLine(a++); // Would print out 5,
// And then increment a to 6
Console.WriteLine(++a); // Would then print out 7 because
// it increments a before printing it out
But, I was wondering if there is any such thing where one might do something like this:
int a = 5;
Console.WriteLine(a += 5); // Would print out 5,
// And then increment a to 10
Console.WriteLine(a =+ 5); // (Or something along those lines)
// To print out 15 at this point
Just interested and didn't really know where or how to look for the answer, so wondered if anyone on SO would know anything more about it. Thanks!
Edit: Added my question from the comments
Where exactly are a += 5 and a =+5 defined? I've never seen the second in use. Does it exist at all...? Do they compile to the same thing?
In the old days, the C language offered this syntax as a shortcut for adding or subtracting a value from a variable.
a =+ 5;
b =- 5;
But early on in the life of C, dmr (of blessed memory) and ken deprecated that syntax in favor of
a += 5;
b -= 5;
for precisely the same purpose, because it's far too easy to write b=-5 which means something entirely different from b -= 5. This "experienced" programmer remembers rewriting a bunch of code to match the new language spec.
So there has never been pre- or post- increment semantics in those constructions like there is in a++ or --b.
No. a += 5 isn't a post increment. It's an increment.
a++ is post-increment. And ++a is pre-increment.
The following prints the required results but is not exactly beautiful code:
int a = 5;
System.out.println(a+=5);
System.out.println((a+=5)-5);
System.out.println(a);
Prints:
10, 10, 15
a+=5 returns the value of a after the increment. (a+=5)-5 increments a and returns its value before the increment.
a=+5 just compiles to a=5. This performs assignment and the unary plus operator. It is akin to doing a=-5 (a equals negative 5).
System.out.println(+5);
Prints:
5
In C# the equivalent code generates the same output:
int a = 5;
Console.WriteLine(a+=5);
Console.WriteLine((a+=5)-5);
Console.WriteLine(a);
Console.WriteLine(+5);
Prints:
10, 10, 15, 5
There is no such operator in any language that I know of, but you can write your own C# function to do the same thing!
static void postAdd<T>(ref T lhs, T rhs) {
T saved = lhs;
lhs += rhs;
return saved;
}
This is not possible in Java because Java does not support pass-by-reference with ref.
Console.WriteLine(a+=5);
Is perfectly legal in the langauge. It is a sort of pre-increment operator in that it will increment the variable a before returning the value to the WriteLine call.
=+ isn't a valid operator since it isn't defined by the C# standard. All of the C# operators can be found on this page: https://msdn.microsoft.com/en-us/library/ewkkxkwb.aspx
Its not possible to create your own operators, because the compiler would have to know how to make expression trees or parse the line to generate the IL. The aside to this is that, by a lot of work and especially with the release of Rosyln, you could in theory make your own language (like IronPython) that had those operators.
The closest that you can come to your own operator are things like extension methods, for example:
public class Extensions
{
public static int AddMul(this int x, int add, int mull)
{
return x * mull + add;
}
}
which would be used like:
int x = 4;
int y = x.AddMul(2, 3); //y now equals 14

Autoboxing wth ++,-- operator in java [duplicate]

This question already has answers here:
Weird Integer boxing in Java
(12 answers)
Closed 8 years ago.
I am confuse about autoboxing unboxing in java. Please see my following two progarm.
Integer x = 400;
Integer y = x;
x++; x--;
System.out.println((x==y));
The output is false.
I known why the output is false. Because of autoboxing x.
Integer x = 100;
Integer y = x;
x++; x--;
System.out.println((x==y));
The output is true.
But the program is same as the upper. Why the output is true?
Please explain me detail.
Thank you very much.
This is because Integers -128 to 127 are cached, so in second example x and y refer to the same Integer instance.
Integer x = 100; // x refers to cached 100
x++;
is equivalent to
int var = x.intValue();
var++;
x = Integer.valueOf(var); // returns cached 100
See Integer.valueOf(int) API.

Getting different results for same thing [duplicate]

This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 9 years ago.
public class main {
public static void main(String[] args) {
int x=20,y=35;
x = y++ + x++;
y = ++y + ++x;
System.out.printf("%d %d\n",x,y);
}
//Output : 56,93
#include<stdio.h>
void main()
{
int x=20,y=35;
x = y++ + x++;
y = ++y + ++x;
printf("%d %d ",x,y);
}
//Output : 57 94
According to Operator Precedence Rules whatever output I got through Java code is right but when executing the same in 'C' code it incremented the output values by 1. I am using ubuntu 12.04 64-bit Operating System.
It's not the same thing because Java and C are different languages.
The behaviour of post increment in Java is defined as performing the increment after the expression has been evaluated.
The behaviour in C is undefined but often follows the order of precedence.
Note: order of evaluation and precedence are different things and this is more obvious for post increment/decrement and short cut boolean operations.
e.g.
Sting s = null;
if (s == null || !(s.length() > 0))
In this case ! has the highest precedence, but in reality will never be evaluated because the lower precedence || prevents it.
Precedence only determines where the implied brackets are, but only suggest how the expression might be evaluated.

Categories