Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

3. Introduction to Java

Uploaded by

23020661
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

3. Introduction to Java

Uploaded by

23020661
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Introduction to Java

Vũ Thị Hồng Nhạn

(vthnhan@vnu.edu.vn)

Dept. of Software Engineering, UET

Vietnam National Univ., Hanoi


Contents
 Primitive data types & objects
 Reference parameter
 Garbage collection

10/9/2024 Introduction to Java Page 2


Data types
 Java has 2 categories of data
 Primitive data (e.g., number, character)
 Object data (programmer created types)

10/9/2024 Introduction to Java Page 3


Primitive data types
Number • byte, short, int, long, float, double
• unsigned doesn’t exists in Java

logic boolean
char char

 Primitive data is not an object


 int a=5;
 if(a==b)…

 The corresponding class of an Integer object: Integer


 Integer count = new Integer(0);
 Refer to the link for more details:
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html

10/9/2024 Introduction to Java Page 4


Primitive data types…
data Size min value max value
type (bits)

char 16 0x0 0xffff

byte 8 -128 or (-27) +127 or (27-1)

short 16 -32768 or (-215) 32767 (215-1)

int 32 - 231, 0x80000000 + 231 - 1, 0x7fffffff

long 64 - 263 + 263 - 1

float 32 1.40129846432481707e-45 3.40282346638528860e+38

double 64 4.94065645841246544e-324 1.79769313486231570e+30


8
boolean 1 true; false

10/9/2024 Introduction to Java Page 5


Where are data stored?
 Primitive data
 Works via variables

 Attributes of objects are responsible for storing data


 Objects work via reference variables

 Where are primitive variables, reference & objects stored?

10/9/2024 Introduction to Java Page 6


Memory

• Class-level data static memory


• Static variables
• Constants

stack memory
• Local variables
• Method call information

Dynamic data
• Objects & instance
variables created using heap memory
new

10/9/2024 Introduction to Java Page 7


Java objects stored in heap
 In java, all objects are dynamically allocated on Heap

 This is different from C++ where objects can be allocated memory either
on Stack or Heap

 Java doesn’t have pointers, java has references

10/9/2024 Introduction to Java Page 8


Java reference
 A reference is a variable that refers to something
 Pointer is a variable that stores a memory address (i.e., pointer is a
reference, but reference is not a pointer)

 When a variable of a class type is declared

 Only a reference is created

 Memory is not created for the object

 To allocate memory to an object, we must use new

10/9/2024 Introduction to Java Page 9


new operator in Java
 The new operator
 dynamically allocates memory for a new object
 and returns a reference to that memory
 This reference is then stored in the variable we declared for the object

 Following the new operator is a class constructor, which initializes the new
object

statements Effects
class Box {
double width;
double height;
double depth;

}

10/9/2024 Introduction to Java Page 10


Assignment operator “=“
 For primitive data, assign a value for a primitive variable
 For an object, two references refer to the same object

int x=10, y=20;

x=y;
x=50;

System.out.println(y); Box x=new Box(1,1,1);


Box y=new Box(2,2,2);
x=y;
x.setWidth(50);
System.out.println(y.getWidth());

10/9/2024 Introduction to Java Page 11


“new” vs. “=“
class MyDate{
int d; int m; int y
MyDate(int d,int m, int y ){this.d=d; this.m=d; this.y=y;}
}
 MyDate d;
 MyDate birthday;
 d= new MyDate(26,9,2005);
 birthday = d; Static/Stack memory
Heap memory
d
26/9/2005
birthday

10/9/2024 Introduction to Java Page 12


== operator
 Can apply for every primitive types (e.g., int, char, double, boolean…)
 Can use for reference comparison
 i.e., check if both objects point to the same memory location

String s1= new String(“Hello”);

String s2= new String(“Hello”);

String s3 = s2;

System.out.println(s1==s2); // false

System.out.println(s2==s3);// true

10/9/2024 Introduction to Java Page 13


