[go: up one dir, main page]

0% found this document useful (0 votes)
6 views22 pages

LEC 07 Annotated

The document discusses key concepts in Object Oriented Programming, specifically focusing on Pass by Value vs Pass by Reference and Mutable vs Immutable Objects. It explains the differences between how primitive data types and object references are handled in Java, including memory allocation on the stack and heap. Additionally, it highlights the implications of aliasing and garbage collection in Java programming.

Uploaded by

f20220329
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)
6 views22 pages

LEC 07 Annotated

The document discusses key concepts in Object Oriented Programming, specifically focusing on Pass by Value vs Pass by Reference and Mutable vs Immutable Objects. It explains the differences between how primitive data types and object references are handled in Java, including memory allocation on the stack and heap. Additionally, it highlights the implications of aliasing and garbage collection in Java programming.

Uploaded by

f20220329
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/ 22

BITS Pilani

Pilani Campus

Object Oriented Programming


Pass by value vs Pass by Reference, Mutable vs
Immutable Objects
Last Class

• Method Overloading >


- multipla methods name
the same
– Constructor Overloading -having different
but
• static keyword arguments
•-Stack and Heap
-

BITS Pilani, Pilani Campus


Pass by Value and Pass by Reference
-

• C vs Java
• Let us go through a concrete example

BITS Pilani, Pilani Campus


natu
L
gramming O

;
20
Inf a=
=
-

Put *

& [10 ,
15 , 9 , 3
10
(b) => 3000
print
b
;
*c =
out
2096
c(0) = = b[0] =

int **
17
=
xb
intd =
;
DID
memory
Java Symbol
-

-
table

;
20
int & = 5

(30 50)!
But b-2;
new
Point ,
40
,

Point PE

Point a ; ↑
q.
-
-

pLEp ;
Point Point (30 ,
40 50) ;
new ,
-

Point P3 =

&
true
p
-
==
p2
p3 =
creating

PJeCalso
object
p3
= = a new

= p x o

p3 y =
.
=
= =
p
P
.

n]
Y
-
true

P3 . 2 = = Prz

mylische
Love

ciscler I wo
Stack and Heap

• When your program is running, some memory is


used to store local variables. This memory is known
as the stack.
• We can use a table to represent variables stored on
the stack
Var Value
x 42
y 3.7
• The rest of memory is known as the heap and is used
for dynamically allocated “stuff” (recall using malloc()
in C)

BITS Pilani, Pilani Campus


Main Memory

The stack grows and shrinks as needed (why?)


The used part of the heap (“allocated”) also grows and shrinks.
Some of the heap is unused (“free”)

Stack Free Heap Used Heap

BITS Pilani, Pilani Campus


Object Creation

Consider this code that creates two strings


S1 == S2-false
String s1, s2;
O
s1 = new String( “abc” );
de

-T
s2 = “abc” ;
weap
stack
stack

Note: Because Strings are very common, using new when creating String objects is optional.

Where are these variables and object located in -


-

memory?
Why do we care?

BITS Pilani, Pilani Campus


Objects in Memory

The statement String s1, s2; creates two local variables on the stack.
The statements
s1 = new String( “abc” );
s2 = “abc”;

create objects on the heap. s1 and s2 contain the memory addresses of


these objects giving us the picture of memory shown below.
s1 and s2 are called reference variables. Reference variables which do not
contain the memory address of any object contain the special value null

Stack Heap

s1
s2 abc abc

BITS Pilani, Pilani Campus


Why We Care (1 of 4)

Given the previous code Stack Heap


String s1, s2;
s1 = new String( “abc” );
s2 = “abc”;
s1
and corresponding picture of memory s2 abc abc
consider the expression s1 == s2

Recall that s1 and s2 contain the addresses of their respective String objects.
Since the String objects have different addresses on the heap, s1 == s2 is
false. The == operator determines if two reference variables refer to the same
Object. Sl = = S2

So how do we compare Strings for equality?


Strings (and other objects) implement a method named equals.
To check if two Strings are the same, use the expression
s1.equals( s2 );
-
-
-

BITS Pilani, Pilani Campus


Why We Care (2 of 4)

Stack Heap
On the other hand, consider this code
and corresponding picture of
memory s1
String s1 = “abc”;
String s2 = s1;
-
s2
②abc
s1 and s2 are ALIASed
-

Now s1 and s2 refer to the same String object. This is known as ALIASING, is often
unintentional, and can be dangerous.

If your intent is for s2 to be a copy of s1, then the correct code is


String s2 = new String( s1 );
--

to object
,
S2 is
referring
a new

separate Brom
SI's obich
.

BITS Pilani, Pilani Campus


Why We Care (3 of 4)

Consider this code and the changing picture of memory

String s1 = “abc”; // line 1


s1 = “xyz”; // line 2

E
S1 = “Hello”; // line 3

Stack Heap Stack Heap Stack Heap


Hello

s1 abc s1 abc xyz s1 Ou


abc xyz
After line 1 After line 2 After line 3

BITS Pilani, Pilani Campus


Why We Care (4 of 4)

• Garbage collection
-
Stack Heap

As the diagram shows, after line 3 is Hello


