CodeGym /Courses /New Java Syntax /Reference variables

Reference variables

New Java Syntax
Level 8 , Lesson 5
Available

"Hi, Amigo, it's me again, Ellie. Sorry for saying that over and over again, but it's customary on the Earth in the 31st century. I'd like to give you more details about reference variables and passing reference variables to functions (methods)."

"I'm ready."

"Great, then listen. Reference variables are any non-primitive variables. Such variables only contain an object reference (a reference to an object)."

"Primitive variables contain values, while reference variables store references to objects or null. Am I right?"

"Absolutely."

"What's a reference?"

"The relationship between an object and an object reference is like the relationship between a person and her phone number. The phone number isn't the person, but it can be used to call the person, ask for some information, manage her, or give orders. A reference is also used to work with objects. All objects interact with one another using references."

"As if they were talking to each other over the phone?"

"Exactly. When a primitive variable is assigned, the value is copied. If a reference is assigned, only the address of the object (the phone number) is copied. The object itself isn't copied."

"OK, I got it."

"A reference gives you one more benefit: you can pass an object reference to any method, and that method will be able to use the reference to modify (change) the object by calling its methods and accessing data inside the object."

Example 1
The values m and n don't change here.
public class References
{
  public static void main (String[] args)
  {
    int m = 5; int n = 6;

    System.out.println("M=" + m + " N=" + n);
    swap(m, n);
    System.out.println("M=" + m + " N=" + n);
  }

  private static void swap(int a, int b)
  {
    int c = a;
    a = b;
    b = c;
  }
}
And here's why.
This code is analogous to the code on the left
public class References
{
  public static void main (String[] args)
  {
    int m = 5; int n = 6;

    System.out.println("M=" + m + " N=" + n);
    int a = m, b = n;

    int c = a;
    a = b;
    b = c;

    System.out.println("M=" + m + " N=" + n);
  }
}

"Only the values 5 (m) and 6 (n), respectively, are assigned to variables a and b; a and b know nothing about (and don't influence in any way) m and n."

"To tell you the truth, I now realize that I didn't understand anything. Can you give me a few more examples?"

"With an object reference, we could have done the following:"

Example 2
The objects' data changes in this code
public class Primitives
{
  public static void main(String[] args)
  {
    Student jen = new Student(); jen.name = "Jen"; jen.age = 21; Student beth = new Student(); beth.name = "Beth"; beth.age = 15;

    System.out.println("Jen is " + jen.age);
    System.out.println("Beth is " + beth.age);

 ageSwap(jen, beth);

    System.out.println("Jen is " + jen.age);
    System.out.println("Beth is " + beth.age);
  }

  private static void ageSwap(Student a,
                                    Student b)
  {
    int c = a.age; a.age = b.age; b.age = c;
  }

  static class Student
  {
    String name;
    int age;
  }
}
And here's why.
This code is analogous to the code on the left
public class Primitives
{
  public static void main(String[] args)
  {
    Student jen = new Student(); jen.name = "Jen"; jen.age = 21; Student beth = new Student(); beth.name = "Beth"; beth.age = 15; 
    System.out.println("Jen is " + jen.age);
    System.out.println("Beth is " + beth.age);

    Student a = jen, b = beth;

    int c = a.age; a.age = b.age; b.age = c;

    System.out.println("Jen is " + jen.age);
    System.out.println("Beth is " + beth.age);
  }





  static class Student
  {
    String name;
    int age;
  }
}

"References to jen and beth, respectively, are assigned to the variables a and b; a and b change the values inside the objects jen and beth."

"And you can declare classes inside of other classes, right? Cool!"

"But I still don't understand everything else very well."

"All in due time."

Comments (94)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Fadhil Radhian Level 18, Semarang, Indonesia
13 March 2023
primitive values don't change because the method will change a NEW value, which does not affect anything, also not the original variable's value.
Lunita Level 4, Dominican Republic
21 December 2022
Ok I'm kinda confused now...
Hoist Level 4, San Diego, United States
8 January 2022
This example and discussion thread on Primitives and Reference variables is superb ! The amalgamation of so many different perspectives / cultures / languages is what makes @Codegym such a cool community. All of these mind blowing answers are just unreal in providing the depth I certainly have never understood with such -improved- clarity. It makes advancing in Java actually fun again and extends to any programming language.
Coding Venus Level 3, Seattle, United States
10 August 2021
Hmm. Why is the class with primitive variables called "References" and vice-versa?
Jonaskinny Level 25, Redondo Beach, United States
7 February 2022
Good catch lol
abhishe_kira Level 18, India Expert
14 June 2023
because the class(ref var) stores the reference to various primitive data(not only one there could be more than one) it dose not store the non primitive data itself. Let's have an example - a class of Student is non-primitive because it can store - 1.student's name, 2.student's age and other information about a student.
Víctor Alfonso Martínez Gómez Level 3, Manizales, Colombia
7 August 2021
El concepto es claro, pero no logro comprender el ejemplo
Figueroa Gabriel Hernan Level 4, Buenos Aires, Argentina
17 September 2021
Buenas, lo que se quiere mostrar es que al crear una variable primitiva el valor se guarda en el nombre de la variable, si quisiese cambiar el valor deberia asignarselo llamando nuevamente al nombre de la variable. Por ejemplo: int a = 5 para asignarle un nuevo valor debo volver a llamar a la variable a =2. En cambio al crear un objeto uno puede asignarle mas de una referencia que van a poder cambiar los valores que contiene.
Cepalomos Level 10
18 July 2021
no entendi nada la verdad
samuel souza e silva Level 2, Sao Paulo, Brasil
12 February 2021
esta tudo muito bom porem gostaria de n ter q ficar traduzindo toda hora lol, traduz para o portugues br ai pra gente
Anonymous #10604401 Level 8, Skopje, Macedonia
11 February 2021
In the first example the values from m and n are copied into a and b. Henceforth a and b are independent variables, and the values in them are swapped, while m and n remain unaffected. In the second example a and b are not assigned values/objects, rather only references to the objects, i.e. their addresses. In the operations that follow a and b manipulate variables inside the objects (Jen and Beth) they have references to, and those values are swapped, not the objects themselves.
NiTro Level 3, Kolkata
4 February 2021
showing error while creating an object in the main class! why?
Rishabh Joshi Level 9, Indore, India
21 November 2020
i did not understand the second example properly
Ahmad Level 7, Detroit, United States
30 December 2020
In the first example the code is copying the actual values of m and n to a and b, respectively. So this means when values of a and b change it does not affect values of m and n because a and b have their own values now even though it was copied from m and n. But in second example the values where not copied, but the reference to the objects (that hold the values) were copied. So let's just look at Student variables jen and a. Since these are not primitive types that means they don't hold the actual value but they hold a reference (or an address, or a pointer) to the actual value that is somewhere in memory. When the reference of jen was copied to a, now both jen and a have the same reference value. Meaning they are both pointing to the same object that hold the value "Jen". Both jen and a can change the value of "Jen" to something else. Whatever that new value is (ex. "Bob") then both jen and a will be pointing to the new value. It's like you and I both share a bowl of soup. You and I are the reference variables both pointing to a single object, and in this case the object is a bowl of soup. If I decide to add too much salt it will affect you because you are also eating from the same bowl of soup. With primitive types (first example) we each got our own bowl of soup. So if I add salt to my soup it does not affect you because you have your own bowl of soup. Hope what I explained above makes sense.
wade bennette Level 11, Springfield, United Kingdom
15 May 2021
Great answer made me get it now thanks
P.B.Kalyan Krishna Level 24, Guntur, India
16 March 2022
Well explained with good examples.