Java Arguments Passed To A Method [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is Java “pass-by-reference”?
Pass by value or Pass by reference in Java?
When we pass the arguments to a method inside a java class. Are the parameters passed in By VALUE or BY REFERENCE as default?
There can be two possibilities,
1. if we pass arguments to a method from another method within the same class.
2. if we pass arguments to a method from another class.
Secondly, if i want to pass values by reference (in case default attribute of java is By Value) then what should i do?

Whatever be the case.. Java is PASS BY VALUE and even references are passed by value
and to get more examples here are few interesting links to read out
http://www.javaworld.com/javaqa/2000-05/03-qa-0526-pass.html
How to do the equivalent of pass by reference for primitives in Java Pass by value or Pass by reference in Java?

I am pretty sure that Java is all pass by value. C/C++ is in to passing by reference. As far as working around passing by reference it is quite easy. As with with C, Java has return type methods. You simply place the variable to the left of the assignment ( = ) operator to call of a method that returns what its new value should be. Plus a few other ways.
String name = "Jon Doe";
name = getName();
String getName()
{
//code to get name goes here.
}

Related

Java implicitly calls intValue when passing Integer as argument [duplicate]

This question already has answers here:
How does auto boxing/unboxing work in Java?
(4 answers)
Closed 2 years ago.
So I came across a bug caused by following example:
I have static method
private static Foo findFoo(int id) {
//we use id here not important
}
Then I used it inside another method like
private static updateFoo(final Integer id, final String newData) {
final Foo existingData = findFoo(id);
// use existing data and update or make new
}
The problem is when updateFoo is called with null in id argument, the intValue() is implicitly called (I think) when calling findFoo(id) and causes NPE.
I thought Java enforces strong typing that prevents cases where Objects are passed to arguments when primitives are expected. Is there a general rule here when implitic calls are made? And could this be picked up by compiler/IDE and possibly enforce or warn?
This always happens if you use a wrapper class as its primitive counter-part. int cannot be null, so you must call intValue() onto the wrapper class.
You can either do a null check before calling findFoo() or just use the primitive int for updateFoo() or the wrapper class in findFoo().
I thought Java enforces strong typing that prevents cases where Objects are passed to arguments when primitives are expected.
The type of Integer fits, so its type is covered. It is just an implicite casting (unboxing) in this case which is totally fine.

Passing params in java by reference [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
How to return multiple objects from a Java method?
(25 answers)
Closed 9 years ago.
I'm a new comer form C#, and I know clearly that "Java is always pass-by-value."
But pass-by-reference is useful when we want to get multiple outputs from one method.
How can we get multiple outputs from one method in java, as in C#.
I know one way to do this -- use a generic wrapper class, and get value from the field.
class Wrapper<T> {
public Wrapper(T value) {
Value = value;
}
public T Value;
}
Is there another way to realize this effect?
No, Java does not have out parameters. You can pass an object reference that the method is to modify to pretend that it has out parameters, but this isn't usually the best design and runs into other issues (multithreading and mutable state for one).
The best way to achieve a method that returns multiple values is to have the method return a type that contains multiple values.
Another way to simulate call by reference in Java is to pass a one-element array as a parameter.

Assign an object to null [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 4 years ago.
If I instantiate an object and pass it to an function, in this function I assign this object to null.
It seems when return from the function, the object still there.
I just want to know when I assign null, what happens.
You can never assign to an object. All you ever have are primitives and references. A reference is either null or a pointer to an object of suitable class.
Java arguments are passed by value. Your called method got a copy of a reference. It made that reference null. The calling method has its own reference which was unaffected by any assignments to the passed copy. That reference still points to the object.
Arguments to methods in Java are 'pass-by-value', which means you are passing a copy of the object reference into the method. Assigning this reference a value of null will change its value within the method call, but does nothing to the reference outside the method, since its a copy. Illustrated with code:
void doSomething(final String input) {
input = null;
System.out.println("Input is: " + input); // prints null
return;
}
final String name = "Bob";
doSomething(name);
System.out.println("Name is: " + name); // prints 'Bob'
when you instantiate an object and pass it to a function, and inside the function you reassign that to null or whatever, at the calling side it is not reflected as arguments are pass by value (copy of reference in case of objects), at calling side it'll still point to the old object. If you want to restrict reassigning in a method, you can use final keyword in method parameter
When you pass the object reference to a function(Java always call it method),in the method scope,a new reference is created on stack memory,but they point to the same object in heap memory.So if you assign null to the new reference,Only this reference's link to that object is break,It does not affect the prevous one.

"..." being used in Java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can I pass an array as arguments to a method with variable arguments in Java?
What is … in a method signature
I first saw this when I was modding Minecraft. It had a constructor that specified (String ... line), and thought it was just some shorthand that Mojang had created. But now, I was looking over ProcessBuider, and saw it again. I was wondering what this is used for. My best guess is that it allows developers to add as many of that type of object as they want. But if that's the case, why not just use an Array or List?
So, really, I am asking two questions:
What is the "..." operator, and
Why would it be more useful than using an Array or List?
... indicates a multiple argument list to a variadic function: a function that can take a variable number of arguments.
For an example of this, look at PrintStream.format. The first (required) argument is a format String, and the remaining 0 or more arguments fulfill that format.
It is called varargs, and as you say it is used to be able to let a method be called with any number of arguments of the specified type. It was introduced in Java 5.
You can read more in the Java tutorials - Varargs.
This is equivalent to a String[] line. It is Java's equivalent to the varargs keyword in C/C++. Similar to C/C++ it must appear as the last parameter.
You've already answered question #1 yourself. As to why it's more useful, it's just a shorthand that requires less typing.
To answer your second question, one advantage of varargs is that you can call a function taking varargs parameter without passing that param. Whereas instead if your function takes in an array, and you need to call it without any value, the caller needs to explicitly pass null.

Java is NEVER pass-by-reference, right?...right? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is Java “pass-by-reference”?
I found an unusual Java method today:
private void addShortenedName(ArrayList<String> voiceSetList, String vsName)
{
if (null == vsName)
vsName = "";
else
vsName = vsName.trim();
String shortenedVoiceSetName = vsName.substring(0, Math.min(8, vsName.length()));
//SCR10638 - Prevent export of empty rows.
if (shortenedVoiceSetName.length() > 0)
{
if (!voiceSetList.contains("#" + shortenedVoiceSetName))
voiceSetList.add("#" + shortenedVoiceSetName);
}
}
According to everything I've read about Java's behavior for passing variables, complex objects or not, this code should do exactly nothing. So um...am I missing something here? Is there some subtlety that was lost on me, or does this code belong on thedailywtf?
As Rytmis said, Java passes references by value. What this means is that you can legitimately call mutating methods on the parameters of a method, but you cannot reassign them and expect the value to propagate.
Example:
private void goodChangeDog(Dog dog) {
dog.setColor(Color.BLACK); // works as expected!
}
private void badChangeDog(Dog dog) {
dog = new StBernard(); // compiles, but has no effect outside the method
}
Edit: What this means in this case is that although voiceSetList might change as a result of this method (it could have a new element added to it), the changes to vsName will not be visible outside of the method. To prevent confusion, I often mark my method parameters final, which keeps them from being reassigned (accidentally or not) inside the method. This would keep the second example from compiling at all.
Java passes references by value, so you get a copy of the reference, but the referenced object is the same. Hence this method does modify the input list.
The references themselves are passed by value.
From Java How to Program, 4th Edition by Deitel & Deitel: (pg. 329)
Unlike other languages, Java does not allow the programmer to choose whether to pass
each argument by value or by reference. Primitive data type variables are always passed
by value. Objects are not passed to methods; rather, references to objects are passed to
methods. The references themselves are passed by value—a copy of a reference is passed
to a method. When a method receives a reference to an object, the method can manipulate
the object directly.
Used this book when learning Java in college. Brilliant reference.
Here's a good article explaining it.
http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
Well, it can manipulate the ArrayList - which is an object... if you are passing an object reference around (even passed by value), changes to that object will be reflected to the caller. Is that the question?
I think you are confused because vsName is modified. But in this context, it is just a local variable, at the exact same level as shortenedVoiceSetName.
It's not clear to me what the exact question within the code is. Java is pass-by-value, but arrays are pass-by-reference as they pass no object but only pointers! Arrays consist of pointers, not real objects. This makes them very fast, but also makes them dangerous to handle. To solve this, you need to clone them to get a copy, and even then it will only clone the first dimension of the array.
For more details see my answer here: In Java, what is a shallow copy? (also see my other answers)
By the way, there are some advantages as arrays are only pointers: you can (ab)use them as synchronized objects!

Categories

Resources