When you use a primitive type, when you assign a value to it, the previous value is "overwritten", so yes, it is literally lost, because variable values can change at any time.
When you work with objects, for example, let's say you have the class Auto
:
class Auto
{
// ...
}
And you assign a new instance:
Auto Toyota = new Auto(2005, "Camry"); // Año y Modelo
You have a new car placed in memory, if we do the following:
Auto OtroToyota = Toyota;
The new variable OtroToyota
points to the reference of the new instance that we created previously, which means that when changing any value in any of the instances, this value is changed in all the references that you have towards that object, example :
Toyota.Modelo = "Corolla";
System.out.print(OtroToyota.Modelo); // Debe imprimir "Corolla"
// O por lo menos este es el comportamiento estimado en C#, en Java debe parecerse.
So yes, your concept is true to the point that you point to the instance defined with the keyword new
. If you assign null
to one of the 2, the other (and all other pointers to that instance) will be affected.
See the following implementation as an example:
public class Auto {
// Implementación de la clase Auto (ejemplo):
public int Year;
public Auto(int y) { Year = y; }
}
public static void main(string []args) {
Auto Camry = new Auto(1994);
Auto Toyota = Camry;
System.out.println(Camry.Year); // Imprime 1994
Toyota.Yr = 1995;
System.out.println(Camry.Year); // Imprime 1995
System.out.println(Toyota.Year); // Imprime 1995
}
Then, your answer finally summarized is "Yes", but "copies" of instances in pointers are not kept (Or at least that is what I understand) .