Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Variable Assignment  RSS feed

 
Samir Raut
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In this small program I was expecting the output to be 11. Since there is y = x and later x has a new value assigned. Why is it 5? Can someone explain it to me? What it the fundamentals behind it?

 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Samir Raut wrote:In this small program I was expecting the output to be 11. Since there is y = x and later x has a new value assigned. Why is it 5? Can someone explain it to me? What it the fundamentals behind it?


Line 5. X=5. And Y have yet to be declared.

Line 6. X=5, so Y=5.

Line 7. X=11. And Y remains unchanged (still equal 5).

Can you show us why Y should be 11?

Henry
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The transitive property doesn't apply in programming - at least, not across distinct lines of code.

mathematically, you may thing that
y = x
x = 11
therefore,
y = x = 11

But that's not now programs work. When you write

int x = 5

you get a hunk of memory that can hold a value. You can refer to it with the variable name "x", and you store the value 5 in it.

You then write

int y = x;

you get ANOTHER hunk of memory that can hold a value. You can refer to it with the variable name "y", and you store the value in it that is stored in the memory you refer to by "x". So now, you have two hunks of memory, and each holds the value 5.

when you then say

x = 11

you are saying "change the value in that first memory hunk to now hold the value 11". This does nothing to what's stored in that second chunk.
 
Campbell Ritchie
Marshal
Posts: 55717
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also we are using the wrong symbol. We should use ≔ for assignment whereas Java┬« uses the = sign (as do many other languages). The = should mean equality, but it doesn't.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!