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.Scanneretc.
| Value type | |
a=5 b=1 |
| Reference type | |
r=Joe Simpson s=Joe Simpson |
public static void main(String[] args) {
int value = 3;
System.out.println(
"Before printDuplicateValue: "
+ value);
printDuplicateValue(value);
System.out.println(
"After printDuplicateValue: "
+ value);
}
static void printDuplicateValue(int n) {
n = 2 * n;
System.out.println(
"printDuplicateValue: " + n);
} |
Before printDuplicateValue: 3 printDuplicateValue: 6 After printDuplicateValue: 3 |
|
Before duplicateString: My After duplicateString: MyMy |
Figure 347. 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 |
