So can someone give a live example of a language which is pass by reference by whose example we could relate that java is not pass by reference
The best example of Pass-by-ref vs pass-by-value is swap.
void swap(String a, String b) { String c = b; b = a; a = c; } void main() { String a = "A"; String b = "B"; swap(a, b); System.out.println(a); // A System.out.println(b); // B }
In this case while the variable main.a points to the same object as swap.a, you have two references to the string "A".
vs C# (IDE One) which supports by-ref.
void Swap(ref string a, ref string b) { string c = b; b = a; a = c; } void main() { string a = "A"; string b = "B"; Swap(ref a, ref b); Console.WriteLine(a); // B Console.WriteLine(b); // A }
In this case the variable main.a and swap.a are the same reference, so changes to swap.a also happen to main.a.
So how does this differ from
void swap(StringBuilder a, StringBuilder b) { String a1 = a.toString(); String b1 = b.toString(); a.setLength(0); a.append(b1); b.setLength(0); b.append(a1); } void main(){ StringBuilder a = new StringBuilder("A"); StringBuilder b = new StringBuilder("B"); swap(a, b); System.out.println(a); // B System.out.println(b); // A }
In this case the objects pointed to get changed. For example:
public static void main(String... agv){ StringBuilder a = new StringBuilder("A"); StringBuilder b = new StringBuilder("B"); StringBuilder alsoA = a; swap(a, b); System.out.println(a); // B System.out.println(b); // A System.out.println(alsoA); //B }
vs in C# (IDEOne)
void Main() { string a = "a"; string b = "b"; string alsoA = a; Swap(ref a, ref b); Console.WriteLine(a); // B Console.WriteLine(b); // A Console.WriteLine(alsoA); // A }
Java Ranch has a good article if you are still unsure.
Objecttypes have a value that is a reference.refmodifier for pass-by-reference parameters. See pobox.com/~skeet/csharp/parameters.html