More on Java
Object-Oriented Programming
Outline
Instance variables vs. local variables
Primitive vs. reference types
Object references, object equality
Objects' and variables' lifetime
Parameters passing and return values
Methods overloading
this reference
Input/Output
Readings:
HFJ: Ch. 3, 4.
GT: Ch. 3, 4.
Đại học Công nghệ - ĐHQG HN More on Java 2
Variables and types
Two kinds of variables: primitive and object reference.
primitive variables hold fundamental types
of values: int, float, char…(*)
byte a = 7;
boolean done = false;
reference variables hold references to objects
(similar to pointers)
Dog d = new Dog();
[Link] = "Bruno";
[Link]();
Đại học Công nghệ - ĐHQG HN More on Java
(*) read textbook 3
Primitive data types
Java’s primitive types:
Numerical: byte, int, long, float, double
Logical: boolean (true/false)
Characters: char
Primitive data are NOT objects
There’re corresponding wrapper classes, useful
when we want to treat primitive values as objects
Integer, Float, …
Integer count = new Integer(0);
Provide utility functions: parseInt(), valueOf()…
Đại học Công nghệ - ĐHQG HN More on Java 4
Object references – controlling objects
str str:String
value = “Hello”
str = new String("Hello");
object reference count = 5
the object
There is actually no such thing as an object variable.
There‘re only object reference variables.
An object reference variable represents a way to
access an object, something like a pointer.
Think of an object reference
as a remote control
Đại học Công nghệ - ĐHQG HN More on Java 5
Object equality
"==" and "!=" compares references (not objects) to
see if they are refering to the same object.
Integer b = new Integer(10); a==b is true
Integer c = new Integer(10); b==c is false
Integer a = b;
Use the equals() method to see if two objects are
equal. Integer b = new Integer(10);
Integer c = new Integer(10);
if ([Link](c)) { // true };
Đại học Công nghệ - ĐHQG HN More on Java 6
Object equality
Method equals()
Pre-defined classes: Integer m1 = new Integer(10);
Integer m2 = new Integer(10);
Ready to use [Link]([Link](m2));
User-created classes:
equals() must be defined, otherwise, it always returns false
This is overriding class MyInteger {
(more on that later) private int value;
public boolean equals (MyInteger other) {
return (value == [Link]);
}
...
}
Đại học Công nghệ - ĐHQG HN More on Java 7
Object references
Dog myDog = new Dog();
Remember: References are not objects!
Đại học Công nghệ - ĐHQG HN More on Java 8
Object's life on the heap
Objects are created in the heap memory
a constructor is automatically called to initialize it
the set of parameters determine which constructor to
call and the initial value of the object
Book b = new Book();
Book c =
new Book(“Harry Potter”);
Đại học Công nghệ - ĐHQG HN More on Java 9
Object's life on the heap
when an object is no longer used,
i.e. there's no more reference
to it, it will be collected and
freed by Java garbage collector.
Book b = new Book();
Book c = new Book();
b = c;
There is no way to reach Book object 1.
It is ready to be collected.
Đại học Công nghệ - ĐHQG HN More on Java 10
Object's life on the heap
Book b = new Book();
Book c = new Book();
b = c;
c = null;
Book object 1 is waiting to be disallocated.
Book object 2 is safe as b is still referring to it.
Đại học Công nghệ - ĐHQG HN More on Java 11
Garbage collection
To reclaim the memory occupied by objects that are no longer in use
Programmers don’t have to disallocate objects
Java Virtual Machine (JVM) performs automatic garbage collection
Method finalize() is called by JVM, not programmers.
Guarantee no memory leaks
However, there’s no guarantee when/whether an object is freed
before the program terminates
Might not needed as memory is still available
Clean-up tasks must be done explicitly by other “clean-up”
methods rather than finalize()
Đại học Công nghệ - ĐHQG HN More on Java 12
12
Instance variables vs. local variables
Instance variables Local variables
belong to an object belong to a method
located inside the object in located inside the method's
the heap memory frame in the stack memory
has the same lifetime as the has the same lifetime as the
object method call.
public class DogTestDrive {
class Dog { public static void main(String []
int size; Dog dog = new Dog();
String breed; [Link] = "Bruno";
String name; [Link]();
... }
} }
Đại học Công nghệ - ĐHQG HN More on Java 13
Instance variables vs. local variables
Stack memory
Heap memory
object:Dog
name: “Bruno”
breed: null
size:
main’s stack frame
dog
public class DogTestDrive {
class Dog { public static void main(String []
int size; Dog dog = new Dog();
String breed; [Link] = "Bruno";
String name; [Link]();
... }
} }
Đại học Công nghệ - ĐHQG HN More on Java 14
Instance variables vs. local variables
Stack memory
Heap memory
object:Dog
name: “Bruno”
breed: null
size:
main’s stack frame
dog
Instance variables Local variables
belong to an object belong to a method
located inside the object in located inside the method's
the heap memory frame in the stack memory
has the same lifetime as the has the same lifetime as the
object method call.
Đại học Công nghệ - ĐHQG HN More on Java 15
Parameter passing & return value
Java allows only pass-by-value
That means pass-by-copy
Argument’s content is copied to the parameter
Dog d = new Dog();
[Link](3);
class Dog {
...
void bark(int numOfBarks) {
while (numOfBarks > 0) {
[Link]("ruff");
numOfBarks--; A method uses parameters.
} A caller passed arguments
}
Đại học Công nghệ - ĐHQG HN More on Java 16
Parameter passing & return value
A parameter is effectively a local variable that is
initialized with the value of the corresponding
argument.
Dog d = new Dog();
[Link](3);
class Dog {
something like
...
int numOfBarks = 3;
void bark(int numOfBarks) {
happens at this point
while (numOfBarks > 0) {
[Link]("ruff");
numOfBarks--;
}
}
Đại học Công nghệ - ĐHQG HN More on Java 17
Parameter passing & return value
The return value is copied to the stack, then to the
variable that get assigned (dogSize in this example)
int dogSize = [Link]();
these types must match
class Dog {
...
int getSize() {
return size;
}
Đại học Công nghệ - ĐHQG HN More on Java 18
Parameter passing & return value
Two kinds of parameters:
Primitive types
parameter’s value is copied
parameters can be constants, e.g. 10, “abc”…
Object references
the reference's value is copied, NOT the referred object.
m
n 50
Đại học Công nghệ - ĐHQG HN More on Java 19
Example
y, m, d are of primitive data type.
They’ll take the values of the
class Date { passed parameters.
int year, month, day;
public Date(int y, int m, int d) {
year = y; month = m; day = d;
}
public void copyTo(Date d) {
[Link] = year; d is a reference.
[Link] = month; d will take the values of the
passed parameter, which is
[Link] = day; an object location.
}
public Date copy() {
return new Date(day, month, year);
} return a reference to the newly
... created Date object.
} Again, it's a value, not the object
Đại học Công nghệ - ĐHQG HN More on Java 20
Example
...
int thisYear = 2010;
Date d1 = new Date(thisYear, 9, 26);
class Date {
int year, month, day; y = thisYear;
public Date(int y, int m, int d) { m = 9;
year = y; month = m; day = d; d = 26;
} year = y;
public void copyTo(Date d) { month = m;
[Link] = year; day = d;
[Link] = month;
[Link] = day;
}
public Date copy() {
return new Date(day, month, year);
}
...
}
Đại học Công nghệ - ĐHQG HN More on Java 21
Example
...
Date d1 = new Date(thisYear, 9, 26);
Date d2 = new Date(2000, 1, 1);
[Link](d2);
class Date {
int year, month, day;
public Date(int y, int m, int d) {
year = y; month = m; day = d; d = d2;
} [Link] = [Link];
public void copyTo(Date d) { [Link] = [Link];
[Link] = year; [Link] = [Link];
[Link] = month;
[Link] = day;
}
public Date copy() {
return new Date(day, month, year);
}
...
}
Đại học Công nghệ - ĐHQG HN More on Java 22
Example
...
Date d2 = new Date(2000, 1, 1);
Date d3 = [Link]();
class Date {
int year, month, day;
public Date(int y, int m, int d) {
year = y; month = m; day = d;
}
public void copyTo(Date d) {
[Link] = year; Date temp =
[Link] = month; new Date([Link], [Link], [Link]);
[Link] = day; d3 = temp;
}
public Date copy() {
return new Date(year, month, day);
}
...
}
Đại học Công nghệ - ĐHQG HN More on Java 23
Method overloading
Methods of the same class can have the same
name but different parameter lists.
class Dog { Dog d = new Dog();
...
void bark() { [Link]();
[Link]("Ruff! Ruff!");
} [Link](3);
void bark(int numOfBarks) {
while (numOfBarks > 0) {
[Link]("ruff");
numOfBarks--;
}
}
}
Đại học Công nghệ - ĐHQG HN More on Java 24
Do you still remember?
Instance variables/methods belong to an object.
Thus, when accessing them, you MUST specify
which object they belong to.
dot notation (.) public class DogTestDrive {
and public static void main(String [] args) {
the object Dog d = new Dog();
reference [Link] = "Bruno";
[Link](); access 'name' of the Dog
}
} call its bark() method
Đại học Công nghệ - ĐHQG HN More on Java 25
How about this case?
class Dog {
int size; Which object does the object that owns the
String breed; size belong to? current method –
String name; bark() or getBigger()
void bark() {
if (size > 14)
[Link](); //this dog's size get compared
[Link]("Ruff! Ruff!");
else
[Link](); //this dog's size get increased
[Link]("Yip! Yip!");
}
void getBigger() {
size += 5;
where is the object reference
}
and dot notation?
}
Đại học Công nghệ - ĐHQG HN More on Java 26
The this reference
class Dog {
int size; this reference
String breed; was omitted
String name;
void bark() {
if ([Link] > 14)
[Link](); //this dog's size get compared
[Link]("Ruff! Ruff!");
else
[Link](); //this dog's size get increased
[Link]("Yip! Yip!");
}
void getBigger() {
[Link] += 5;
}
}
Đại học Công nghệ - ĐHQG HN More on Java 27
The this reference
this : the object reference referring to the current
object – the owner of the current method
usage of this:
explicit reference to object’s attributes and
methods
often omitted
parameter passing and return value
calling constructor from inside constructor
Đại học Công nghệ - ĐHQG HN More on Java 28
The this reference
class MyInteger {
private int value;
public boolean greaterThan (MyInteger other) {
return ([Link] > [Link]);
}
public boolean lessThan (MyInteger other) {
return ([Link](this));
}
public MyInteger increment() {
value++;
return this;
}
}
MyInteger counter = new MyInteger();
[Link]().increment(); // increased by 2
Đại học Công nghệ - ĐHQG HN More on Java 29
Input / output
Details:
HFJ. Ch.14 / GT. Ch.12
In this slide:
standard input / output stream
simple input / output
simple text file input / output
Đại học Công nghệ - ĐHQG HN More on Java 30
Standard I/O
Three stream objects automatically created when a Java
program begins executing:
[Link] : standard output stream object
enables a program to output data to the console
[Link] : standard error stream object
enables a program to output error messages to the console
[Link] : standard input stream object
enables a program to input bytes from the keyboard
Redirect at command line (input and output stream only):
C:\> type [Link] | java AJavaProgram > [Link]
Đại học Công nghệ - ĐHQG HN More on Java 31
Standard output and error streams
[Link] and [Link] can be used directly
[Link]("Hello, world!");
[Link]("Invalid day of month!");
Note: if you mix up these two streams in your
programs, the output might not end up being
displayed in the same order as the output
instructions.
Đại học Công nghệ - ĐHQG HN More on Java 32
Standard input
[Link]
An InputStream object
must be wrapped before use
Scanner: wrapper that supports input of primitive types and
character strings
next(): get the next word separated by white spaces
nextInt(), nextDouble(),…: get the next data item
hasNext(), hasNextInt(), hasNextDouble(),…: check if there
are data left to be read
Đại học Công nghệ - ĐHQG HN More on Java 33
Standard input. Example
// import the wrapper class
import [Link];
...
// create Scanner to get input from keyboard
Scanner input = new Scanner( [Link] );
// read a word
String s = [Link]());
// read an integer
int i = [Link]();
// read a series of big intergers
while ([Link]()) {
long aLong = [Link]();
}
Đại học Công nghệ - ĐHQG HN More on Java 34
Import required
classes
Input from a text file. Example
import [Link];
import [Link]; To deal with errors such
import [Link]; as file-not-found
...
public static void main(String args[]) {
try {
// create Scanner to get input from a file stream
Scanner sc = new Scanner(new FileInputStream("[Link]"));
String s = [Link]()); // read a word
int i = [Link](); // read an integer
while ([Link]()) { // read a series of big intergers
long aLong = [Link]();
}
Open and close
the text file
[Link]();
} catch(IOException e) {
[Link]();
}
}
...
Đại học Công nghệ - ĐHQG HN More on Java 35
Write to a text file. Example
import [Link];
import [Link];
import [Link];
...
public static void main(String args[]) {
int i = 1; long l = 10;
try {
// create a printwriter to write output to a file stream
PrintWriter out = new PrintWriter(new FileWriter("[Link]"));
// write to file
[Link]("Hello " + i + " " + l);
[Link]();
} catch(IOException e) {
[Link]();
}
}
...
Đại học Công nghệ - ĐHQG HN More on Java 36
Command-line parameters
//[Link]: read all command-line parameters
public class CmdLineParas {
public static void main(String[] args)
{
//display the parameter list
for (int i=0; i<[Link]; i++)
[Link](args[i]);
}
}
}
C:\>java CmdLineParas hello world
hello
world
Đại học Công nghệ - ĐHQG HN More on Java 37