Java: Array expanding is not changing the original array? [duplicate] - java

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 8 years ago.
I have a problem where I'm supposed to expand an array, each time creating an array with identical results. Before you tell me to just use ArrayList or something else already in the Java API, I was specifically instructed to use my own code. I tried simply creating an array that is one slot larger than my current array, though that does not seem to work very well. Here is what I have that the current moment:
public static void expand(Object[] objArray) {
Object[] objArray2 = new Object[a.length + 1];
for (int i = 0; i < a.length; i++)
objArray[i] = objArray[i];
objArray = objArray2;
}

You can't update the caller's reference inside the function. Instead, you need to return your new Object[] and update in the caller. Also, you could use System.arraycopy()
public static Object[] expand(Object[] a) {
Object[] b = new Object[a.length + 1];
System.arraycopy(a, 0, b, 0, a.length);
return b;
}

I Java, arrays are objects and objects are passed by value to methods, and that is, if you change what the reference is pointing to in the method, your changes will stay locally. The solution is to return the modified object
public static Object[] expand(Object[] objArray) {
Object[] objArray2 = new Object[a.length + 1];
..
return objArray2;
}

objArray is just a passed in reference argument to the method. It will not change external reference variables. The variable objArray is removed from the stack the moment the method is ended.

Assigning to a parameter has no affect on the matching argument, as opposed to modifying a parameter, which does.

