programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Liutauras Vilda
• Tim Cooke
• Jeanne Boyarsky
• Paul Clapham
Sheriffs:
• Devaka Cooray
• Ron McLeod
• paul wheaton
Saloon Keepers:
• Tim Moores
• Piet Souris
• Tim Holloway
• Stephan van Hulst
• Carey Brown
Bartenders:
• Al Hobbs
• Frits Walraven
• Scott Selikoff

# Variable Assignment

Greenhorn
Posts: 3
• Number of slices to send:
Optional 'thank-you' note:
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?

author
Posts: 23928
142
• Number of slices to send:
Optional 'thank-you' note:

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

lowercase baba
Posts: 13081
67
• 1
• Number of slices to send:
Optional 'thank-you' note:
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.

Marshal
Posts: 76821
366
• Number of slices to send:
Optional 'thank-you' note:
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.

 Politics is a circus designed to distract you from what is really going on. So is this tiny ad: the value of filler advertising in 2021 https://coderanch.com/t/730886/filler-advertising