Compare two objects
class MyDate{
int d; int m; int y
MyDate(int d, int m, int y){this.d=d; this.m=m; this.y=y;}
MyDate(MyDate date){d=date.d; m=date.m; y=date.y;}

boolean equalTo(MyDate date)


{return d==date.d && m==date.m && ty==date.y; }
}
MyDate d1= new MyDate(1,1,1954);
MyDate d2= new MyDate(d1);
MyDate d3= new MyDate(10,10,1954);

System.out.println(d1.equalTo(d2));

System.out.println(d1.equalTo(d3));

10/9/2024 Introduction to Java Page 14


Method overloading
 A class can have more than one method having the same name,
however their parameters must be different
 It’s similar to constructor overloading in Java mentioned before!

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

Passing value to function


public class Main  Like C/C++, Java creates a
{
public static void main(String[] copy of the variable being
args) passed in the method and
{
int x = 5; placed in Stack and then do
change(x); the manipulation
System.out.println(x);
}
public static void change(int x)  Hence, the change is not
{ reflected in the main method
x = 10;
}
}

 Output: ?5

10/9/2024 Introduction to Java Page 16


Class object

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

10/9/2024 Introduction to Java Page 17


Passing objects/references…
class Test {
int x;
Test(int i) { x = i; }
}
class Main { class Main {
public static void main(String[] args) public static void main(String[] args)
{ {
Test t = new Test(5); Test t = new Test(5);
change(t); change(t);
System.out.println(t.x); System.out.println(t.x);
} }
public static void change(Test t) public static void change(Test t) {
{ t.x = 10; } t = new Test();
} t.x = 10; }
}

Output: ?10 Output: ? 5

10/9/2024 Introduction to Java Page 18


Passing objects/references…
class MyDate{
int year, month, day;
MyDate(){year=0; month=0; day=0;}
public MyDate(int year, int m, int d){
this.year=year; month=m; day=d;
}
public void copyTo(MyDate d){
d.year=year; d.month=month; d.day=day;
}
public MyDate copy(){
return new MyDate(day, month, year);
}
}

10/9/2024 Introduction to Java Page 19


Passing objects/references…
MyDate d1= new MyDate(2009, 9, 9);
MyDate d2= new MyDate(2001,1,1);
d1.copyTo(d2);
d2.getYear(); //???
MyDate d3 = new MyDate();
d3= d1.copy();

How many MyDate objects were created?

10/9/2024 Introduction to Java Page 20


this reference
“this” reference
 “this” is a reference variable that refers to the current object
1. Using “this” keyword to refer current class instance variables

class Test {
int a;
int b;
Test(int a, int b)
{
this.a = a;
this.b = b;
}
}

10/9/2024 Introduction to Java Page 22


“this” reference…
2. Using this keyword to invoke current class method

//Định nghĩa lớp


class Test {
void display(){
this.show();
System.out.println(“outside show()”);
}
void show(){System.out.println(“inside show()”);}
}
Output:
Test object = new Test();
inside the show function
object.display(); //??? inside the display function

10/9/2024 Introduction to Java Page 23


“this” reference…
3. Using this() to invoke the current class constructor
class Test
{
String name; int age;
Test(String name, int age){ this.name=name; this.age=age; }
Test()
{
this(“Me”, 20);
}
Test(String name){
this(name,20);// constructor call must be the first
//statement in the constructor
System.out.println("Inside default constructor");
}
}

10/9/2024 Introduction to Java Page 24


“this” reference…
4. Using this keyword to return the current class instance
class Person {
String name; int age;
Person() { name = “Mimi”; age = 0; }

//Method that returns current class instance


Person getPerson() { return this; }
Person setName(String name){this.name=name; return this;}

void display(){
System.out.println(name + “ “ + age);
}
}
Person p = new Person();
p.getPerson().display(); //?
p.setName(“Lili”).display(); //?

10/9/2024 Introduction to Java Page 25


