Following snippet doesn't produce expected result - java

I found this in one of the Java programming quiz question.
public class Calculator {
public static void main(String[] args) {
int i = 0;
Calculator c = new Calculator();
System.out.print(i++ + c.opearation(i));
System.out.print(i);
}
public int operation(int i) {
System.out.print(i++);
return i;
}
}
Executing above snippet gives me the result of 121. I'm expecting it to be 111. I'll explain how I interpreted it.
+ addition operator would get executed from right to left (ref: operator precedence). So, c.operation(0) is invoked first and it prints the value 1 instead I'm expecting the value to be 0 since System.out.print prints the value of i first and then increments the i value since it is a post increment operator.
Secondly, the i value 1 is returned to the main and the statement System.out.print(i++ + 1) gets executed now. And since i has post increment operator it should have executed like 0 + 1 and produced the result 1 insted it printed result as 2.
Thirdly, the i value is now incremented to 1 and this gets printed as expected.
In short, I'm expecting the value to be printed as 011 but I got the result as 121. I'm not sure where my interpretation goes wrong.

Additive Operators
The additive operators have the same precedence and are syntactically
left-associative (they group left-to-right).
int i = 0;
System.out.print(i++ + c.operation(i));
evaluate i++, get left operand 0, and increment i to 1.
pass i(1) to c.operation(i), execute System.out.print(i++). Print 1 then return 2(right operand).
i++ + c.operation(i) ---> 0 + 2, print 2.
print 1.

Related

JAVA program always gives the wrong output for the first iteration and then works correctly [duplicate]

I was going through some exercises but I am confused in this one:
public static int f (int x, int y) {
int b=y--;
while (b>0) {
if (x%2!=0) {
--x;
y=y-2;
}
else {
x=x/2;
b=b-x-1;
}
}
return x+y;
}
What is the purpose of b=y--?
So, for example, x=5 and y=5
when we first go inside of while loop (while (b>0)) will b = 4 or 5? When I am running the code in my computer b is 5. And the return is 3. It is really unclear to me. Sorry if I am unclear in my question.
int b=y--; first assignes b=y and then decrements y (y--).
Also take a look at the prefix/postfix unary increment operator.
This example (taken from the linked page) demonstrates it:
class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
// prints 4
System.out.println(i);
++i;
// prints 5
System.out.println(i);
// prints 6
System.out.println(++i);
// prints 6
System.out.println(i++);
// prints 7
System.out.println(i);
}
}
The difference between a post-increment/decrement and a pre-increment/decrement is in the evaluation of the expression.
The pre-increment and pre-decrement operators increment (or decrement) their operand by 1, and the value of the expression is the resulting incremented (or decremented) value. In contrast, the post-increment and post-decrement operators increase (or decrease) the value of their operand by 1, but the value of the expression is the operand's original value prior to the increment (or decrement) operation.
In other words:
int a = 5;
int b;
b = --a; // the value of the expression --a is a-1. b is now 4, as is a.
b = a--; // the value of the expression a-- is a. b is still 4, but a is 3.
Remember that a program must evaluate expressions to do everything. Everything is an expression, even just a casual mention of a variable. All of the following are expressions:
a
a-1
--a && ++a
System.out.println(a)
Of course, in the evaluation of expressions, operator precedence dictates the value of an expression just as the PEMDAS you learned in grade school. Some operators, such as increment/decrement, have side effects, which is of course great fun, and one of the reasons why functional programming was created.
I believe b would equal 5 entering the loop because
b=y--;
When the "--" is behind the variable it decrements it after the action.
It's poor coding, as it can confuse new programmers.
The function, assuming it is passing by value, like in the example above (as opposed to passing by reference) takes a copy of y, decrements it, and assigns it to b. It does not alter the argument passed to the function when it was called.
Post increment
x++;
x += 1;
Post decrement
x--;
x -=1;
Pre increment : ++x;
Pre decrement : --x;
According to the Head First Java:
Difference between x++ and ++x :
int x = 0; int z = ++x;
Produces: x is 1, x is 1
in x = 0; int z = x++;
Produces: x is 1, z is 0

Post-Increment in Recursive Method? [duplicate]

