Order of operations in i=i++; [duplicate] - java

This question already has answers here:
Why this giving me 0? [duplicate]
(7 answers)
Closed 8 years ago.
Understanding the difference between ++i and i++, the below example still feels counter-intuitive.
Could someone please explain the order of operations and assignments in the following example?
int i = 0;
i = i++;
System.out.println(i); // 0
Namely on line two, why is i not incremented after the assignment?

The simple way to see it is like this:
Step 1: Your int i = 0; line, which (of course) does this:
i = 0
Then we come to the i = i++; line, where things get interesting. The right-hand side of the = is evaluated, and then assigned to the left-hand side. So let's look at the right-hand side of that, i++, which has two parts:
Step 2:
temporary_holder_for_value = i
The value of i is read and stored away in a temporary location (one of the virtual machine registers, I expect). Then the second part of i++ is done:
Step 3:
i = i + 1
Now we're done with the right-hand side, and we assign the result to the left-hand side:
Step 4:
i = temporary_holder_for_value
The key is that last step. Basically, everything to the right of the = is done first, and the result of it is then assigned to the left. Because you used a post-increment (i++, not ++i), the result of the expression on the right takes i's value before the increment. And then the last thing is to assign that value to the left-hand side.

Related

I need help in trying to fully understand the concept of recursion [duplicate]

This question already has answers here:
Understanding recursion [closed]
(20 answers)
Closed 5 years ago.
Before you get started, I have used google countless times in hopes of searching for a very brief and simple explanation of how recursion works when it has a return type. But I guess I'm not as bright as I thought since i still cant understand it quite well.
Take the following code snippet (in java) as an example
public static int recursion(int num)
{
int result;
if (num == 1)
result = 1;
else
result = recursion(num - 1) + num;
return result;
}
I grabbed this code from my professors lecture slide and he said this will return 1 + 2 + 3 + ... + num.
I just need someone to explain how the process works in the method that i provided. Maybe a step by step approach might help me understand how recursion works.
recursion(5) = recursion(4) + 5, let's figure out recursion(4) and come back to this later
recursion(4) = recursion(3) + 4, let's figure out recursion(3) and come back to this later
recursion(3) = recursion(2) + 3, ...
recursion(2) = recursion(1) + 2, ...
recursion(1) = 1, we know this!
recursion(2) = 1 + 2, now we can evaluate this
recursion(3) = (1+2) + 3, and now we can evaluate this
recursion(4) = (1+2+3) + 4, ...
recursion(5) = (1+2+3+4) + 5, the answer to our original question
Note: Without knowing recursion(1), we'd have gone to 0, -1, -2, and so on until forever. This known quantity is called the base case and it is a requirement for recursion.
Basically when there is a stack buildup for each item that is created beyond the last iteration. (Where num=1)
When n>1 the if statement kicks the iteration to the else which 'saves' the result in a stack and calls the same funtion again with n-1
what this effectively does is keep calling the same function until you hit your designated 'base case' which is n=1
Recursion is all about solving a problem by breaking it into a smaller problem. In your case, the question is "how do you sum the numbers from 1 to n", and the answer is "sum up all the numbers from 1 to n-1, and then add n to it". You've phrased the problem in terms of a smaller or simpler version of itself. This often involves separating out a "base case"—an irreducibly simple problem with a straightforward answer.
public static int recursion(int num)
{
int result;
if (num == 1)
result = 1; // Base case: the sum of the numbers from 1 to 1 is 1.
else
result =
// This is the sum of numers from 1 to n-1. The function calls itself.
recursion(num - 1)
// Now add the final number in the list, and return your result.
+ num;
return result;
}
You're defining the unsolved problem in terms of itself, which works because the solution always involves either the base case or a simpler version of the problem (which itself further involves either the base case or an even simpler version of the problem).
I'll close with one of my favorite jokes:
How do you explain recursion to a five-year-old?
You explain recursion to a four-year-old, and wait a year.
Going by the classic code example you posted. if you call your method like so with number passed in as 5:
recursion(5);
In layman terms just to understand, your function will create & call another copy of your function in the else block as below:
recursion(4);
and then
recursion(3);
recursion(2);
recursion(1);
as the number keeps decrementing.
Finally it will call the if part in the final copy of the method as num will satisfy num == 1. So from there it starts unwinding & returning each value to the previous call.
As each method call has its own stack to load method local variables on, there will be n number of stacks created for n calls. When the deepest call in recursion is made, then the stacks start unwinding. Hence recursion achieved
The most important thing however to note is that there is a base-most call in your code, which is done at 1 just because you have the check if (num == 1). Else it would be infinite recursion & of course a fatal & wrong program to write. The base-most call is from where its called as stack unwinding in recursion terms.
Example: Finding the factorial of a number is the most classic examples of recursion.
Performance: Do look into recursion vs iteration and recursion vs looping to see what are the performance impacts of recursion