“this” reference…
5. Using this keyword as a method parameter
class Test {
String a; int b;
Test()
{ a = null; b = 200; }
void display(Test obj){
System.out.println( obj.a + “, ” obj.b);
}
void get() {display(this);}
}
….
Test object = new Test();
object.get(); //??? Output: null, 200

10/9/2024 Introduction to Java Page 26


“this” reference…
6. Using this keyword as an argument in the constructor call
class Engine{
Car car;
Engine(Car car){this.car=car;}
void startEngine(){System.out.println(“Engine started ”+car.model);}}
class Car{
String model;
Engine engine;
Car(String model){this.model = model; engine= new Engine(this);)
void startCar(){
engine.startEngine();}
}
Car car= new Car(“Kia”);
car.startCar();

10/9/2024 Introduction to Java Page 27


Garbage collector
Garbage collection (GC)
 in C/C++ programmer is responsible for both creation & destruction of
objects

 Usually programmer neglects destruction of useless objects

 In Java, the programmer need not to care for all those objects which are
no longer in use

 Garbage collector destroys these objects

 Main objective of Garbage collector is to free heap memory by destroying


unreachable objects

10/9/2024 Introduction to Java Page 29


GC

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

• MyDate startDate = new MyDate(10,10,2005);


• openDate = startDate;
this object is no longer reachable

openDate X 1-10-2005
Heap area

startDate 10-10-2005


openDate =null; startDate =null; //the 2nd MyDate object is no longer
reachable

10/9/2024 Introduction to Java Page 30


GC

Ways to make an object eligible for GC

 Even though programmer is not responsible for destroying useless


objects but it is highly recommended to make an object unreachable if it
is no longer required

 4 different ways to make an object eligible for GC

 Nullifying the reference variable

 Re-assigning the reference variable

 Object created inside method

 Island of isolation

 is a group of objects that reference each other but they are not referenced by any active
object in the application

10/9/2024 Introduction to Java Page 31


GC

Ways for requesting JVM to run Garbage collector

 There are 2 ways to request JVM to run Garbage Collector

 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

10/9/2024 Introduction to Java Page 32


Example 1
public class Test{
public static void main(String[] args) throws InterrupedException{
Test t1= new Test()
Test t2= new Test();

//till here, no object’s eligible for GC

t1=null; //1 object eligible for GC


t2= null; //now 2 object eligible for GC
System.gc();//Calling garbage collector
}

//override finalize method which is called on object once before garbage


collecting it
protected void finalize() throws Throwable {
System.out.println(“ Finalize method called!”);
}
}

10/9/2024 Introduction to Java Page 33


Example 2: Island of isolation
public class Test{
Test test;
public static void main(String[] args) throws InterrupedException{
Test t1= new Test();
Test t2= new Test();
t1.test =t2,
t2.test=test;

t1=null; //this object eligible for GC


System.gc();//requesting JVM for running Garbage Collector

t2= null; //this object eligible for GC


Runtime.getRuntime().gc(); //requesting JVM for running Garbage Collector
Thread.sleep(100);//give time to GC to run before program terminates, not
guarantee otherwise!
}
//override finalize method which is called on object once before garbage collecting it
protected void finalize() throws Throwable {
System.out.println(“ Garbage collector called”);
System.out.println(“Object garbage collected” + this);
}
}
10/9/2024 Introduction to Java Page 34
GC

Finalization
 Before destroying an object, Garbage Collector calls finalize() method
on the object to perform cleanup activities

 Once finalize() method completes, Garbage Collector destroys that object

 finalize() method is present in Object class with following


prototype

 protected void finalize() throws Throwable

10/9/2024 Introduction to Java Page 35


GC

Notes
 In the previous example of GC

 There’s no guarantee that any of the methods will definitely run Garbage
Collector

 Because the finalize() method is called by Garbage Collector not JVM

 finalize() method of Object class has empty implementation

 so it is recommended to override finalize() method to dispose of the system


resources

10/9/2024 Introduction to Java Page 36

You might also like