This question already has answers here:
Post-increment and Pre-increment concept?
(14 answers)
Java: Prefix/postfix of increment/decrement operators
(11 answers)
Closed 6 years ago.
I'm trying to learn java oop and i find some problem understanding why the use of post-increment in Recursive Method cause error ? I don't understand .
Main Class :
public class Main {
public static void main(String[] args) {
A a = new A();
a.res(0);
}
}
Code work fine :
public class A {
public void res(int a){
if (a < 5)
res(a+1);
System.out.println(a);
}
}
Output : run:
5
4
3
2
1
0
BUILD SUCCESSFUL (total time: 0 seconds)
But in when i use the ++ operator i got StackOverflowError .
public class A {
public void res(int a){
if (a < 5)
res(a++);
System.out.println(a);
}
}
You are confusing a++ and ++a. As per java documentation - "The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value".
In your case the recursive method is always called with the argument 0
The post-increment operator increments the variable after you use it, so it will only increment the variable after the recursive function is returned.
Your code is doing this:
res(a++) //a = 0
//now a = 1
The recursion will never reach that next line, so the recursive function will always call res(0)
References: https://stackoverflow.com/a/2371162/7238307
Well... what do you expect, exactly? Let's re-write your program slightly. Your program (the one that crashes) can effectively be re-written like so, achieving the same effect (that is, crashing due to a StackOverflowError):
public class A {
public void res(int a){
if (a < 5) {
res(a);
++a;
}
System.out.println(a);
}
}
Your variable a will only increment after the recursive call to res has completed... which is never, because you're always invoking res with the same value.
This is how the recusrive calls are resolved with a+1.
a=0, res(0)
+ 0 < 5, res(1)
++ 1 < 5, res(2)
+++ 2 < 5, res(3)
++++ 3 < 5, res(4)
+++++ 4 < 5, res(5)
++++++ 5 = 5, print 5
+++++ print 4
++++ print 3
+++ print 2
++ print 1
+ print 0
Regarding the problem of your code with a++ is that the increment is performed after the the recursive call is performed. So you basically get:
a=0, res(0)
+ 0 < 5, res(0)
++ 0 < 5, res(0)
+++ ...

Why the Overrided function getting called first?

I executed the following program and I am curious about the output i got in which the function output is getting printed first even if it was the variable i tried to print first.
class Baap{
public int h = 4;
public int getH(){
System.out.println("Baap "+h); return h;
}
}
public class Beta extends Baap{
public int h = 44;
public int getH(){
System.out.println("Beta "+h); return h;
}
public static void main(String args[]){
Baap b = new Beta();
System.out.println(b.h+" "+b.getH());
Beta bb = (Beta)b;
System.out.println(bb.h+" "+bb.getH());
}
}
The output was as follows
Beta 44
4 44
Beta 44
44 44
Can somebody help me understand why the function block gets executed first?
Your System.out.println line prints a String.
The String is evaluated at run-time as b.h + " " + b.getH(), so it concatenates b.h, space and the result of the method b.getH(), so it calls getH() which prints Beta 44, then prints the result 4 44.
When you call a function, all of its parameters have to be evaluated first. In your case the only parameter to System.out.println is the expression b.h + " " + b.getH().
Since that is still an expression, the next step is to evaluate that expression, which means to determine the value of the expression. It consists of 2 plus operators which have 3 operands. In order to evaluate the plus operators the program has to evaluate the values of the operands.
The value of b.h evaluates to 4, because variables are resolved statically-ish in Java. The type of the variable b is Baap so we get 4.
The next value is " " which is already a literal so there's nothing to do.
After that we have the function call b.getH(). Function calls in Java are always resolved virtually, so we actually call the function called getH of the Beta type. This function only sees its own scope, where the variable h declared in the class Beta "shadows" the one declared in the class Baap, meaning the h variable of Baap is hidden to every member of Beta.
To evaluate the function call we have to execute the function which prints "Beta 44" and returns the value 44.
Now that we have values for all 3 operators we can evaluate the expression with the + operators. This results in the String "4 44" which now gets passed to System.out.println and finally printed on the screen.

Printing Recursively

