Lecture03 Annotated
Lecture03 Annotated
Lecture03 Annotated
}
}
Conversion between primitive
types
• Widening conversions : from a small data
type to a larger one.
byte -> short -> int -> long -> float -> double
• Narrowing conversions: Can lose
information because they tend to go from a
large data type to a smaller one (such as an
int to a short)
•
Casting
• Both types of conversions can be achieved
by explicitly casting a value.
• To cast, the type is put in parentheses in
front of the value being converted.
"ABC"
20
car1 100
Stack Heap
Variable lifetime
• When a method is invoked, the parameters
are first pushed onto the stack. When the
method is entered, additional space on the
stack is reserved for all local variables. The
method's code is then executed.
• When the method finishes, it releases the
space on the stack occupied by its local
variables and parameters automatically:
they no longer exist.
Garbage collection
• To manage heap memory, Java maintains a
reference count of how many reference
variables point to it.
• Reference count drops to zero-> the object
is eligible for garbage collection which
reclaims the heap space used by the object.
• Garbage collection relieves the programmer
from the responsibility of releasing
dynamically allocated heap memory.
Reference variable and assignment
minivan Memory
Stack
v=minivan;
Garbage
v collected
minivan
Stack
public class Car {
String licensePlate;
double speed;
double maxSpeed;
double fuel;
public Car(String plateNumber, double speedVal, double maxVal){
licensePlate=plateNumber;
speed=speedVal;
maxSpeed=maxVal;
}
public Car(){
}
}
public class CarTest {
public static void main(String[] args){
Car miniVan;
miniVan=new Car("ABC", 50, 100); Which object will be
Car sedan = new Car();
sedan=miniVan; Garbage collected after
}
} execution of this line?
Arrays
• An array stores multiple values of the same
type.
• That type can be primitive types or objects
• Array of size N is indexed from zero to N-1.
Declaring Arrays
int [] scores;
scores=new int[10];
int scores[10];
Initializing Arrays
int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476};
char[] letterGrades = {'A', 'B', 'C', 'D', ’F'};
Accessing Array elements
int scores[3];
scores[0] = 79;
scores[1] = 87;
scores[2] = 92;
mean = (scores[0] + scores[1]+scores[2])/3;
System.out.println ("Average = " + mean);
Accessing Array elements
int scores[3];
scores[0] = 79;
scores[1] = 87;
scores[2] = 92;
mean = (scores[0] + scores[1]+scores[2])/3;
System.out.println ("Average = " + mean);
class HeapQuizTest{
public static void main (String [] args) {
int x = 0;
HeapQuiz [] hq = new HeapQuiz[5];
while (x < 3) {
hq[x] = new HeapQuiz();
hq[x].id = x;
x =x +1; }
hq[3] =hq[1];
hq[4] =hq[1];
hq[3] =hq[2];
for (int j=0; j<5; j++)
System.out.println ("hq["+j +"]:"+hq[j].id);
}
}
}