BITS Pilani
Pilani Campus
Object Oriented Programming
Mutable vs Immutable Objects, Arrays
Last Class
WhatsApp-7742710554
-
• Primitive data types (int, double, float etc.)
• Non-primitive or object data types (object
variables)
• Passing arguments to methods
– Pass by Value (refers to passing primitive data types)
– Pass by Reference (refers to passing object variables)
-
• This is also “pass by value” only. But it is called as “pass by
reference” as we are passing the object variable which
stores the reference to the actual object (stored on the
heap).
BITS Pilani, Pilani Campus
Mutable Objects
• A mutable object is one whose internal state (i.e.,
-
its fields) can be changed after it is created.
-
• Example: Most objects in Java, such as instances
of ArrayList, StringBuffer, and custom objects
-
where fields are modifiable, are mutable.
• Methods: Typically, mutable objects provide
setter methods or methods that modify the
-
internal state (e.g., ArrayList.add(),
StringBuffer.append()).
BITS C342, Object Oriented Programming
BITS Pilani, Pilani Campus
Immutable Objects
• An immutable object is one whose internal state -
cannot be changed after it is created. Once the
-
object is initialized, it cannot be modified.
• Example: Instances of String, Integer, and custom
- -
objects designed to be immutable are immutable.
• Methods: Immutable objects do not provide
-
setters or methods that modify the state. Instead,
-
-
any method that would change the state returns
a new object (e.g., String.concat()).
BITS C342, Object Oriented Programming
BITS Pilani, Pilani Campus
1
5 Java
String
=
SI
Sting S
=
Immutable Object – Example (String)
public class DemoPassByReference2 {
ch
100
·
!
public static void main(String[] args) {
S
- String s = - "Java is fun!";
Java Bun System.out.println(s);
-
es -
=
smethod (1000)
- sMethod(s); !
7
=>=>
3
System.out.println(s);
} Is Bur
Jura
[
public static void sMethod(String -
sTest){
-
- -
*
sTest = sTest.substring(8, 11);
&
-
-
System.out.println(sTest);
} Bun
Heap
}
D create C 12
Bus's
rbiech with
string
a
new
① returns this new object
BITS Pilani, Pilani Campus
Immutable Object – Example (String)
BITS Pilani, Pilani Campus
Mutable Object – Example (StringBuffer)
public class DemoPassByReference1 {
stack public static void main(String[] args) {
#Hello
StringBuffer sb = new StringBuffer("Hello, world");
-
System.out.println(sb); Hello world -
-
- =
0123456
=
sbMethod(sb);
-
System.out.println(sb);
}
O
public static void sbMethod(StringBuffer sbTest) {
sbTest = sbTest.insert(7, "Java ");
}
System.out.println(sbTest);
,a
}
BITS Pilani, Pilani Campus
Mutable Object – Example (StringBuffer)
- -
-
-
BITS Pilani, Pilani Campus
Parameter Names
• When you declare a parameter to a method or a constructor, you
provide a name for that parameter. This name is used within the
-
method body to refer to the passed-in argument.
[
• The name of a parameter must be unique in its scope. It cannot be
the same as the name of another parameter for the same method
or constructor, and it cannot be the name of a local variable within
the method or constructor.
• A parameter can have the same name as one of the class's fields. If
this is the case, the parameter is said to shadow the field.
=
Shadowing fields can make your code difficult to read and is
conventionally used only within constructors and methods that set a
particular field.
BITS Pilani, Pilani Campus
Parameter Names
no relationship
-T
public class Circle {
private int 00
x, y, radius;
=
>
-
public void setOrigin(int x, int O
y) {
...
}
}
• The Circle class has three fields: x, y, and radius. The setOrigin
method has two parameters, each of which has the same name as
one of the fields. Each method parameter shadows the field that
shares its name. So using the simple names x or y within the body
of the method refers to the parameter, not to the field. To access
the field, you must use a qualified name.
BITS Pilani, Pilani Campus
Introduction to Arrays
• An array is a data structure used to process a
collection of data that is all of the same type
– An array behaves like a numbered list of variables
with a uniform naming mechanism
– It has a part that does not change:
• the name of the array
– It has a part that can change:
• an integer in square brackets
– For example, given five scores:
score[0],score[1],score[2],score[3],score[4]
array of rise
5
BITS Pilani, Pilani Campus
Creating and Accessing Arrays
• An array that behaves like a collection of variables, all
of type double, can be created using one statement
0 double[] score = new double[5];
• Or using two statements:
(double[] score;
score = new double[5];
– The first statement declares the variable score to be of
the array type double[] (an array of doubles)
– The second statement creates an array with five numbered
variables of type double and makes the variable score
a name for the array
BITS Pilani, Pilani Campus
Creating and Accessing Arrays
• The individual variables that together make up the
array are called indexed variables
– They can also be called subscripted variables or elements of
the array
– The number in square brackets is called an index or subscript
– The number of indexed variables in an array is called the
length or size of the array
– In Java indices must be numbered starting =
with 0, and
nothing else
O
score[0], score[1], score[2], score[3], score[4]
P
BITS Pilani, Pilani Campus
Creating and Accessing Arrays
• When an array is created, the length of the array is
given in square brackets after the array type
• The indexed variables are then numbered starting
with 0, and ending with the integer that is one less
than the length of the array
• The declaration length
double[] score = new double[5];
results in the 5 elements
score[0], score[1], score[2], score[3], score[4]
BITS Pilani, Pilani Campus
Creating and Accessing Arrays
double[] score = new double[5];
reference variable
• A variable may be used in place of the integer (i.e., in
place of the integer 5 above)
– The value of this variable can then be read from the
keyboard
– This enables the size of the array to be determined
when the program is run langen
double[] score = new double[count]; can&
• An array can have indexed variables of any type, also
be
Variable
including any class type
• All of the indexed variables in a single array must be of
the same type, called the base type of the array
BITS Pilani, Pilani Campus
Declaring and Creating an Array
• An array is declared and created in almost the same way that
objects are declared and created:
1 BaseType[] ArrayName = new BaseType[size];
-
- -
- -
– The size may be given as an expression that evaluates
to a nonnegative integer, for example, an int variable
rPre
ay(
char[] line = new char[80];
double[] reading = new double[count];
w Person[] specimen = new Person[100];
↑
datatype
array # objects
BITS Pilani, Pilani Campus
Referring to Arrays and Array Elements
• Each array element can be used just like any other single
variable by referring to it using an indexed expression:
score[0]
• The array itself (i.e., the entire collection of indexed
variables) can be referred to using the array name
(without any square brackets): score
• An array index can be computed when a program is run
– It may be represented by a variable:
6
score[index]
– It may be represented by an expression that evaluates
to a suitable integer: score[next + 1]
-
BITS Pilani, Pilani Campus
Using the score Array in a Program
• The for loop is ideally suited for performing array
manipulations: eize of the array
-
I
for (int index = 0; index < 5; index++)
System.out.println(score[index]
+ " differs from max by "
+ (max - score[index]) );
me
Trelared
BITS Pilani, Pilani Campus
Three Ways to Use Square Brackets []
with an Array Name
• Square brackets can be used to create a type name:
① score;
double[]
• Square brackets can be used with an integer value as
part of the special syntax Java uses to create a new
array:
O
score = new double[5];
• Square brackets can be used to name an indexed
variable of an array:
O
max = score[0];
BITS Pilani, Pilani Campus
The length Instance Variable
- Car a (10] ;
• An array is considered to be an object
-
• Since other objects can have instance variables, so can a
-
arrays
• Every array has exactly one instance variable named
#length
-
– When an array is created, the instance variable
length is automatically set equal to its size
– The value of length cannot be changed (other than
by creating an entirely new array using new)
double[] score = new double[5];
– Given score above, score.length has a value of 5
-
BITS Pilani, Pilani Campus
Pitfall: Array Index Out of Bounds size = 10
Index = 10
• Array indices always start with 0, and always end
with the integer that is one less than the size of the ↑
array
O to 9
– The most common programming error made
when using arrays is attempting to use a valued ↓
index
nonexistent array index
• When an index expression evaluates to some value 39
other than those allowed by the array declaration, ↑
the index is said to be out of bounds invalid
– An out of bounds index will cause a program to 40
terminate with a run-time error message Invalid
– Array indices get out of bounds most commonly =
at the first or last iteration of a loop that
processes the array: Be sure to test for this!
BITS Pilani, Pilani Campus
Initializing Arrays
• An array can be initialized when it is declared
– Values for the indexed variables are enclosed in braces,
and separated by commas
– The array size is automatically set to the number of values
in the braces
int[] age = {2, 12, 1};
-
– Given age above, age.length has a value of 3
BITS Pilani, Pilani Campus
Initializing Arrays
• Another way of initializing an array is by using a for loop
inta; >
-
P
-
double[] reading = new double[100]; 0
-
for (int index = 0; index < reading.length; index++){
reading[index] = 42.0;
}
• If the elements of an array are not initialized explicitly, they will
-
-
automatically be initialized to the default value for their base type
- -
BITS Pilani, Pilani Campus
An Array of Characters Is Not a String
• An array of characters is conceptually a list of
characters, and so is conceptually like a string
• However, an array of characters is not an object of the
class String
char[] a = {'A', 'B', 'C'};
#E String s = a; //Illegal!
• An array of characters can be converted to an object of
type String, however
new String (a) ;
-
String
=
(continued)
BITS Pilani, Pilani Campus
An Array of Characters Is Not a String
• The class String has a constructor that has a single
parameter of type char[]
String s = new String(a); ~
– The object s will have the same sequence of characters as
the entire array a ("ABC"), but is an independent copy
• Another String constructor uses a subrange of a
=
character array instead
-
String s2 = new String(a,0,2);
=
– Given a as before, the new string object is "AB"
(continued)
BITS Pilani, Pilani Campus
An Array of Characters Is Not a String
-
• An array of characters does have some things in
common with String objects
– For example, an array of characters can be output
using println
System.out.println(a);
– Given a as before, this would produce the output
ABC
BITS Pilani, Pilani Campus
Arrays and References
• Like class types, a variable of an array type
-
holds a reference
=
– Arrays are objects
– A variable of an array type holds the address of
-tap
-
where the array object is stored in memory
– Array types are (usually) considered to be class
types
do
double [] a =
BITS Pilani, Pilani Campus
Arrays are Objects
• An array can be viewed as a collection of indexed variables
• An array can also be viewed as a single item whose value is a
collection of values of a base type
– An array variable names the array as a single item
6
double[] a;
– A new expression creates an array object and stores the
object in memory
new double[10]
– An assignment statement places a reference to the
memory address of an array object in the array variable
a = new double[10];
0-
-
– The previous steps can be combined into one statement
double[] a = new double[10];
(continued)
BITS Pilani, Pilani Campus
Arrays with a Class Base Type
mopare
• The base type of an array can be a class type
·
- Date[] holidayList = new Date[20];
.
- -
double 2) abc new double []
;
=
D
-
• The above example creates 20 indexed reference
-
variables of type Date. It does not create 20
objects of the class Date
– Each of these indexed variables are automatically
initialized to null
I
– Any attempt to reference any them at this point would
result in a "null pointer exception" error message
nepwerday (continued)
BITS Pilani, Pilani Campus
Arrays with a Class Base Type
• Like any other object, each of the indexed variables requires a
separate invocation of a constructor using new (singly, or
perhaps using a for loop) to create an object to reference
holidayList[0] = new Date();
. . .
holidayList[19] = new Date();
OR
⑫
for (int i = 0; i < holidayList.length; i++)
holidayList[i] = new Date();
-
• Each of the indexed variables can now be referenced since
each holds the memory address of a Date object
BITS Pilani, Pilani Campus
THANK YOU
BITS Pilani, Pilani Campus