Skip to content

Instantly share code, notes, and snippets.

@shah-smit shah-smit/output.txt
Last active Apr 26, 2017

Embed
What would you like to do?
Pass By Value and Pass By Reference JAVA
1
2
11
12
12
10
A
public class tests
{
public static void main(String args[])
{
// PASS BY REFERENCE
int[] arr = {1,2};
for(int i=0; i<arr.length; i++)
{
System.out.println(arr[i]);
}
passByReference(arr);
for(int i=0; i<arr.length; i++)
{
System.out.println(arr[i]);
}
p(arr);//here i am passing arr, but in the method it is creating a new instace, thus this will perform as pass by value
// PASS BY VALUE
String val = "12";
passByValue(val);
System.out.println(val);
int num = 10;
passByValue(num);
System.out.println(num);
char charVal = 'A';
passByValue(charVal);
System.out.println(charVal);
}
static void passByReference(int[] num)
{
for(int i=0; i<num.length; i++)
{
num[i] += 10;
}
}
static void passByValue(String val)
{
val = "has gone through pass";
}
static void passByValue(int val)
{
val += 10;
}
static void passByValue(char val)
{
val += 10;
//val = val + 10; //compile time error
}
static void p(int [ ] m)
{
m= new int[3]; m[0]=7;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.