This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 3 years ago.
this is the test code I am using to understand how java handles object memory.
public class TestCode {
public static void main(String[] args) {
TestCode obj = new TestCode();
CustomClass cs1 = new CustomClass(5);
obj.updateExistingObj(cs1);
System.out.println(cs1.val);
CustomClass cs2 = new CustomClass(5);
obj.instantiateExistingObj(cs2);
System.out.println(cs2.val);
CustomClass cs3 = null;
obj.updateNullObj(cs3);
System.out.println(cs3.val);
}
void updateExistingObj(CustomClass cs1) {
cs1.val = 9;
}
void instantiateExistingObj(CustomClass cs2) {
cs2 = new CustomClass(9);
}
void updateNullObj(CustomClass cs3) {
cs3 = new CustomClass(9);
}
}
class CustomClass {
int val;
CustomClass next;
CustomClass(int x) { val = x; }
}
The output of the first syso where I am printing cs1.val I am getting expected value which is 9.
The output of the second syso where I am printing cs2.val I am getting 5 as output instead of 9.
The output of the third syso where I am printing cs3.val I am getting a null pointer exception.
Can anybody help me understand what is happening here under the hood? How exactly java handles the memory location when we pass an object as a function parameter? Thanks for helping!!
cs2 and cs3 are local variable, assigning a new value to them have no effect outside of the methods where they are declared.
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I'm writing a program which utilizes OOP. The program I am creating is supposed to recruit applicants to a team. In my Team.java, I created a method which is supposed to accept members and add it to the team. This is a snippet of my code:
public int maxMembers;
public Member members[] = new Member[maxMembers];
public int memberCount = 0;
public void addMember(Member newMember) {
members[maxMembers] = newMember;
memberCount++;
}
I have tried this code but the line,
members[maxMembers] = newMember;
keeps throwing an error java.lang.ArrayOutOfBoundsException: 2
I have tried using a for loop in adding a new member but it does not do what I expected. Can anyone assist me in finding a solution?
You have to assign maxMembers a value in the first line, otherwise your array will have 0 elements.
public int maxMembers = 10;
Firstly, you did not initialize the variable maxMembers.Also, in the code, the line members[maxMembers] = newMember; would always put your entry in the end of the array, I think thats not the intended use of your method, public void addMember(Member newMember)
Rewriting your method would look like,
public int maxMembers=somePositiveInteger;
public Member members[] = new Member[maxMembers];
public int memberCount = 0;
public void addMember(Member newMember) {
members[memberCount] = newMember;//here
memberCount++;
}
Initialize the array with a value so that number of elements in array can be decided.
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 5 years ago.
Here is my example: I want to know if it is possible to pass an argument initialized with null, and later initialize the object with a correct value.
private class Source {
String str;
String getStringValue() {
return str;
}
void setStringValue(String str) {
this.str = str;
}
}
private class UserSource {
Source src;
UserSource(Source src) {
this.src = src;
}
String getValue() {
return src.getStringValue();
}
void setValue(String str) {
src.setStringValue(str);
}
}
Now how I'm using.
Source srcW = new Source();
UserSource userSourceW = new UserSource(srcW);
srcW.setStringValue("Second Value");
System.out.println("From UserSource:" + userSourceW.getValue());
userSourceW.setValue("Is not Second");
System.out.println("From Source:" + srcW.getStringValue());
The output:
From UserSource:Second Value
From Source:Is not Second
But, want to know if is possible to use like:
Source srcN = null; // YES I want to assign Not initialized!
UserSource userSourceN = new UserSource(srcN);
srcN = new Source();
srcN.setStringValue("First Value");
System.out.println("From UserSource:" + userSourceN.getValue());
Of course the output is
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
Is there an alternative?
Unfortunately, it's not possible to do so. When the value is initially null, then you're passing the null reference. Later you initialize it with srcN = new Source();, but then you're rewriting the source.
You could work around it with a Reference<Source>. But that would only make the code more cumbersome. Moreover, the Source class is a perfect candidate to pass it as an empty source, and then initialize it later with setString().
Am I missing something? What's your problem with the code as is?
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 7 years ago.
{
int[] n = new int[4];
n[0]=1;
n[1]=3;
n[2]=4;
n[3]=5;
for(int i=0; i<4; i++)
{
System.out.print(n[i]+ " ");
}
menjava(n);
System.out.println();
for(int i =0;i<4;i++)
{
System.out.print(n[i]+ " ");
}
}
public static void menjava(int[] a)
{
a[0]=1*10;
a[1]=3*10;
a[2]=4*10;
a[3]=5*10;
}
}
http://imgur.com/0CNqY9A //the result in console
{
int n = 1;
System.out.println(n);
menjava(n);
System.out.println(n);
}
public static void menjava(int st)
{
st = 4;
}
}
http://imgur.com/dAqzuez //the result in console
So why did the Array get returned, but the integer stayed the same (whcih in my mind should). I can't find anything on why the array get's returned in an void function.
The reference to the array is not returned nor changed.
The array referenced has been changed.
int[] n = new int[4];
In this code n is a reference to an array and this reference is copied when you pass it to a method. This reference is not changed.
Your issue here is that Java is a pass by value language. This means in your situation you are providing your method menjava with what might as well be a temporary array that contains the same values as your original array n. So when this array is passed to menjava it does the calculations, but to this temporary array that your main method doesn't know about.
The easiest fix here is to have your menjava method return the array it worked on and set your array to that value in the calling function something like this:
public static int[] menjava(int[] a){
//changes to array a
return a;
}
and then in your calling function:
{
//your other code
n = menjava(n);
//the rest of your code
}
This question already has answers here:
how to explain return statement within constructor?
(6 answers)
Closed 7 years ago.
I don't know what is the usage return;. What does it mean ? Does it return something ? I think return keyword use to put back some value but I am not sure because if constructors return only instance of class below code should be invalid.
public class Test {
public Test() {
return;
}
}
Any suggestions ?
It does not returns anything.
It means the end of any method which returns void, so in this case, it means the end of the constructor. See the example below:
class Test {
private int sum;
public Test(Object otherObj) {
if (otherObj != null){
sum = 42;
return;
}
sum = 0;
}
public static void main(String[] args) {
Test testZero = new Test(null);
Test testNonZero = new Test(testZero);
System.out.println(testZero.sum); // 0
System.out.println(testNonZero.sum); // 42
}
}
if the otherObj is not null, the sum'll be 42, and the constructor will stop running.
You can use the same strategy, if you have a public void someFunction() method, to exit at some point.
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 7 years ago.
I have a very basic doubt in Java.
Here is a code I have written. From a method in class A in package A, I try to instantiate an object of class b of a different package and call its method, to which I pass a list.
parseObjectList = new ArrayList<ParseObject>();
pullAllService.pullAllData(queryType,parseObjectList);
and in the function I do some manipulation:
public void pullAllData(String queryType,List<ParseObject> parseObjectList)
{
ParseQuery<ParseObject> query = null;
List<ParseObject> parseObjects = parseObjectList;
if(queryType.equals("a"))
{
query = new ParseQuery<ParseObject>("a");
}
else if(queryType.equals("b"))
{
query = new ParseQuery<ParseObject>("b");
}
try {
parseObjects = query.find(); //I get the list
/* final List<ParseObject> finalParseObjectList = parseObjectList;
curActivity.runOnUiThread(new Runnable() {
public void run() {
ToastMessageHelper.displayLongToast(curActivity, "Objects found : ");
for (int i = 0; i < finalParseObjectList.size(); i++) {
ToastMessageHelper.displayLongToast(curActivity, finalParseObjectList.get(i).get("Name").toString());
System.out.println();
}
}
});
*/
} catch (ParseException e) {
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
}
after which if I try to print the list in class A's method. I get an empty list.
But if I do this,
parseObjectList = new ArrayList<ParseObject>();
parseObjectList = pullAllService.pullAllData(queryType,parseObjectList);
and make it return the list from pullAllData() (by changing the return type and returning the list) , I get the list with the expected data.
I thought that just by passing the parseObjectList into the function, the passed parameter would behave as a reference and automatically be assigned the intended data. What's wrong here?
Java is a pass by value language. Passing a List reference to a method allows the method to mutate the List referenced by the reference, but it can't change the value of the List reference that was passed to it.
You can do something like this to add the elements to the list that was passed to your method :
parseObjectList.addAll(query.find());