3. Introduction to Java
3. Introduction to Java
(vthnhan@vnu.edu.vn)
logic boolean
char char
stack memory
• Local variables
• Method call information
Dynamic data
• Objects & instance
variables created using heap memory
new
This is different from C++ where objects can be allocated memory either
on Stack or Heap
Following the new operator is a class constructor, which initializes the new
object
statements Effects
class Box {
double width;
double height;
double depth;
…
}
x=y;
x=50;
String s3 = s2;
System.out.println(s1==s2); // false
System.out.println(s2==s3);// true
System.out.println(d1.equalTo(d2));
System.out.println(d1.equalTo(d3));
class Game{
…
public void setScore(int sore){…}
public void setScore(String s){…}
}
…
g.setScore(10);
g.setScore(“Ten”);
10/9/2024 Page 15
Primitive data type
Output: ?5
Passing objects/references
All non-primitives are always references
When passing object references to methods
Java creates a copy of references and pass it to method
but they still point to the same memory reference
class Test {
int a;
int b;
Test(int a, int b)
{
this.a = a;
this.b = b;
}
}
void display(){
System.out.println(name + “ “ + age);
}
}
Person p = new Person();
p.getPerson().display(); //?
p.setName(“Lili”).display(); //?
In Java, the programmer need not to care for all those objects which are
no longer in use
Unreachable objects
An object is said to be unreachable iff it doesn’t contain any reference to
it
MyDate openDate = new MyDate(1,10,2005); //The new MyDate object is reachable
via the reference in openDate
openDate X 1-10-2005
Heap area
startDate 10-10-2005
openDate =null; startDate =null; //the 2nd MyDate object is no longer
reachable
Island of isolation
is a group of objects that reference each other but they are not referenced by any active
object in the application
Using System.gc()
System class contain static method gc() for requesting JVM to run Garbage
Collector
Using Runtime.getRuntime().gc()
Runtime class allows the application to interface with the JVM in which the
application is running
Finalization
Before destroying an object, Garbage Collector calls finalize() method
on the object to perform cleanup activities
Notes
In the previous example of GC
There’s no guarantee that any of the methods will definitely run Garbage
Collector