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.
Related
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.
I have just started taking a Computer Science class online and I am quite new to Programming(a couple of week's worth of experience). I am working on an assignment, but I do not understand what a mystery method is. I have yet to find an answer that I can wrap my head around online, in my textbook, or from my professor. Any explanation using this code as an example would also be greatly appreciated!
This is the equation where I saw it in:
public static void mystery1(int n) {
System.out.print(n + " ");
if (n > 0) {
n = n - 5;
}
if (n < 0) {
n = n + 7;
} else {
n = n * 2;
}
System.out.println(n);
}
If anybody can help, that would be amazing! Thank you!
First of all, I voted your question up because I think it's a valid question for someone who is just beginning in computer programming, and I think that some people fail to understand the significance and purpose of Stack Overflow, which is to help programmers in times of need.
Secondly, I think that the couple of users that have commented on your post are on the right track. I have personally never heard of a mystery method, so I think the goal here is for you to simply figure out what the method does. In this case, the method takes a parameter for int 'n'. This means that if, at any point in the application, the 'mystery1()' method is called, an integer will have to be passed as the variable.
Let's say that a user enters the number '9'. The method would be called by the code mystery1(9). This would then run the first part of the 'if' statement, because n is greater than 0. So, n would be equal to n - 5, or 9 - 5, which is 4. (So, n=4.)
I hope my answer was somewhat helpful to you. Take care.
Your assignment is probably to figure out what this method does. More specifically, what does it print to the screen. I'll walk you through how to figure this out.
You have a function, also called a methood, called mystery1. A function is just a named block of code that you can use throughout other pieces of code. This function takes an integer argument called n. Let's assume n=12 for this example.
The first thing that happens in your function when it is called is that n is printed out via the System.out.print method. Notice that it prints a blank space after it. Notice also at the end it prints another value of n that gets assigned within the method. So the method is going to print "12 ?" without the double quotes. The question mark is what we have to figure out. The code says if n > 0 then n = n-5. Since 12 is greater than 0, n gets the new value of 7. The next if statement says if n is less than 0, n gets assigned n+7. But it is not less than zero, it is 7 at this point, so we move to the else statement. In this statement n gets multiplied by 2 which is 14. So the last statement prints 14.
So for an input value of 12 this method prints:
12 14
I hope this helps. If not, please give more detail about your assignment and what you don't understand about my explanation.
The point of this kind of exercise is that you are given a method, but they don't tell you what it does (hence the "mystery"). You are supposed to figure out what it does on your own (like "solving the mystery"). It doesn't mean that the method is special in any way.
Say I give you a "mystery" method like this:
public static void mystery(int n) {
System.out.println(n+1);
}
You would "solve the mystery" by telling me that this method prints out the number that comes after n. Nothing else is special here.
In the example you gave, your job would be to tell me why the method prints out 0 0 when n = 0, or 6 2 when n = 6.
I think the usage of the term "mystery method" is rather misleading, as it has clearly made you (and many, many, many others) believe that something about these methods is special and something that you need to learn about. There isn't anything special about them, and there's nothing to learn.
I think a lot of people would understand this better if instructors just said "tell me what this method does" instead of trying treat students like 5 year olds by saying "Here's a mystery method (ooh, fancy and entertaining). Can you play detective and solve the mystery for me?"
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.
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.
I'm trying to remember some crazy java array trickery I came over in a certification exam. This was a couple of years ago and I'm a bit fuzzy on the details.
It goes something like this:
int[] a = {4,2,1}
int i = a[ a[0] = 0 ]
This is of course total bollocks but the question tried to show that an array saves it's state when it's accessed. So if I actually got it right I expected 'i' to equal 4 still, but as shown when run 'i' gets the new value 0.
The certification was for java 6 and I checked thats still what I'm running here (1.6.0_51 to be precise). Is it changed in some way or is my memory just completely off?
Thank you for indulging me in this, in reality, rather meaningless question :)
edit: I would never ever suggest to use or use this sort of weird thing in real code.
what about official documentaion?
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.13.1
15.13.1 read it =)
int i = a[ a[0] = 0 ]
is equal to -
a[0] = 0 // this assignment change the index 0 value to 0 - {0,2,1}
int i = a[ 0 ] // this 0 comes from assignment operation which is assigned value.
so the result is 0.