Oh dear, where to start.
This method is void and doesn't throw or side-effect, therefore it does nothing.
The statement objArray[i] = objArray[i]; has no effect.
a is not declared (or you haven't shown us enough context).

Related

What is going on with this Java array passed to a method? [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 2 years ago.
I've learned that in Java, arrays are passed by reference, meaning that they can be modified within functions. However, I recently came across this piece of code that confused me, because it seems to show inconsistent behavior.
import java.io.*;
import java.util.*;
public class TestProgram {
public static void fMethod(int[] f){
f[0] = 9;
f[1] = 7;
f = new int[4];
}
public static void main(String[] args){
int[] fParam = new int[3];
fMethod(fParam);
System.out.println(Arrays.toString(fParam)); // prints [9, 7, 0]
}
}
Because the function fMethod() seems to reset f to a new int[4] at the end, I expected to see [0, 0, 0, 0] printed to the console. However, it seems that only the f[0] = 9 and the f[1] = 7 lines were actually executed, while the last line was ignored. I find this strange. Can somebody please point me in the right direction?
Remember, that:
In Java, everything is passed by value.
and in case of objects (arrays are also objects), address of the object, a value, is being copied into another variable.
In your code, int[] f is a local variable (scoped in a method), which initially refers to the original array and:
f[0] = 9;
f[1] = 7;
changes original array.
However, then you assign a new array object to f and you, eventually, discard that object entirely (as you don't return anything).
As long as f refers to the first array, it alters that array, and therefore, it only changes first two elements of it. After that, f refers to something else.
In your main method, though, fParam still refers to the previous array object and you print that object, 3rd element of which, is an integer array's default value, 0.
Within fMethod, you get the array passed as variable f. As long as you modify the content of the variable, it will actually change your reference.
On line 3 of your method: f = new int[4] you assign a new array to the variable f. This means you overwrite the reference the variable f holds by assigning a new value, so any modifications afterwards to the array happen to the new assigned array.
If you would introduce a class variable instead and pass it to the method, your application would act as you'd expect it to.

Java: Modifying Objects by Method Call [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 4 years ago.
I've read a gazillion times that in Java, arguments passed to methods cannot be modified by the methods. Nonetheless, I find I can modify objects I create as opposed to Java Objects. Consider the following code:
// My Integer Object
class MyInteger {
Integer val;
}
// Change Java Object
public void test1() {
Integer intval; // Integer object
intval = 123;
setInteger( intval ); // THIS DOESN'T WORK
TTY.putR( "Integer Object="+intval);
}
// Change My Object
public void test2() {
MyInteger myInt; // MyInteger object
myInt = new MyInteger();
myInt.val = 456;
setMyInteger( myInt ); // THIS WORKS!
TTY.putR( "MyIntegerObject=" + myInt.val );
}
// Set an Integer object
public void setInteger( Integer val) {
val = 888;
}
// Set a MyInteger object
public void setMyInteger( MyInteger myint) {
myint.val = 999;
}
test1 doesn't work as I have been warned. But test2 works just fine. AFAIK, both are objects and are passed by reference. So how come one works and the other doesn't? (Note: TTY is my print function)
You have either read things that were wrong, or misunderstood what you've been told.
If you pass 'a' to a java method, you cannot have the method change 'a' to be something other than 'a'. However, you can modify 'a'.
In other words, you cannot create an object of the same class as 'a' and return that in place of 'a'. The only way you can return an object created by the method is either to have a place to put a reference to that new object within an object passed to the method, or to return it as the return value from the method.
The best way I've seen this explained:
You pass an object A pointing to a memory address P.
A ===> P
When you modify A by doing A.foo = bar, A is still pointing to P, so the object at P has its property foo changed. However, let's say you want to completely reassign A, and so do A = new MyCoolObject(). This means
P_New <=== A ==/=> P
So when you modify A by doing A.foo = bar, A is no longer pointing to P, so the object at P_New has its property foo changed, but the object at P remains unchanged. This means when you exit the method and go back to whatever parent called the method, A will be completely unchanged.
Disclaimer: I saw this on another Stack Overflow article probably 5 years ago, and am too lazy to find it. If you're reading this right now and you're the person who wrote this, thanks, and forgive my casual plagiarism.
I think you are confused by pass-by-reference vs. pass-by-value. Read this to help clear it up.
You might also have misinterpreted what you've read. A mutable Object can be mutated anywhere -- where it is created or by a method it is passed to.
Good luck.
Because MyInteger the val is a public variable. So ANYONE can modify it.
// Change MyInteger object
public void setMyInteger( MyInteger val) {
val.val = 999; // ACCESING TO A PUBLIC VAR and SETTING IT
}
// Change an Integer object
public void setInteger( Integer val) {
val = 888; // Accesing to the value of the Variable and not modifing it
}
Java is a pass by value language. When you invoke any method with argument it creates new variable and you are changing this variable.
You can look at this also,
Is Java "pass-by-reference" or "pass-by-value"?

Why am I able to modify a List in a method that's out of scope, without returning it? [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 6 years ago.
Let's say I initialise my list like so:
public static void main(String[] args) {
ArrayList<String> a = new ArrayList<String>();
a.add("one");
a.add("two");
a.add("three");
a.add("four");
modifyList(a);
}
where modifyList simply changes every value to "one" like so:
private static void modifyList(ArrayList<String> a) {
for (int i = 0; i < a.size(); i++) {
a.set(i, "one");
}
}
If I print the list before and after I call this method, I expect the same original list to appear twice. But for some reason, the ArrayList that gets modified in modifyList is the same as the ArrayList in main.
If I try the same experiment with ints and Strings instead of Lists they do not get modified.
Can anyone explain why?
In Java, parameters are passed by value.
However, you passed a reference to your ArrayList to the method (and the reference itself is passed by value), and therefore the method modified the original list.
If you want to ensure that this cannot happen, you need to pass an immutable list as the parameter.

How are these two situation different? [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 8 years ago.
public void otherMethod(){
List<String> list = new ArrayList<String>();
list.add("abc");
list.add("abc");
list.add("abc");
someOtherMethod(list);
System.out.println(list.size());
}
public void someOtherMethod(List<String> list){
list.add("abc");
}
Invoking otherMethod prints 4.
where as
public void otherMethod(){
int a = 10
someOtherMethod(a);
System.out.println(a);
}
public void someOtherMethod(int a){
a = 11;
}
prints 10;
How are the two different. Aren't both local variables? Does sending list reference work in a different way? Please help me understand how the two scenario differ?
Before downvoting please make me understand why this below one also prints 10?
public void otherMethod(){
Long a = new Long(10);
someOtherMethod(a);
System.out.println(a);
}
public void someOtherMethod(Long a){
a = 11;
//or a= new Long(11);
}
In fact conceptually they are not different, in both cases a copy of the original value is passed in as an argument to the method. The thing is that in the first case you have a complex/composite structure of some sort so you pass in a reference copy which is different from the original reference but which still points to the original structure/object.
In the second case you pass in a copy of an int and so the method just operates on the copied int. Unlike that in the first case the method operates directly on the original structure through that copy of the reference (which it receiver from the caller).
Now, in the case of Integer and Long, you work on the original objects through a copied reference. The thing is that you cannot do much on the original object as these classes are immutable e.g. they don't have methods Integer.increment(int n) or Long.increment(long n) which change the original objects by incrementing their values. It would be same if we talk about String (which is immutable) but not the same if we talk about StringBuilder (as the latter is mutable).
public void someOtherMethod(Long a){
a = 11;
//or a= new Long(11);
}
In this example you direct the copied reference to a new object (11)
but the caller still has the original reference which still points
to the same old object (10). You have no way of changing the original
object (from within the called method) just because Long is immutable.
If it wasn't, you would be able e.g. to increment it e.g. by calling
a.increment(1). If that was possible, this is different: you're not
directing the copied reference to a new object, you're using it to call
a method on the original object.
Remember, Java is pass-by-value (always) but certain
differences like these make people confused sometimes.
int are not Objects in Java, so no a is not a reference.

Java:Why changing array' address in a function, does not change its address when we return from that function? [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 9 years ago.
I mean that when we return from that function, the address of the array remains the same address it was before we enterd the function.
an example:
class sdasd {
public static void main(String[] args){
int[] obj = new int [7];
//obj has an address
sdasd t = new sdasd();
t.func(obj);
//obj has the same address as before!!
}
void func(int[] obj){
int[] otherObj = new int[13];
obj=otherObj;``
//we changed the address of the array 'obj'?
}
}
thanks for helping
In the called function obj is copy of the reference to the array. So you have, just when you enter func, what can be described as
main::obj --> int[7];
func::obj --> int[7];
After assigning the new array, you have
main::obj --> int[7];
func::obj --> int[13];
Parameters are passed by value, so a copy of them is created. When it is a reference, the copy of the reference points to the original object; changes to the reference are local to that method (but changes to the object itself are shared by all the references!)
To put the last point in clear, if you had done, instead of assigning a new reference, something like
void func(int[] obj) {
obj[1] = 69;
}
then the change would be visible from main::obj.
That's because the reference to obj is passed by value into func. So in your method func, you've changed the local reference to a new array, but main's obj still refers to the original array. In Java, arrays are objects too, so arrays are declared as references just as normal objects are.
Thats because when you passed obj array to func() it actually created
one copy of your array 'obj' and then passed it as parameter.
So any changes to copy didn't affect your original 'obj'.

Categories