JAVA trying to find positions of the year. Not Working [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I have a small program that reads a json file that gives the
weather, time, temp, wind, ect. I need to calculate the average
tempature for 2009 through 2015. The years are in an array, and are in
length, around 60k. I am trying to write a small loop that will first
find the position of the first instance of the year 2009 and then
the last instance of the year 2009. Then I can run my
average temp loop through that, but I am running into an issue as seen
below.
place will be the index of the array. However, no matter how I run my
code, it always equals -1, rather than giving me the position of
the index in the array. Both arguments in the if statements are
strings.
So what am I doing wrong?
String twozerozeronine = "2009";
int place = -1;
for (int a = 0; a < years.size(); a++){
if (years.get(a) == twozerozeronine){
place = 1;
break;
}
}
System.out.println(place);
years.get(a) == twozerozeronine
checks whether the object on the left side of the operator and the object on the right side of the operator are the very same. In your case they might be similar, but will never be the very same.
You will need to check whether they are similar instead:
years.get(a).equals(twozerozeronine)
You can use equals() method to compare the value of the Strings.
Like: if ( years.get( a ).equals( twozerozeronine ) ){
The == operator compares the Object references (in your case, both are not equal) whereas equals() method compares the actual string values (in your case, the string values are "2009").

Variable expected [duplicate]

This question already has answers here:
Why doesn't the post increment operator work on a method that returns an int?
(11 answers)
Closed 5 years ago.
private void calculateForEachQuestion() {
...
if (questions.size() >= answers.size()) {
answers.forEach(answer -> {
if (questions.contains(answer))
this.answer.setPoints((this.answer.getPoints())++);
// Variable expected ^
});
}
The error I encountered is:
unexpected type
required: variable
found: value
What is wrong with the statement?
this.answer.setPoints((this.answer.getPoints())++);
The ++ operator only makes sense when applied to a declared variable.
This operator will add one to an integer, long, etc. and save the result to the same variable in-place.
If there is no declared variable, there is nowhere to save the result, which is why the compiler complains.
One way to allow use of the ++ operator in this situation would be (not the most concise code, but to illustrate the point):
int myVariable = this.answer.getPoints();
myVariable++;
this.answer.setPoints(myVariable);
this.answer.getPoints() will return a value, and you can't use increment ++ or decrement -- on that. You can only use it on variables.
If you want to add 1 to it, you can do it as:
this.answer.setPoints((this.answer.getPoints())+1);
I know that, but why?
You can do this:
int x = 5;
x++; // x is a variable and can have value 6
but not this:
5++; // 5 is a value and can't have value 6
Change this:
this.answer.setPoints((this.answer.getPoints())++);
to:
this.answer.setPoints((this.answer.getPoints())+1);
++ will increment a variable with 1, but since this.answer.getPoints() will return a value and its not a defined variable, it won't be able to store the incremented value.
Think of it like doing:
this.answer.getPoints() = this.answer.getPoints() + 1, where would the incremented value be stored?
The error is just in this bit:
(this.answer.getPoints())++
The first part of this (this.answer.getPoints()) creates an rvalue: effectively, an anonymous variable that lasts almost no time.
The second part ++ increments that anonymous variable after it is passed into setPoints().
Then, the anonymous variable (now incremented) is thrown away.
The compiler/IDE knows that you're doing something that will never be used (incrementing a temporary value), and is flagging it.

Java: Unexpected Type Error [duplicate]

This question already has answers here:
Replace a character at a specific index in a string?
(9 answers)
Closed 8 years ago.
Can someone help me understand why I'm getting an "Unexpected Type Error"?
if(s.charAt(i-1) == ' '){
String sub = s.substring(i, s.indexOf(' ')+1);
for(int j = 0; j < sub.length()/2; j++){
char temp;
temp = sub.charAt(j);
sub.charAt(j) = sub.charAt(sub.length()-1-j);
sub.charAt(sub.length()-1-j) = temp;
sub = sub+" ";
complete = complete+sub;
}
}
I'm getting the error on lines 6 and 7. I can't figure out why and I'd appreciate the help!
charAt() returns the character. It is not a left side operand aka you cannot assign a value to it.
Strings are immutable, which means you cannot change them (this seems to be your intention).
Instead: create a new String and add to that.
If this confused you, I try to elaborate a little: the assignment operator takes whatever is on the right and tries to shove it into whatever is on the left of it.
The problem here is that some things do not like it when you try to shove other things into them. You cannot put everything on the left that you want. Well, you can try:
"everything" = 5;
but this does not work, neither does this:
"everything" = 42;
Set aside what that last snippet failing implies to the universe and everything, your problem at hand is that charAt() is also one of those things that do not like it on the left side of the assignment operator.
I'm afraid there's no way to turn charAt() into one of those things that like it on the left side. A week after stranding on a deserted island without any plants but only solar powered refrigerators filled with steaks, this probably works:
vegetarian = meat;
Even though the vegetarian doesn't like it there, he'd accept his situation being on the left side of the = operator. He eats some steaks.
This does not hold true for what you are trying, though. There's no such deserted island for charAt().
In these lines you're trying to set the value of functions' return. This is illegal
sub.charAt(j) = sub.charAt(sub.length()-1-j);
sub.charAt(sub.length()-1-j) = temp;
as far as I see you're trying to change the characters of a String, but Strings are imutable objects. So you'll need to use a StringBuffer to set the values.

post increment behaviour [duplicate]

This question already has answers here:
What is x after "x = x++"?
(18 answers)
Closed 9 years ago.
i have small doubt.why the below code is printing value i=2.
int i=2;
i=i++;
System.out.println(i);
can someone please explain me what is happening in line no 2.
so there is no meaning here of doing ++ here?
Thanks
i=i++;
Because first the assignment happens, then the increment applies.
Something like:
first i gets 2, then ++ operation happens, but results won't be re-assigned to i, so i value will remain as 2.
i = i++; first evaluates the i++ expression, which increments i and evaluates to the value of i prior to the increment. Since you immediately assign to i this value, it resets the value of i so the increment appears to never have happened. i = ++i; would cause the other behavior.
When you are telling i=i++; you are telling the computer to assign i to i, and after that, increment i's value, but it will not affect i, because i's value is 2.
The correct way to do it should be i=++i; meaning, add 1 to i before assigning it to i, or you could simply use i++;
Thanks to all for helping me in understanding the things which was of great value.
I found somewhere nice post on this.
I got the answer from the suggestion given by stackoverflow forum only but there was some clear explanation missing what I feel.
Miljen Mikic suggested link is not working and saying page not found.
Some Clear explanation given for problem below is
int a=2, b=2;
int c = a++/b++;
System.out.println(c);
disassembles to the following.
0:iconst_2 ; [I]Push the constant 2 on the stack[/I]
1:istore_1 ; [I]Pop the stack into local variable 1 (a)[/I]
2:iconst_2 ; [I]Push the constant 2 on the stack, again[/I]
3:istore_2 ; [I]Pop the stack into local variable 2 (b)[/I]
4:iload_1 ; [I]Push the value of a on the stack[/I]
5:iinc1, 1 ; [I]Add 1 to local variable 1 (a)[/I]
8:iload_2 ; [I]Push the value of b on the stack[/I]
9:iinc2, 1 ; [I]Add 1 to local variable 2 (b)[/I]
12:idiv ; [I]Pop two ints off the stack, divide, push result[/I]
13:istore_3 ; [I]Pop the stack into local variable 3 (c)[/I]
14:return
which help me understand much better.
Please add to this If I am wrong in my point.
Thanks for all your answers.

Categories

Resources