This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 7 years ago.
So I thought Java was pass by value but why does the following code:
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<Integer>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
phase1(numbers);
for (Integer number: numbers) {
System.out.println("number = " + number);
}
}
static void phase1(List<Integer> numbers) {
numbers.remove(0);
}
Print the following?
number = 2
number = 3
So I thought Java was pass by value
It is.
...but why does the following code...print the following?
Because the value passed for reference types is the reference, not a copy of the object.
"Pass by reference" refers to a completely different thing, passing a reference to the variable. Java doesn't have that.
If Java had pass-by-reference, then this change to your method:
static void phase1(List<Integer> &numbers) {
// Pass-by-reference indicator --^--- that Java doesn't actually have
numbers = new ArrayList<Integer>()
}
...would make your code print no numbers at all. But it doesn't, so it doesn't.
Think of the object reference as an int or long that uniquely identifies the object elsewhere in memory. (Which is basically what it is.) Just as a = b with ints copies b's value into a, so a = b copies b's value into a even when the value is an object reference. The value being copied is the reference, not the object it refers to.
Related
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 3 years ago.
In Pass By value when arguments are passed by value to a method, it means that a copy of the original variable is being sent to the method and not the original one, so any changes applied inside the method are actually affecting only the copy version and not the original one.
for example,
public class Test {
private void squareNumber(int number){
number=number*number;
}
public static void main(String[] args) {
int x=2;
System.out.println(x); //output = 2
new Test().squareNumber(x);
System.out.println(x);//output = 2
}
}
But in case of Arrays and List, this doesn't work like this and below is the example of ArrayList
public class Test {
private void squareOfList(List<Integer> integerList){
for (int i=0;i<integerList.size();i++) {
integerList.set(i,integerList.get(i)*integerList.get(i));
}
}
public static void main(String[] args) {
List<Integer> nums= new ArrayList<>();
nums.add(2);
nums.add(3);
nums.add(4);
nums.add(5);
System.out.println(nums); // output = [2, 3, 4, 5]
new Test().squareOfList(nums);
System.out.println(nums); // output = [4, 9, 16, 25]
}
}
Since we have passed nums as a parameter, only the value inside the method should change but it is changing the value of the original list.
Does this "STRICTLY Pass by value" term hold good?
int is primitive type and List is Reference type. According to JLS
The reference types are implemented by dynamically created objects that are either instances of classes or arrays. Many references to each object can exist.
When you pass a value of any reference type in a function only the reference is copied. Now both the references (caller, callee) are pointing to the same dynamically allocated memory. If you change that (dynamically allocated memory) in callee it is going to reflect in caller.
A variable of a primitive type holds a value of that exact primitive type
int is primitive type and it holds the value. when passed to a function it copies the value and there is no dynamically allocated memory which is shared. therefore all the changes you make in function remain in the function.
This example may clarify it further
public class Test {
private void squareOfList(List<Integer> integerList){
integerList = new ArrayList<>(); // Refering to a different dynamically allocated memory
}
public static void main(String[] args) {
List<Integer> nums= new ArrayList<>();
nums.add(2);
System.out.println(nums); // output = [2]
new Test().squareOfList(nums);
System.out.println(nums); // output = [2]
}
}
For further information read chapter 4 of java language specification.
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 6 years ago.
I have the following instantiated variable
public static int r1 = 10;
I have several of these variables r1 - r4, I want to write a method that will be able to take the variable r1 as a parameter of the method and increment it.
Pseudo code would look like :
r1 = r1 + 1;
My question is how can I take the variable as a parameter of one method instead of writing 4 different methods to accomplish this?
You can't, because Java does not let you pass variables of primitive types by reference.
You can put your variables into an array, and pass an array and an index:
public static int[] r = new int[4];
...
public static void modify(int[] array, int pos) {
array[pos]++;
}
...
modify(MyClass.r, 1); // instead of modify(MyClass.r1);
Alternative approach is to return the modified value to callers, and let them assign it back:
public static int modify(int orig) {
return orig+1;
}
...
MyClass.r1 = modify(MyClass.r1);
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 8 years ago.
So as far as I know, in java you can't access objects directly, you only have the pointer to it. So for example I have this code:
public class App {
public App() {
Thing t = null;
doStuff(t);
System.out.println(t);
}
public void doStuff(Thing a) {
a = new Thing();
}
public static void main(String[] args) {
new App();
}
}
class Thing { }
And the output is null. Why? I've passed the pointer to a method which gave it a new Thing instance to point to. Is it because it's a new pointer? Also how can I resolve it without returning anything from doStuff()?
You have references not pointers, and a method cannot update the callers reference without an assignment in the caller - so this
public App() {
Thing t = null;
doStuff(t);
System.out.println(t);
}
public void doStuff(Thing a) {
a = new Thing();
}
Would work if you did,
public App() {
Thing t = null;
t = doStuff(t);
System.out.println(t);
}
public Thing doStuff(Thing a) {
a = new Thing();
return a;
}
This is because Java works by pass by value of Object references and not pass by reference of an Object ,even if the reference is an Object,it still gets passed by the value of reference.So you always work with new references
Refer:http://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html
Declaring a Variable to Refer to an Object
Previously, you learned that to declare a variable, you write:
type name; This notifies the compiler that you will use name to refer
to data whose type is type. With a primitive variable, this
declaration also reserves the proper amount of memory for the
variable.
You can also declare a reference variable on its own line. For
example:
Point originOne; If you declare originOne like this, its value will be
undetermined until an object is actually created and assigned to it.
Simply declaring a reference variable does not create an object. For
that, you need to use the new operator, as described in the next
section. You must assign an object to originOne before you use it in
your code. Otherwise, you will get a compiler error.
A variable in this state, which currently references no object, can be
illustrated as follows (the variable name, originOne, plus a reference
pointing to nothing):
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 8 years ago.
while learning C language I have learned that when you pass a variable to a function. you are not passing the variable itself you are passing a copy of it so the actual varible's value will not change unless the function returns a value and you assign that value to the variable.
but I just executed this program and this happened when I passed "Newobj" object to a "changer" function and then change the values of the variables and then print the new variables values it is working. It should not happen right? because I am sending the copy of "Newobj" to "copyobj". explain please I am confused.
Note: Explain in detail please. My brain is slow. I know the concepts of c and few concepts of c++;
here is my code:
public class PassObjects {
int regno;
String name;
double per;
PassObjects(int a,String s,double p){
regno=a;
name=s;
per=p;
}
PassObjects changer (PassObjects copyobj){
copyobj.regno=797;
copyobj.name="Srimanth";
copyobj.per=70.9;
return copyobj;
}
public static void main(String[] args){
PassObjects Newobj= new PassObjects(86,"srimanth",85.4);
System.out.println("The original values of Instance variables are "+Newobj.regno+" "+Newobj.name+" "+Newobj.per);
Newobj.changer(Newobj);
System.out.println("The changeed values of Newobj are "+Newobj.regno+" "+Newobj.name+" "+Newobj.per);
}
}
output is here:
The original values of Instance variables are 86 srimanth 85.4
The changeed values of Newobj are 797 Srimanth 70.9
What you are doing is passing a pointer to an object. You are effectively modifying the PassObjects object.
There is a difference between a reference type and a value type. For example, a function that takes an integer and modifies it will indeed receive a copy of that integer.
public void add(int x)
{
x = x + 1;
}
However, an array of ints is also a reference type.
When you call this function using the following code:
int x = 5;
add(x);
// X will still have a value of 5.
This is because x is a value-type. You call the function and pass in a copy of the integer.
However, when you create an object, you do not pass a copy of the entire object. See code below.
public void ChangeName(SomeObject x, String newname)
{
x.name = newname;
}
SomeObject x = new SomeObject("thename");
ChangeNameTo(x, "newname"); // As the comment below pointed out, you don't even have to reassign.
//x.name will have the value "newname" now.
You can read more here and here.
Java does manipulate objects by reference, and all object variables are references.
That means u only created a new reference to the same object and when u changed the values then it gets changed in actual object.
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 8 years ago.
Ok so if primitive data types in java are passed into methods, they are treated as pass by value. And if object data types are passed into methods, they are treated as pass by reference right? So in this code:
//Class 1
public void passByValue(int x){
x = 0;
}
public void passByReference(Integer y){
y= 40;
}
//MainClass(contains main method)
int primitiveType = 50;
Integer wholeInteger = 100;
Class1 a = new Class1();
a.passByValue(primitiveType);
a.passByReference(wholeInteger);
System.out.println(primitiveType);
System.out.println(wholeInteger);
This should result in primitiveType being equal to 50(variable hasnt changed). I understand that, however the Integer object is also not changed... So how does this work? Thanks!
Object references are passed by value too. It is the reference that is passed and not the object. You confuse pass-by-reference of the object with pass-by-value of the reference.
In A x = new A() the symbol x is a reference to an object of type A.
If x is a reference and f(A a) { a = null; } is a method then f(x) will not set x to null. Hence, the reference was passed by value.
The reason behind this (and your confusion) is that - to some extend - the phrase "the object is passed by..." is already wrong. Because correctly we have to say "the object reference is passed by...". If A is a class then A a; means that a is a reference to an object of class A. If that is clear, it becomes clear why we have a pass-by-value.
First of all there is no pass by reference in java when you pass an object then it's also pass by value...
secondly, like String class , the wrapper class Integer is also immutable...
when you write Integer y= 40 ; then new Object new Integer(40); is being created by autoboxing feature java supports ..
That's why .... there is no change in value of wholeInteger you passed..