Objects and Variables Local variables – Confined to single context: allocated on stack –...
-
Upload
claribel-roberts -
Category
Documents
-
view
223 -
download
0
Transcript of Objects and Variables Local variables – Confined to single context: allocated on stack –...
Objects and Variables
• Local variables– Confined to single context: allocated on stack– Primitive types such as int or object references– Must be initialized before use (or fail compilation)
• Objects– Shared among multiple procedure contexts– Allocated on heap using new operator– Can be initialized after creation (by constructor)
1
Variables and Objects: Example
int i = 6;int j;int [] a = {1, 3, 5, 7, 9};int [] b = new int[3];String s = “abcdef”;String t = null;j = i;b = a;t = s;
Stack
i = 6
j
a
b
s
t = null
1 3 5 7 9
heap
0 0 0
“abcdef”
j = 6
t
2
Object references
• All object references are uninitialized initially– Can be initialized to null, but not necessary
• Need to explicitly allocate the object on the heap or assign it to (the start of ) an existing object– No pointer arithmetic possible once assigned– No need to explicitly de-allocate the reference
(garbage collection frees it when not in use)
• Can be passed to procedures and copied around3
Example of Objects and References
{ Object b = null; {
Object a = new Object();b = a;
} c = b.hashCode();}
4
Reference b is allocated on stackand initialized to null
Reference a is allocated on stack
Object is allocated on the heap and reference a points to it
b and a both point to the same object
a goes out of scope, so only b points to object
b goes out of scope too, so nobody points to the object.Object is automatically reclaimed by garbage collector
1 3 5 7 91 3 5 -1 9
Object Mutability
• By default, Java objects are mutable– Modifications made through one reference
will be visible when the object is accessed through another reference to the object
• Example: Arrays– int [] a = {1, 3, 5, 7, 9};– a[3] = -1;– b = a;– b[4] = -2;
1 3 5 -1 -25
Exception: Immutable objects
• State of immutable object never changes once it is assigned
• Example: String objectString s1 = “abcdef”;String s2 = “ghij”;String s3 = s1;s3 = s1 + s2;String s4 = s3;s4 = s2 + s1;
“abcdef”
“ghij”
“abcdefghij”
“ghijabcdef”
6
Heap
Group Activity: Try it yourself
What happens after these ?int[ ] a = {1, 2, 3};int[ ] b = new int[2];int[] c = a;int x = c[0];b[0] = x;a[1] = 6;x = b[1];int y = a[1];
What happens after these ?String s1 = “ace”;String s2 = “f”;String s3 = s1;String s4 = s3 + s2;s1 = s4;s4 = s1 + s2;
7