Click here to Skip to main content
15,896,456 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Java
class Main {
static void m (int[] i) {
i[0] += 7;
}
public static void main (String[] args) {
int[] j = new int[1];
j[0] = 12;
m(j);
System.out.println(j[0]);
}
}


output
19

Here j and i points to the same address so the value gets changed for i too.

What I have tried:

Java
class Main {
static void m (int i) {
i += 7;
}
public static void main (String[] args) {
int j;
j= 12;
m(j);
System.out.println(j);
}
}


output
12



Java
class Main{
static void m(String s1) {
s1=new String("acting");

}
public static void main(String[] args) {
String s2 = new String("action");
m(s2);
System.out.println(s2);
}
}


output
action

here separate memory will be created for s1 and s2 so this output makes sense for me.

Java
class Main{
static void m(String s1) {
s1="acting";

}
public static void main(String[] args) {
String s2 ="action";
m(s2);
System.out.println(s2);
}
}


output
action

But here the string literals will be pointing to the same location and then too the value of s2 is not changed. Could anyone explain me clearly?
Posted
Updated 18-Jul-18 0:40am
v2

See here: Java Method Arguments[^].
 
Share this answer
 
With Java, all paramters are passed by value. That means a function gets a copy of the original reference when passing objects like strings. Because strings are Immutable Objects (The Java™ Tutorials > Essential Classes > Concurrency)[^], a new string is created and assigned to the copy of the reference while the original is left unchanged.

But when using an array, the copy of the reference is unchanged (still the same value as the original) so that array items can be changed.

See also the SO thread c - Passing a String by Reference in Java? - Stack Overflow[^] which also provides solutions to modify a string passed as function parameter.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900