I have this class the just prints an int:
class PRecursion {
public static void main(String[] args){
foo(1);
}
public static void foo(int x){
System.out.println("" + x);
if (x < 3)
foo(x+1);
System.out.println(""+x);
}
}
Output:
1
2
3
3
2
1
Why is it the is printing backwards then decrements?
It is not actually decrementing. What is happening is:
You are calling foo(1).
foo(1) does it's thing and starts a recursion.
Recursion goes on for how long you tell it to (foo(3) in your example)
After the recursion is done, foo(1) still has one statement to execute, and that is:
System.out.println(""+x);
hence you are seeing the print of foo(1) a second time, but after all other prints have been made. The same goes for every other time foo() is being called with a different number. So in the end it looks like it is decrementing, when really you are only printing a second time for the same value, in reverse order.
Try this:
class PRecursion {
public static void main(String[] args){
foo(1);
}
public static void foo(int x){
System.out.println("before " + x);
if (x < 3)
foo(x+1);
System.out.println("after "+x);
}
}
The second print statement doesn't decrement the input. What is happening is it leaves the call of foo(3) before it leaves the call of foo(2) and then finally `foo(1). So it executes the second print statements in the reverse of the order of the first.
If you read out the execution of the program as:
set x=1
print x (i.e. 1)
push x=1 on stack and set x=2 (this is how you can read foo(x+1))
print x (i.e. 2)
push 2 on stack and set x=3
print x (i.e. 3)
Don't push anything (x<3 is false)
print x again (i.e. 3)
pop x=2 off the stack
print x (i.e. 2)
pop x=1 of the stack
print x (i.e. 1)
stripping out the pushing and popping you get:
print 1
print 2
print 3
print 3
print 2
print 1
The value of x is not decrementing but it executes the remaining part of code which looks like decrementing.
System.out.println(" " + x); // 1 2 3
if (x < 3)
foo(x+1);
System.out.println(""+x); //3 2 1
due to recursion it calls the same function again and again and print only the first print statement until the if condition is true but at the end when if is false it stop executing foo(x+1) and exute the remaining print statements as the execution in the last step x is 3 so it prints 3 2 1 .
Maybe this could clear a bit more
Since all the foo(1)-->foo(2)-->foo(3) is executed causing output 1 2 3 the execution is in the last method foo(3) so it started executing the remaining method statement with flow like foo(3)-->foo(2)-->foo(1) printing the remaining print statement which executes looks like all the function backwards resulting in remaining 3 2 1.

Learning Java - Do not fully understand how this sequence is calculated (Fibonacci) in for loop [duplicate]

This question already has answers here:
Java recursive Fibonacci sequence
(37 answers)
Closed 8 years ago.
I am learning Java and I have this code from the internet and running it in Eclipse:
public class Fibonacci {
public static void main (String [] args) {
for (int counter = 0; counter <= 3; counter++){
System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter));
}
public static long fibonacci(long number) {
if ((number == 0) || (number == 1))
return number;
else
return fibonacci(number - 1) + fibonacci(number - 2);
}
}
I've tried to understand it but cannot get it. So I run through the code and counter gets passed in through the fibonacci method. As counter starts at 0 and this is what gets passed first, then 1 and I understand the method passes back 0 and then 1.
When it reaches 2: it will return 2-1 + 2-2 = 2 and it does return this.
When it reaches 3: it will return 3-1 + 3-2 = 3 but it does not return 3 it returns 2.
Please can someone explain to me why as I cannot figure this out?
Thanks
First, I have to tell you that this recursive version has a dramatic exponential cost. Once you understand how it works, my advice for you would be to learn about tail recursivity, write a tail-recursive solution, an iterative solution, and compare them to your current method for high values of "number".
Then, your function basically uses the mathematical definition of the Fibonacci sequence :
f0 = 1, f1 = 1, fn = fn-1 + fn-2 for all n >= 2
For example if we call fibonacci(3), this will return fibonacci(2) + fibonacci(1). fibonacci(2) will be executed first and will return fibonacci(1) + fibonnacci(0). Then fibonacci(1) will return immediately 1 since it is a terminal case. It happens the same thing with fibonnacci(0), so now we have computed fibonnacci(2) = 1 + 0 = 1. Let's go back to fibonacci(3) which has been partially evaluated at this point : 1 + fibonnacci(1). We just have to compute fibonnacci(1) and we can finally return 1 + 1 = 2.
Even in this little example, you can see that we evaluated twice fibonacci(1), that is why this version is so slow, it computes many times the same values of the sequence, and it gets worth when "number" is high.

Categories