In java, is an object considered a variable? - java

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

Related

Why doesn't the variable value changes when it goes through a method [duplicate]

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.

Java object creation difference

I'm new to OOP concepts in Java. What is the difference between these two incidents?
1.
ClassName obj_name = new ClassName();
obj_name.method();
2.
new ClassName().method();
A good explanation is much appreciated. Thanks
In Option(1), you are still having/holding the reference to the object, so you can reuse that reference to access/call the other members(method/variables) of the object (class).
In Option (2), you don't have the reference (i.e., reference has been lost), so you will NOT be able to use it again.
One point to remember is that if you want to access the same object members multiple times, you need to hold the reference (use option 1 above), rather than creating the object (option 2) again and again (which is costly operation i.e., occupies memory).
Please refer the below link for more details:
https://docs.oracle.com/javase/tutorial/java/javaOO/usingobject.html
The reference variable obj_name hold the object of ClassName.through which you can call the instance method of ClassName through reference variable obj_name.
Whene ever we create an object and dont assign its reference to any reference variable its Known as Anonymous object instantiation.The Advantage of this type of instantiation is that you can only do the limited operation on that.Like you can call a single method.
If you want to perform mopre operation then reference varaibale which hold the object is better approach.If you have multiple method in your class and you want to use them then option 1 is right choice.
for details please go through this Link
While they might accomplish the same objective for the first call, the two approaches do fundamentally different things in terms of class definition and instantiation.
ClassName object = new ClassName();`
object.method();`
This is a case of instantiation. You create a new ClassName object which possesses certain instance fields and methods. It can call these methods, and the result may cause its instance fields to change.
ClassName.method();
On the other hand, this approach does not create an instance of the class. Instead, it calls method as a class attribute. Thus, the result can change fields in ClassName, but it won't necessarily existing fields in already-instantiated objects.
public class ClassName(){
public int attr = 0;
public ClassName(){}
public void setAttr(int value){
this.attr = value;
}
public void method(int value){
this.attr += value;
}
}
Now, using the first approach, we can create a newObj and call newObj.method(100). This will increase newObj's instance variable attr by 100.
To see the difference between the two approaches, let's use setAttr(200) to change the object's attr to 200.
Next, if we just use ClassName.method(100), the class's attr value will become 100 for all future instances of ClassName. So if we create ClassName nextObj = new ClassName(), this new instance of ClassName will have attr of 100, while newObj will still have attr of 200.
Hopefully this explains the core difference between the two approaches.
in option 1 you are creating an object with new keyword
followed by constructor and that object is referenced by class_name
obj_name variable so obj_name is pointing to that object.
In option 2 you not referencing to that object. just you make an
object and call the method with no references so that object is
eligible for garbage collection.

What is the difference between a variable, object, and reference? [duplicate]

