Why?
A Simple Number
Class
class Number {
public int value;
Number (int val) {
value = val;
}
}
What does the following code do?
Number aNum = new Number(10);
Number bNum = new Number(5);
bNum = aNum;
aNum.value = 20;
What are aNum.value
and bNum.value
at the end of the execution?
Consider the method
void setNumberValue (Number a, int value) {
a.value = value;
}
What is the result of
setNumberValue(aNum, 0);
What is the value of aNum.value
at the end of the execution?
Java has 8 primitive datatypes:
byte
, short
, int
, long
float
, double
boolean
char
All other datatypes are objects (class
es)
new
int a = 10; // assign value of 10 to a
int b = 5; // assign value of 5 to b
b = a; // copy value of a (10), assign to b
a = 20; // assign value of 20
Method calls take copies of datatype values passed as arguments
a
passed to setValue(a, 0)
setValue(a, 0);
a
in method is a local copy; only local copy’s value is changed void setValue (int a, int value) {
a = value;
}
a
in main
is unchanged!new Number(...)
creates a new instance of the Number
class
aNum
stores a reference to the Number
Number aNum = new Number(10);
Number bNum = new Number(5);
aNum
stores the reference, not the Number
itself!
In this statement
Number aNum = new Number(10);
Number bNum = new Number(5);
bNum = aNum;
the reference stored in aNum
is copied and stored in bNum
aNum
and bNum
now refer to the same Number
instanceIn this statement
setNumberValue(aNum, 0);
the reference stored in variable aNum
is passed to setNumberValue
void setNumberValue (Number a, int value) {
a.value = value;
}
The statement a.value = value
sets the value
void setNumberValue (Number a, int value) {
a.value = value;
}
public static void main (String[] args) {
Number aNum = new Number(10);
setNumberValue(aNum, 0);
}
What happens?
int a = 10;
int b = 10;
if (a == b) {
System.out.println("equal");
} else {
System.out.println("not equal");
}
What happens?
Number aNum = new Number(10);
Number bNum = new Number(10);
if (aNum == bNum) {
System.out.println("equal");
} else {
System.out.println("not equal");
}
aNum
and bNum
not Equal?Number
s?public class Number {
public int value;
public Number (int aValue) {
value = aValue;
}
public boolean equals (Number a) {
return (value == a.value);
}
}
Number aNum = new Number(10);
Number bNum = new Number(10);
boolean areEqual = aNum.equals(bNum);
Drawbacks?