Value types and reference types
- Value type: Holding data in associated memory location
-
-
byte
-
short
-
int
-
long
-
float
-
double
-
char
-
boolean
-
- Reference type: Holding a reference to an object
-
Array or class instances i.e.
String
,java.util.Scanner
etc.
Value type |
|
a=5 b=1 |
Reference type |
|
r=Joe Simpson s=Joe Simpson |
|
Before printDuplicateValue: 3 printDuplicateValue: 6 After printDuplicateValue: 3 |
|
Before duplicateString: My After duplicateString: MyMy |
Figure 338. No «call-by-reference» in Java™!
|
Before duplicateString: My After duplicateString: My |
int a = 1;
int &b = a;
cout << a << " : " << b << endl;
a = 5;
cout << a << " : " << b << endl; |
1 : 1 5 : 5 |
// Passing a reference // to variable n void printDuplicateValue(int& n) { n = 2 * n; cout << "duplicateValue: " << n << endl; } int main() { int value = 3; cout << "Before call: " << value << endl; printDuplicateValue(value); cout << "After call: " << value << endl; } |
Before call: 3 duplicateValue: 6 After call: 6 |