This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 9 months ago.
I'm Ryan who's a rookie in programming. I was going through the OOP part of my textbook today and I found a part that I won't understand at all. There are 2 codes, I'll have them copied here.
The first one is :
public class Change {
public static void main(String[] args) {
int x = 17;
dontChange(x);
System.out.println(x);
}
static void dontChange(int z) {
z = 42;
}
}
When the code was executed. The output would still be 17, which is not the expected 42(in my understanding of parameter and Method.)
The textbook provided another example as well, which results in a change.
public class Change {
void change(Student s) {//student is a type
s.name = "Fred";
public static void main(String[] args) {
stu.name = "Jane";
change(stu);
System.out.println(stu.name);
}
}
This code would result in the output the name as 'Fred', I was wondering where's the difference between them and what was the reason behind these codes when they look similar and worked totally differently.
Thank you for going through the whole post, I wish you have a great day!
You need to distinguish between “passing by value” and “passing by reference”. Maybe this helps
If you want to understand the answer to this Question, why the value does not change, you have to understand, why the value sometimes change.
The values changes,if the Datatyp is referencial. This means, that the data is stored at the heap(a part of memory) and our variable only points to this data. This means, that your variable only stores, where the data is really stored.
If we change our data,we are following our reference and change it there.
This means, that every reference, which points at our data is also changed. It is the same object.
What happens here is different. You are not dealing with referencial Datatyps.
You are dealing with primitives(int, float, char....). Those datatyps aren't stored in the heap. They are stored in the stack(another part of memory). This means, that the data is really stored in our variable. So, if we change our data in our variable, we aren't following an reference and change it there. We are really changing the value in our variable.
An analogy:
Referencial types are like notes, which point to a different note. In the second note is the data. If we try to change the datanote, we take a look at our first note with the reference to the datanote and then change the datanote. Any note pointing to the datanote has now the updated data.
primitives are like, if our first note has all the data. There is no pointing to somewhere else. It is our data
Primitives start most of the time with a lower case letter. Primitives can't have any functions or anything.
Refercal start most of the time with a Capital letter. They can have functions and are most of the time classes
What you wanted to do was to return the new value and set it equal to x.
I hope, i've helped you a bit.
If you have any Questions left, feel free to ask
sorry for my English:)
Firstly, I would point out the difference between the two examples you've shown. The method Change#change(Student)
public class Change {
public void change(Student s) {
s.name = "Fred";
}
}
Compared to Change#dontChange(int)
public class Change {
public void dontChange(int i) {
i = 42;
}
}
The most notable difference between these two methods is where they assign (=) the value they're passing. s.name vs i. Note the presence of the dot operator (.) indicating that there's access of an Object's field or method. This can help start the explanation of why change(Student) updates the value it assigns to as compared to dontChange(int).
There was reference of looking into the difference between pass-by-value and pass-by-reference in other answers, and that will be required information for WHY this happens. However, I think there should be a slightly deeper understanding of what a variable is in java for that to help explain it. The easiest explanation I find is that a variable in java is a number. Period. Always. Now that might seem weird, right? You obviously have an object when you do Student stu = new Student(), but that's only partially correct. You do instantiate (create/construct) an object, but the value stored in Student stu can actually be thought of as a number pointing to a spot in memory where stu's values are stored. There IS a difference in how these number are handled, but they are, in essence, all numbers.
Knowing this, you can work with the thought that values passed to a method in java are always passed-by-value. If you wanted to test this you could see the output of changing the body of Change#change(Student) to
public class Change {
void change(Student s) {
Student newStudent = new Student();
newStudent.name = "Fred";
s = newStudent;
}
}
You may expect the output name to still be "Fred", but it should result in "Jane". We didn't modify the object that Student s refers to, we updated what the variable s points to. The difference being that in the original Change#change(Student) method you assigned the value "Fred" to the name field (s.name) of the object that Student s refers to.
When you call Change#change(Student) with the variable stu the parameter s's value becomes the same identifying number that stu points to, but the variables themselves are entirely different. They only, when s is initialized, have the same value (a number pointing to a space in memory).
It should be noted that assigning "Jane" and "Fred" to the Student's name field is actually assigning a reference to a String which represents "Jane" or "Fred" to the Student's name field. As the name field's type is, assumed to be, String which is not a primitive type. Meaning it's a reference to some String object in memory.
What is happening here is passing by value and passing by reference. In Java all primitive types(int, char...) are passed by value to any method, this means the value of them are copied for the method to use.
Anything else like objects from classes you create are passed by reference. This means the contents of the object are not copied but the address of where that object is in memory is copied to the method. The value at this address(the original object) is then used within the method meaning changes to it are seen outside of the method.
To go into more detail and why this happens can get quite confusing as a beginner but other people have linked good articles to read. To put it simply in my own words.
Whenever you are using an object(non-primitive type) i.e Student. Java is actually seeing this as an address to that object but to keep things easier for the programmer Java doesn't make you declare this in any way. Any access to this object is automatically handled by Java to mean the value of the address you are using.
Just want to know whether this statement is true or not:
For these lines of code:
Person Bob = new Person("Bob W.", 30);
System.out.println(Bob.name);
An Object Person is created and its memory address or a kind of reference is sent to Bob, the reference variable . Next, when we call "Bob.name", the JVM looks at the "address" held by Bob and goes there to look at the Person Object. Then JVM looks at Bob's name and prints it!
Thanks!
All objects in Java are accessed via their references (different from primitive access!). The variable bob is a reference to an instance of the Person class. Memory allocation/disposal of instances will be handled by the JVM, and the instance data will be kept alive by the JVM as long as there exist strong references to that instance (ie Person bob = new ... declares a strong reference to the newly created Person instance).
An Object Person is created and its memory address or a kind of reference is sent to Bob, the reference variable
It would be more correct to say that an "An instance of the Person Object is created", but yes, all variables used for objects in Java are reference variables. Calling new will return the reference to the instance created. There can be many reference variables which point to a single instance. For example, in the following code snippet we can have two references pointing to a single instance:
Person bob = new Person("Bob W.", 30);
Person bob2 = bob;
Next, when we call "Bob.name", the JVM looks at the "address" held by Bob and goes there to look at the Person Object.
Exactly. After code is compiled, the JVM bytecode will use the instruction getfield to access the name field. This instruction requires an object reference and the field reference. In this case bob.name will use bob as the objectref and use Person#name as the fieldref.
Please help me clear this confusion its bugging me alot. When I write the following code what happens in the memory and how is the object Jhon stored?(If I am correct that Jhon is an object and not merely a reference to an object)
class Human{
String Name;
float height;
}
class Student extends Human{
int Student_ID;
Student Jhon = new Student();
}
My question is, is Jhon an object or is it a reference to an object created? what is the reference variable here? What is an object variable here?
I'd say this is well-explained by the following line from JLS:
The value of a class instance creation expression is a reference to the newly created object of the specified class.
So, in the following code:
Student Jhon = new Student();
^-----------^ Class instance creation expression
^----------^ Variable declaration
To reiterate: the value of the class instance creation expression is the reference to a newly created object. That object is created somewhere in memory; but the key point is that the value isn't that object, but a reference to it.
And then you assign that reference to a variable, Jhon. So Jhon is not an object, nor a reference, but a variable whose value is a reference to a variable.
Just to add to #Andy Turner's response. Jhon is a variable that points to the reference to an instance of the class student that is held in the Java Virtual Machine (JVM) memory heap. The programmer has no way of directly accessing the object in the heap, that is all done by the JVM. The heap is managed by the JVM, when an object in the heap no longer has a variable that points to the reference to it, it will be cleaned up by the JVM garbage collection. The programmer does not have to concern themselves with this process.
See more detailed explanantion in official Oracle docs
Also see helpful disccusion in opening chapter of David Eck's book
One source I am studying defines an array as "a collection of variables under one name, where the variables are accessed by index numbers."
But then I realized that you can have an array of objects (or an array of pointers to objects, at least).
This got me to wonder what a variable is defined as in java, as I did not consider an object to be a variable. Jenkov Tutorials cites a variable as being "a piece of memory that can contain a data value."
And since I believe an object fits this definition, is an object considered a variable?
Calling an array a "collection of variables" is arguably stretching the definition already. But an array is certainly a collection of references that can be made to point to different objects in memory, and each such reference can reasonably be called a variable.
Asking "is an object a variable" is a little weird in the first place. In Object o = new Object(), o is clearly a variable, though remember it's a reference to an object in the heap, not the object itself.
Honestly, "variable" is a pretty flexible, ill-defined term -- is a field a variable? The return result of a method? It depends on who's talking and what fuzzy definition they're using today.
is an object considered a variable?
No, these are two distinct things.
The first one (the object) is the value and the second one (the variable) is a way to reference an object, generally to use it (invoking a series of method on it for example).
For example when you write :
new Dog()
You instantiate a Dog. Nice. But suppose you want feed it if it is hungry.
You cannot if you have not a way to chain a series of method on this object.
By storing the reference of the Dog in a dog variable you can do it :
Dog dog = new Dog();
if (dog.isHungry()){
dog.feed();
}
Jenkov Tutorials cites a variable as being "a piece of memory that
can contain a data value."
It says the same thing.
But this :
One source I am studying defines an array as "a collection of
variables under one name, where the variables are accessed by index
numbers."
is rather misleading.
An array is an object that has a state that contains, among other things, elements of the array.
The way which the elements are referenced in is a implementation detail of the Array class and I would not affirm that each element is stored in a specific variable.
An object is created when you call the constructor with the reserved word new.
For example:
Object a = new Object();
a will be the variable of that new object created and will go to reserved memory for that object. You are instantiating that new variable and that variable is associated with that object.
Hope might this will help you to understand it better...
class Bulb
{
private int w;
public void setWattage(int e)
{
w=e;
}
public int getWattage()
{
return w;
}
}
class Test
{
public static void main(String args[])
{
Bulb b[];
b=new Bulb[2];
b[0]=new Bulb();
b[1]=new Bulb();
b[0].setWattage(60);
b[1].setWattage(100);
System.out.println(b[0].getWattage());
}
}
here b[0] and b[1] are reference variables who have the address of two Bulb objects
I've been programming Java for 2 years now, and I have encountered a problem where I couldn't understand and differentiate class, reference, and an object.
I am not sure if a class or reference are the same, though I have an idea of what an object is.
Can someone differentiate in a complete manner what classes, references, and objects are?
All I know is that a class is more like a template for an object (blueprint to a house where the class is the blueprint and the house is an object).
If you like housing metaphors:
a class is like the blueprint for a house. Using this blueprint, you can build as many houses as you like.
each house you build (or instantiate, in OO lingo) is an object, also known as an instance.
each house also has an address, of course. If you want to tell someone where the house is, you give them a card with the address written on it. That card is the object's reference.
If you want to visit the house, you look at the address written on the card. This is called dereferencing.
You can copy that reference as much as you like, but there's just one house -- you're just copying the card that has the address on it, not the house itself.
In Java, you can not access objects directly, you can only use references. Java does not copy or assign objects to each other. But you can copy and assign references to variables so they refer to the same object. Java methods are always pass-by-value, but the value could be an object's reference. So, if I have:
Foo myFoo = new Foo(); // 1
callBar(myFoo); // 2
myFoo.doSomething() // 4
void callBar(Foo foo) {
foo = new Foo(); // 3
}
Then let's see what's happening.
Several things are happening in line 1. new Foo() tells the JVM to build a new house using the Foo blueprint. The JVM does so, and returns a reference to the house. You then copy this reference to myFoo. This is basically like asking a contractor to build you a house. He does, then tells you the house's address; you write this address down.
In line 2, you give this address to another method, callBar. Let's jump to that method next.
Here, we have a reference Foo foo. Java is pass-by-value, so the foo in callBar is a copy of the myFoo reference. Think of it like giving callBar its very own card with the house's address on it. What does callBar do with this card? It asks for a new house to be built, and then uses the card you gave it to write that new house's address. Note that callBar now can't get to the first house (the one we built in line 1), but that house is unchanged by the fact that a card that used to have its address on it, now has some other house's address on it.
Back in the first method, we dereference myFoo to call a method on it (doSomething()). This is like looking at the card, going to the house whose address is on the card, and then doing something in that house. Note that our card with myFoo's address is unchanged by the callBar method -- remember, we gave callBar a copy of our reference.
The whole sequence would be something like:
Ask JVM to build a house. It does, and gives us the address. We copy this address to a card named myFoo.
We invoke callBar. Before we do, we copy the address written on myfoo to a new card, which we give to callBar. It calls that card foo.
callBar asks the JVM for another house. It creates it, and returns the new house's address. callBar copies this address to the card we gave it.
Back in the first method, we look at our original, unchanged card; go to the house whose address is on our card; and do something there.
When you code, you build an
Instance (occurrence, copy)
of an
Object
of a said
Class
and keep a
reference
to it, so you can call its methods.
Also, some OOP basics: Classes, Object, Instance, and Reference.
In the book "Thinking in Java" from Bruce Eckel it has been described perfectly:
"You might imagine a television (the object) and a remote control (the reference). As long as you’re holding this reference, you have a connection to the television, but when someone says, “Change the channel” or “Lower the volume,” what you’re manipulating is the reference, which in turn modifies the object. If you want to move around the room and still control the television, you take the remote/reference with you, not the television.
Also, the remote control can stand on its own, with no television. That is, just because you have a reference doesn't mean there’s necessarily an object connected to it. So if you want to hold a word or sentence, you create a String reference:
String s;
But here you’ve created only the reference, not an object. If you decided to send a message to s at this point, you’ll get an error because s isn’t actually attached to anything (there’s no television). A safer practice, then, is always to initialize a reference when you create it:
String s = "asdf";
However, this uses a special Java feature: Strings can be initialized with quoted text. Normally, you must use a more general type of initialization for objects.
When you create a reference, you want to connect it with a new object. You do so, in general, with the new operator. The keyword new says, “Make me a new one of these objects.” So in the preceding example, you can say:
String s = new String("asdf");
Not only does this mean “Make me a new String,” but it also gives information about how to make the String by supplying an initial character string.
Of course, Java comes with a plethora of ready-made types in addition to String. What’s more important is that you can create your own types. In fact, creating new types is the fundamental activity in Java programming."
Suppose you write there two lines of code:
Engine app1 = new Engine(); //LINE 1
Engine app2 = app1; //LINE 2
In line 1, Engine is a class, its a blue-print basically.
new Engine() is the instance that is made on the heap.
You are refering that instance by using app1 and app2 in your code.
So app1 and app2 are the references.
When you create an object, what happens behind the scene is that a piece of memory is reserved for containing that object. This could be anywhere in the great big memory landscape; it's up to the operating system and the compiler, and you don't really have any control or knowledge of where it ends up.
Ask yourself, then, how do you use that object if you don't know where in memory it is? How can you read a value from it if you don't know where that value is stored? This is what references do for you. They are a way of keeping in touch with the object. It's a little string attached to the balloon that is a reference.
You use the reference to say that "I want to touch this object now!", or "I want to read a value from this object!".
========= Class and Object ===========
Class => ex: Person (More like imagination)
Object => ex: John, Mike (Real person)
=========== Reference ============
ex:
Television tv1; - (Television is a class, tv1 is a remote controller without Television)
Television tv2 = new Television(); - (Now tv2 remote controller has a Television)
tv1 = tv2; - (Now tv1 and tv2 can control same Television)
Television tv3 = new Television(); - (tv3 is a new remote controller with new Television)
Class:
Structure or BluePrint
Object:
Physical Manifestation
Reference:
Address of Object
Class is a template, you are right. It is some knowledge about data structure. Object is that structure instance in memory. Reference is a memory address of that instance.
If by Object you meant the java identifier, then Object is the basic class for all complex Java classes.
Object is the run time representation of the Classdefinition. And the name with which you use the object is called the reference (as it references the actual object location in memory )
example
MyClass ref = new MyClass();
Here, MyClass is (contains) the class definition.
new MyClass() creates an object for this class (done only during execution, hence runtime representsion)
ref is the name you use to work on the class object, is the reference.
Class : Used to define a real life entity into a programming environment.
Any real life entity having at least one property and a corresponding behaviour can be considered as a class. Lets take an example of a Car, it is having a property accelerator which helps the car to move and to control its speed. The corresponding behaviour is acceleration, which is directly proportional to the push applied to the accelerator.
class Car {
private String tier;
private String tierFriction;
private double weight;
private double gasFedToEngine;
}
The above class shows some properties of a Car, on which its acceleration depends. Behaviour (method in the class) always depends on the property(s) (global attribute(s) of the class). Now if you want more details you can define Tier as another entity, then the definition will look like
class Tier {
private String tierMaterial;
private String tierFriction;
private double weight;
private double tierDiameter;
}
class Car {
private Tier tier; // getting all properties of Tier here itself
private double weight;
private double gasFedToEngine;
}
Object : Used to define various flavours of an Entity and to perform data manipulations on them separately.
Now we have defined an entity to our program, say we are having a showroom of used cars, having cars of different companies. So each car becomes an object of our entity. Objects can be Audi, Nissan, Ferrari etc. So after opening the showroom we add cars to it like this
static List<Car> showroomCars = new ArrayList<Car>();
public boolean addCarToShowroom() {
Car carNissan = new Car(); // always creates a new objects and allocates some memory in heap
carNissan.setName("Nissan");
carNissan.setColor(RED);
carNissan.setWeight(300);
showroomCars.add(carNissan);
Car carAudi = new Car();
carAudi.setName("Audi");
carAudi.setColor(BLACK);
carAudi.setWeight(270);
showroomCars.add(carAudi);
}
So now two new cars are added to the Showroom, one of Nissan and another one of Audi, each having their own specific attribute values.
Class only gives definition, manipulation is done on Object, for doing manipulation on any Class, object should be created. Every time an object is created to a class all its non-satic(instance) variables will load into memory with their respective default values.
Reference : Used to address an object
When we say Car carAudi = new Car(); we define a new object to Car and a memory location is assigned for that object. The reference variable carAudi holds the memory address of that object. Object is never accessed directly by user, neither its memory location. That's where reference variable has significance, its stores the hexadecimal format of memory location. If we want to do modifications on an object do with the help of reference not directly.
An object can have any number of reference, but a reference can point only to one object at a time.
class Car {
void test() {
Car car1 = new Car(); // (1)
Car car2 = new Car(); // (2)
car2 = car1;
/**
Says that car2 should point to where car1 points, so now both points to first object of Car
But for this car2 has to loose its current object-(2), making it an Abandoned object (An object with no active reference from the stack).
**/
}
}
In Real world, Object is a material thing that can be seen and touched in this universe.
In Programming, Objects are same but those are stored or trapped inside a memory like when any object is being created. it will create in the RAM(Memory). So, As a human we will not be able to see it or touch it but it do exist in the memory somewhere.
So, we don't care about how system is creating or destroying objects, rather we will see how to handle it using programming.
In order to create an object, Programming language provide's us syntax format's which we can use handle these objects.
Now, How you will define what object you want to create like if you want to create a customize new car then you have to provide your requirements to the manufacturer right?.
Same way in programming, class is used. The class is a blueprint which will define how object should look like/what all data it will store and what all operation it will do. It doesn't exist in the memory and just used to define the requirements for creating an object.
Let's take an example of student:
//We have a Student class. Below are some attributes which we will use:
class Student
{
string Name;
int Age;
string Address;
}
Now, Above Student doesn't really exist. This is only a blue print of how student will be. If we need to create a student then we call it creating a object and below is the format to create one student.
Student student=new Student();
Now, 1 student object has been created in the memory which can be used to set any name/age/address and get the same information as shown below:
static void Main(string[] args)
{
Student student = new Student();
student.Name = "Vivek";
student.Age = 24;
student.Address = "Address";
Console.Write("Student Name is " + student.Name + " whose age is " + student.Age + " and he/she stays at " + student.Address);
}
Now, Assume you want to provide some work to Student, How will you do it?
//By writing a function/method and write the code which student should handle as below:
class Student
{
public string Name;
public int Age;
public string Address;
public void Run()
{
//Write some code
}
public void Walk()
{
//Write some code
}
}
Above one is just an example as student will not run in the memory, So, Code which you have to write is C# code only or whatever programming language which you are using to write code. Like do some operation with C#.
Now, I would like to highlight that:
if you see in the real world. Student does not only contain Name/Address/Age but student also have other attributes like Mother Name/Father Name/Passport etc. In addition to normal attributes, We can also add body parts like Brain/Heart/Legs etc.
So, Class Student can be more complex if you add all attributes to it.
Example: Your customize car will not customize all parts of your car. You have to use exisiting parts like wheels/tier/Air conditioner etc. So, Classes can use exisiting classes/struct/methods/fields etc. in order to achieve the requirement. As you can see below that class is using other classes/struct/methods/fields etc. in order to achieve the requirements:
//String is also class which represents text as a sequence of UTF-16 code units
public string Name;
//Integer is a struct which represents a 32-bit signed integer
public int Age;
//String is also class which represents text as a sequence of UTF-16 code units
public string Address;
Everything in Java is associated with class objects and classes, including attributes and methods. Ex: a car is an object in real life. The car has attributes, such as weight and color, and methods, such as drive and brake. A Class is like an object constructor or a "blueprint" for creating objects.
A reference is an address that indicates where an object's variables and methods are stored. You aren't actually using objects when you assign an object to a variable or pass an object to a method as an argument.