0% found this document useful (0 votes)
11 views

04 More On Java

This document discusses object-oriented programming concepts in Java, including: - Primitive variables hold fundamental data types like int and boolean, while reference variables hold references to objects. - Objects are created in heap memory and accessed via object references, not the objects themselves. Garbage collection reclaims unused memory. - Instance variables belong to objects and exist in heap memory, while local variables exist on the stack during method calls. - Parameters are passed by value, meaning the argument's value is copied to the parameter. Return values are also copied back from methods.

Uploaded by

hanguyenb1a4
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)
11 views

04 More On Java

This document discusses object-oriented programming concepts in Java, including: - Primitive variables hold fundamental data types like int and boolean, while reference variables hold references to objects. - Objects are created in heap memory and accessed via object references, not the objects themselves. Garbage collection reclaims unused memory. - Instance variables belong to objects and exist in heap memory, while local variables exist on the stack during method calls. - Parameters are passed by value, meaning the argument's value is copied to the parameter. Return values are also copied back from methods.

Uploaded by

hanguyenb1a4
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/ 37

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();
d.name = "Bruno";
d.bark();

Đạ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 (b.equals(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 System.out.print(m1.equals(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 == other.value);
}
...
}

Đạ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; dog.name = "Bruno";
String name; dog.bark();
... }
} }

Đạ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; dog.name = "Bruno";
String name; dog.bark();
... }
} }

Đạ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();


d.bark(3);

class Dog {
...
void bark(int numOfBarks) {
while (numOfBarks > 0) {
System.out.println("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();
d.bark(3);

class Dog {
something like
...
int numOfBarks = 3;
void bark(int numOfBarks) {
happens at this point
while (numOfBarks > 0) {
System.out.println("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 = dog.getsize();


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) {
d.year = year; d is a reference.
d.month = month; d will take the values of the
passed parameter, which is
d.day = 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;
d.year = year; day = d;
d.month = month;
d.day = 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);
d1.copyTo(d2);
class Date {
int year, month, day;
public Date(int y, int m, int d) {
year = y; month = m; day = d; d = d2;
} d.year = d1.year;
public void copyTo(Date d) { d.month = d1.month;
d.year = year; d.day = d1.day;
d.month = month;
d.day = 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 = d2.copy();

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) {
d.year = year; Date temp =
d.month = month; new Date(d2.year, d2.month, d2.day);
d.day = 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() { d.bark();
System.out.println("Ruff! Ruff!");
} d.bark(3);
void bark(int numOfBarks) {
while (numOfBarks > 0) {
System.out.println("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 d.name = "Bruno";
d.bark(); 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)
dog1.bark(); //this dog's size get compared
System.out.println("Ruff! Ruff!");
else
dog2.getBigger(); //this dog's size get increased
System.out.println("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 (this.size > 14)
dog1.bark(); //this dog's size get compared
System.out.println("Ruff! Ruff!");
else
dog2.getBigger(); //this dog's size get increased
System.out.println("Yip! Yip!");
}
void getBigger() {
this.size += 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 (this.value > other.value);
}
public boolean lessThan (MyInteger other) {
return (other.greaterThan(this));
}
public MyInteger increment() {
value++;
return this;
}
}

MyInteger counter = new MyInteger();


counter.increment().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:
 System.out : standard output stream object

 enables a program to output data to the console


 System.err : standard error stream object
 enables a program to output error messages to the console
 System.in : standard input stream object
 enables a program to input bytes from the keyboard

 Redirect at command line (input and output stream only):


C:\> type input.dat | java AJavaProgram > output.dat

Đại học Công nghệ - ĐHQG HN More on Java 31


Standard output and error streams

 System.out and System.err can be used directly


 System.out.println("Hello, world!");
 System.err.println("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

 System.in
 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 java.util.Scanner;
...
// create Scanner to get input from keyboard
Scanner input = new Scanner( System.in );

// read a word
String s = sc.next());

// read an integer
int i = sc.nextInt();

// read a series of big intergers


while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}

Đại học Công nghệ - ĐHQG HN More on Java 34


Import required
classes
Input from a text file. Example
import java.util.Scanner;
import java.io.FileInputStream; To deal with errors such
import java.io.IOException; 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("test.dat"));

String s = sc.next()); // read a word


int i = sc.nextInt(); // read an integer
while (sc.hasNextLong()) { // read a series of big intergers
long aLong = sc.nextLong();
}
Open and close
the text file
sc.close();

} catch(IOException e) {
e.printStackTrace();
}
}
...
Đại học Công nghệ - ĐHQG HN More on Java 35
Write to a text file. Example
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.IOException;
...
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("test.data"));

// write to file
out.println("Hello " + i + " " + l);

out.close();
} catch(IOException e) {
e.printStackTrace();
}
}
...

Đại học Công nghệ - ĐHQG HN More on Java 36


Command-line parameters

//CmdLineParas.java: read all command-line parameters


public class CmdLineParas {
public static void main(String[] args)
{
//display the parameter list
for (int i=0; i<args.length; i++)
System.out.println(args[i]);
}
}
}
C:\>java CmdLineParas hello world
hello
world

Đại học Công nghệ - ĐHQG HN More on Java 37

You might also like