This question already has answers here:
What are classes, references, and objects?
(12 answers)
Closed 6 years ago.
Exactly what are the differences between variables, objects, and references?
For example: they all point to some type, and they must all hold values (unless of course you have the temporary null-able type), but precisely how are their functions and implementations different from each other?
Example:
Dog myDog = new Dog(); //variable myDog that holds a reference to object Dog
int x = 12; //variable x that hold a value of 12
They have the same concepts, but how are they different?
(Just to be clear, the explanation I'm giving here is specific to Java and C#. Don't assume it applies to other languages, although bits of it may.)
I like to use an analogy of telling someone where I live. I might write my address on a piece of paper:
A variable is like a piece of paper. It holds a value, but it isn't the value in itself. You can cross out whatever's there and write something else instead.
The address that I write on the piece of paper is like a reference. It isn't my house, but it's a way of navigating to my house.
My house itself is like an object. I can give out multiple references to the same object, but there's only one object.
Does that help?
The difference between a value type and a reference type is what gets written on the piece of paper. For example, here:
int x = 12;
is like having a piece of paper with the number 12 written on it directly. Whereas:
Dog myDog = new Dog();
doesn't write the Dog object contents itself on the piece of paper - it creates a new Dog, and then writes a reference to the dog on that paper.
In non-analogy terms:
A variable represents a storage location in memory. It has a name by which you can refer to it at compile time, and at execution time it has a value, which will always be compatible with its compile-time type. (For example, if you've got a Button variable, the value will always be a reference to an object of type Button or some subclass - or the null reference.)
An object is a sort of separate entity. Importantly, the value of a variable or any expression is never an object, only a reference. An object effectively consists of:
Fields (the state)
A type reference (can never change through the lifetime of the object)
A monitor (for synchronization)
A reference is a value used to access an object - e.g. to call methods on it, access fields etc. You typically navigate the reference with the . operator. For example, if foo is a Person variable, foo.getAddress().getLength() would take the value of foo (a reference) and call getAddress() on the object that that reference refers to. The result might be a String reference... we then call getLength() on the object that that reference refers to.
I often use the following analogy when explaining these concepts.
Imagine that an object is a balloon. A variable is a person. Every person is either in the value type team or in the reference type team. And they all play a little game with the following rules:
Rules for value types:
You hold in your arms a balloon filled with air. (Value type variables store the object.)
You must always be holding exactly one balloon. (Value types are not nullable.)
When someone else wants your balloon, they can blow up their own identical one, and hold that in their arms. (In value types, the object is copied.)
Two people can't hold the same balloon. (Value types are not shared.)
If you want to hold a different balloon, you have to pop the one you're already holding and grab another. (A value type object is destroyed when replaced.)
Rules for reference types:
You may hold a piece of string that leads to a balloon filled with helium. (Reference type variables store a reference to the object.)
You are allowed to hold one piece of string, or no piece of string at all. (Reference type variables are nullable.)
When someone else wants your balloon, they can get their own piece of string and tie it to the same balloon as you have. (In reference types, the reference is copied.)
Multiple people can hold pieces of string that all lead to the same balloon. (Reference type objects can be shared.)
As long as there is at least one person still holding the string to a particular balloon, the balloon is safe. (A reference type object is alive as long as it is reachable.)
For any particular balloon, if everyone eventually lets go of it, then that balloon flies away and nobody can reach it anymore. (A reference type object may become unreachable at some point.)
At some later point before the game ends, a lost balloon may pop by itself due to atmospheric pressure. (Unreachable objects are eligible for garbage collection, which is non-deterministic.)
You can think of it like a answering questions.
An object is a what...
It's like any physical thing in the world, a "thing" which is recognizable by itself and has significant properties that distinguishes from other "thing".
Like you know a dog is a dog because it barks, move its tail and go after a ball if you throw it.
A variable is a which...
Like if you watch your own hands. Each one is a hand itself. They have fingers, nails and bones within the skin but you know one is your left hand and the other the right one.
That is to say, you can have two "things" of the same type/kind but every one could be different in it's own way, can have different values.
A reference is a where...
If you look at two houses in a street, although they're have their own facade, you can get to each one by their one unique address, meaning, if you're far away like three blocks far or in another country, you could tell the address of the house cause they'll still be there where you left them, even if you cannot point them directly.
Now for programming's sake, examples in a C++ way
class Person{...}
Person Ana = new Person(); //An object is an instance of a class(normally)
That is to say, Ana is a person, but she has unique properties that distinguishes her from another person.
&Ana //This is a reference to Ana, that is to say, a "where" does the variable
//"Ana" is stored, wether or not you know it's value(s)
Ana itself is the variable for storing the properties of the person named "Ana"
Jon's answer is great for approaching it from analogy. If a more concrete wording is useful for you, I can pitch in.
Let's start with a variable. A variable is a [named] thing which contains a value. For instance, int x = 3 defines a variable named x, which contains the integer 3. If I then follow it up with an assignment, x=4, x now contains the integer 4. The key thing is that we didn't replace the variable. We don't have a new "variable x whose value is now 4," we merely replaced the value of x with a new value.
Now let's move to objects. Objects are useful because often you need one "thing" to be referenced from many places. For example, if you have a document open in an editor and want to send it to the printer, it'd be nice to only have one document, referenced both by the editor and the printer. That'd save you having to copy it more times than you might want.
However, because you don't want to copy it more than once, we can't just put an object in a variable. Variables hold onto a value, so if two variables held onto an object, they'd have to make two copies, one for each variable. References are the go-between that resolves this. References are small, easily copied values which can be stored in variables.
So, in code, when you type Dog dog = new Dog(), the new operator creates a new Dog Object, and returns a Reference to that object, so that it can be assigned to a variable. The assignment then gives dog the value of a Reference to your newly created Object.
new Dog() will instantiate an object Dog ie) it will create a memory for the object. You need to access the variable to manipulate some operations. For that you need an reference that is Dog myDog. If you try to print the object it will print an non readable value which is nothing but the address.
myDog -------> new Dog().