executed no variable refers to the
s1 abc xyz
String objects which contain “abc”
or “xyz”. After line 3

In C/C++, we’d consider this a “memory leak”. In C/C++ it’s the


programmer’s responsibility to return dynamically allocated memory
back to the free heap. (recall using malloc and free in C?)
Not so in Java!

Java has a built-in “garbage collector”. From time to time Java detects
objects has been “orphaned” because no reference variable refers to
them. The garbage collector automatically returns the memory for
those objects to the free heap.

BITS Pilani, Pilani Campus


Passing Information to a Method or a Constructor

-
L
public double computePayment(double loanAmt, double rate,
3
double futureValue, int numPeriods){

//your code goes here


}

Parameters refers to the list of variables in a method declaration.


Arguments are the actual values that are passed in when the
method is invoked. When you invoke a method, the arguments used
must match the declaration's parameters in type and order.

BITS Pilani, Pilani Campus


Pass by Value
1. Most methods are passed arguments when they are called. An
argument may be a constant or a variable.
➢ For example, in the expression
-
Math.sqrt(33), the constant 33 is passed to the sqrt()
method of the Math class. In the expression
-Math.sqrt(x), the variable x is passed.
Ent 50;
4 I =

I
-
2. This is simple enough, however there is an important but
simple principle at work here. If a variable is passed, the
- -

method receives a copy of the variable's value. The value of


-

-
the original variable cannot be changed within the method.
-

This seems reasonable because the method only has a copy of


the value; it does not have access to the original variable.
- -

This process is called pass by value.


-

Math .

Syst (50) ;

BITS Pilani, Pilani Campus


Pass by Value - Example
public class DemoPassByValue {
public static void main(String[] args) {
int=i = 25;
-
&
System.out.println(i); 25

# iMethod(i);
??
why
=
System.out.println(i); > ?? 25
-
not
}
-
E -

i Test = 1 25

#0
=

-
-

iTest = 9; // change it
&
public static void iMethod(int iTest) {
-
=>

=>

System.out.println(iTest); -
} memory Ex =
9

#
}

BITS Pilani, Pilani Campus


Pass by Reference
1. If the variable passed as an object, then the effect is
different.
2. We often say things like,
➢ This method returns an object
➢ This method is passed an object as an argument
3. This not quite true, more precisely, we should say,
➢ This method returns a reference to an object
➢ This method is passed a reference to an object as an
argument
4. In fact, objects, per se, are never passed to methods or returned
by methods. It is always "a reference to an object" that is
passed or returned.
5. The term "variable" also deserves clarification. There are two
types of variables in Java:
➢ Those that hold the value of a primitive data type and those
that hold a reference to an object.
➢ A variable that holds a reference to an object is an "object
variable" — the prefix "object" is often dropped for brevity.

BITS Pilani, Pilani Campus


Pass by Reference vs Pass by Value
1. Pass by value refers to passing a constant or a variable
holding a primitive data type to a method, and pass by
reference refers to passing an object variable to a method.
2. In both cases a copy of the variable is passed to the
method. It is a copy of the "value" for a primitive data
type variable; it is a copy of the "reference" for an object
variable. So, a method receiving an object variable as an
argument receives a copy of the reference to the original
object.
3. Here's the catch: If the method uses that reference to make
changes to the object, then the original object is changed.
This is reasonable because both the original reference and
the copy of the reference "refer to" to same thing — the
original object.
4. There is one exception: Strings. Since String objects are
immutable in Java, a method that is passed a reference to a
String object cannot change the original object.

BITS Pilani, Pilani Campus


Cela cirla
;
Passing Reference Data Type Arguments
① circle ② int int

·
public void moveCircle(Circle circle, int deltaX, int deltaY) {

not s
// code to move origin of circle to x+deltaX, y+deltaY
circle.setX(circle.getX() + deltaX);
-

circle.setY(circle.getY() + deltaY);
-

10 + 23 =
3
//code to assign a new reference to circle
-

&
circle = new Circle(0, 0);

=cla
} main()
(10 20) Y


Lisele -
=

Color now ,
=
my - - -

Fische ele⑫ ;
-

move ,

C INVOKE: moveCircle(myCircle, 23, 56) ;


X BITS Pilani, Pilani Campus
cirle
public
Gala move Circle (circle ,
int dellax
,

=
int delta4)
E
-
-

Circle (0 , 0),

li
new

3
?
main new Lisela (10 , 20)
licle =

E

my
Cel
(
=

cree-movelis)
-

)my Grele)
-

L
S 4 ⑧O
I
-
-
lost
Passing Reference Data Type Arguments

• Inside the method, circle initially refers to myCircle. The method


changes the x and y coordinates of the object that circle references
(i.e., myCircle) by 23 and 56, respectively. These changes will
persist when the method returns. Then circle is assigned a reference
to a new Circle object with x = y = 0. This reassignment has no
permanence, however, because the reference was passed in by
value and cannot change. Within the method, the object pointed to
by circle has changed, but, when the method returns, myCircle still
references the same Circle object as before the method was called.

BITS Pilani, Pilani Campus


THANK YOU

BITS Pilani, Pilani Campus

You might also like