#Arithmetic operation

17 messages · Page 1 of 1 (latest)

iron topaz
#

I'm trying to learn Java basics in an app, and while i've been doing fine understanding how the arithmetic itself works this code example they provided confused me a bit.

int x = 10
int y = x - 5; // y will equal 5
y = x / 4; // y will equal 2
y = x * 4; //y will equal 8
y = x % 3; // y will equal 1

My question is if int y = x - 5 is equal to 5, shouldnt the next declaration be 5/4 = 1.25 which is 1 instead of 10/4 = 2? Why does x still apply to the first line of y without the int declaration but the next two use the previous answer of y? This question is worded a bit weird, sorry about that.

"Why is it y = 10 / 4 instead of y = 5 / 4"

austere shadowBOT
#

This post has been reserved for your question.

Hey @iron topaz! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

pale rampart
#

A good way to read it is from right to left... So I would read the second line as follows:
calculate x - 5, which is 10 - 5 = 5. Take this value and store it in the variable y

#

x is not modified

#

Sorry i meant right to left

iron topaz
#

and then does the same for the last one

pale rampart
#

Im not sure where you got those outputs in your comments

#

I just ran the code and here are the results:

(x / 4) = 2
(x * 4) = 40
(x % 3) = 1
iron topaz
#

Its possible its an error in the writers explanation, i can send the app and the reference

pale rampart
#

That comment on the line y = x * 4; is incorrect

#

Everytime you say y = something you are overwriting what was already in y

iron topaz
#

It doesn’t actually explain that part, but in other languages i’ve learned theg don’t use the int, string etc declarations for variables so i was wondering if that made a different in the code execution but this is good to know i wasn’t losing my mind lol thank you

austere shadowBOT
pale rampart
#

In java you need to include the variable type when declaring it for the first time