Can Objects of user defined classes in Java be created on Stack and not dynamically on Heap like they can be in C++?

Class A {
// blah blah
}
Now, whenever we need to create an instance of this class, we do:
A a = new A();
In c++ there are two ways:
1. A a(10); // Created on Stack. Assume that the constructor takes an int argument
2. A a = new A(); // Created on Heap
How do you create user defined Java objects on stack?
No it isn't. All method-local primitive types and references are put on the stack, all objects are put in the heap. No ifs and buts about it.
One reason I can think why they did is that it removes one commonly made error: you pass the stack-based object to a method that stores a reference to that object. Then the object goes out of scope, is removed from the stack, and the reference points to something undefined. Next when you want to access the "object" through the reference, you're in a world of hurt since the object is no longer there - and nobody knows what is.

"Object" vs "Object Variable" in Java?

I am teaching myself Java, and one of the review exercises in my book asks for the difference between an "object" and an "object variable."
I know what an object is (a specific instance of a class), but I can't seem to find the term "object variable" anywhere in the book (no answers section) or on the internet.
Does anyone know the meaning of this term?
I'll bite.
The Object is the instance itself, whereas the Object Variable is the reference to the Object.
Here's a contrived example:
Object o = new Object();
Object ref1 = o;
In his case, there is a single instance of the Object, but it is referenced by two Object Variables: o and ref1.
When an Object is no longer referenced by an Object Variable, the Object is garbage collected.
It's a synonym of "instance variable":
class A {
static int m; // <-- class variable
int n; // <-- instance variable
...
}
Evidently, this term is not so commonly used, and it would better to avoid any potential ambiguities by just sticking with "instance variable".
tl;dr;fmoe
I came across the same question in a review exercise found within Cay Horstmann, Big Java, Early Objects (John Wiley & Sons, 2013), 73.
Cay defines an object variable as a variable (whose type is a class) which stores a reference to the memory location of an object.
Rectangle box = new Rectangle();
box is the object variable which stores a reference to the newly instantiated Rectangle object's memory location.
Multiple object variables can exist which store the same reference to an object's memory location.
Rectangle box = new Rectangle(5,10,20,30);
Rectangle box2 = box;
Calling a mutator/mutagenic method (modifies the object on which the method is invoked) on either object variable mutates (modifies) the object since the object variables reference the same object's memory location
box2.translate(15, 25);
System.out.println(box.getY()); // 35.0
System.out.println(box2.getY()); // 35.0
This gets a bit confusing if you compare Cay's definition with the information from The Java Tutorials, and numerous other sources, but I believe this is the answer to your question when placed within the context of Cay's book(s).
I prefer this perspective => An object's memory location is stored in the object reference (object variable per Cay). When I invoke a method on an object, I specify the object reference followed by the dot (.) operator, followed by the method name.
objectReference.method();
If the public interface of a class allows access to one or more of it's instantiated object's fields (AKA instance variables, object variables, class member variables, properties, or attributes... depending on programming language and documentation) then I can access it by specifying the object reference, followed by the dot (.) operator, followed by the field name
objectReference.fieldName;
Why do I prefer this? I'm not a fan of using variable as a noun too many times; overloaded semantics boggle my simple mind.
#Faaris Cervon : Object variables are the variables which does not create any object but refer to some object ..
exmp : Date d1= new Date();
d1 is a object.
date d2;
d2 is not an object and neither it refers any object But it can hold any object of type date.
d2=d1; // valid.
hence d2 is a object variable.
It is important to remember that object variables does not contains objects actually but it refers to some object.
I found something that help you too.
There are few words like object, object variable and object reference.
Object variable and object reference are similar in the way that object variable stores the reference of an object where as object reference describes the location of an object. (You might be confused here so just consider them as same)
consider an example::
Class Car{
....
....
}
Car AudiQ7; //S1
Car AudiQ8 = new Car(); //S2
Here in S1 we created only object. Means it does not refer to memory.
In S2 we created an object variable/reference means it refers to memory location.
At university its tought, that an Object Variable is: "a variable whose type is a class, and which holds a reference to an object that is an instance of that class"
Object thing = new Object();

Categories

Resources