QUALITY. PRODUCTIVITY. INNOVATION.
Basic Programming
Session 4
endava.com
Basic Programming
Garbage collection
String & StringBuilder
toString
Collections
ArrayList
HashSet
HashMap
Q&A
QUALITY. PRODUCTIVITY. INNOVATION.
Memory management and Garbage Collection
Memory management
Garbage collection is a way in which Java recollects the space occupied
by loitering objects.
In general, a garbage collector is responsible with three tasks:
Allocating memory for new objects
Ensuring that any reference objects (live objects) remain in
memory
Recovering memory used by objects
that are no longer reachable
3
(dead objects)
When Does the Garbage Collector Run?
How Does the Garbage Collector Work?
QUALITY. PRODUCTIVITY. INNOVATION.
Writing Code That Explicitly Makes
Objects Eligible for Collection
Nulling a Reference - set the reference variable
that refers to the object to null.
public class GarbageTruck {
public static void main(String [] args) {
StringBuffer sb = new
StringBuffer("hello");
System.out.println(sb);
// The StringBuffer object is not eligible
for collection
sb = null;
// Now the StringBuffer object is eligible
for collection
}
Reassigning a Reference Variable set the reference
variable to refer to another object.
class GarbageTruck {
public static void main(String [] args) {
StringBuffer s1 = new StringBuffer("hello");
StringBuffer s2 = new StringBuffer("goodbye");
System.out.println(s1);
// At this point the StringBuffer "hello" is
not eligible
s1 = s2; // Redirects s1 to refer to the
"goodbye" object
// Now the StringBuffer "hello" is eligible for
collection
}
QUALITY. PRODUCTIVITY. INNOVATION.
String
The String Class
KEY concept: once a String object is created, it can never
be changed !
Immutable Objects
Step 1
String myString = Hello;
The heap
Hello
myString
(reference
variable)
Step 2
String secondString =
myString;
myString
(reference variable)
The heap
Hello
secondString
(reference variable)
Step 3
myString =
myString.concat( World)
myString
The heap
(reference variable)
secondString
Hello World
Hello
(reference variable)
QUALITY. PRODUCTIVITY. INNOVATION.
Important Methods in the String class
QUALITY. PRODUCTIVITY. INNOVATION.
toString()
Implementing toString method in java is done by overriding the Objects toString method.
The java toString() method is used when we need a string representation of an object. It is defined in
Object class. This method can be overridden to customize the String representation of the Object.
Demo
7
Conclusion
Since our example has no toString method, the default one in Object is used. The format of the default
toString method of the Object is as shown below.
Class Name, @, and the hex version of the objects hashcode concatenated into a string.
The default hashCode method in Object is typically implemented by converting the memory address of the
object into an integer.
QUALITY. PRODUCTIVITY. INNOVATION.
The StringBuffer and StringBuilder
Classes
The java.lang.StringBuffer and java.lang.StringBuilder classes should be used
when you have to make a lot of modifications to strings of characters.
The StringBuilder class was added in Java 5. It has exactly the same API as the
StringBuffer class, except StringBuilder is not thread safe.
8
Sun recommends that you use StringBuilder instead of StringBuffer whenever
possible because StringBuilder will run faster.
QUALITY. PRODUCTIVITY. INNOVATION.
Important Methods in the StringBuffer
and StringBuilder Classes
public synchronized
StringBuffer
reverse()
public String
toString()
This method returns a StringBuffer object and updates the value of the StringBuffer
object that invoked the method call. In both cases, the characters in the StringBuffer
are reversed, the first character becoming the last, the second becoming the second
to the last, and so on:
This method returns the value of the StringBuffer object that invoked the method call
as a String
9
public synchronized
StringBuffer
append(String s)
update the value of the object that invoked the method, whether or not the return is
assigned to a variable. This method will take many different arguments, including
boolean, char, double, float, int, long, and others
public StringBuilder
delete(int start, int
end)
This method returns a StringBuilder object and updates the value of the StringBuilder
object that invoke the method call. In both cases, a substring is removed from the
original object.
public StringBuilder
insert(int offset,
String s)
This method returns a StringBuilder object and updates the value of the StringBuilder
object that invoked the method call. In both cases, the String passed in to the second
argument is inserted into the original StringBuilder starting at the offset location
represented by the first argument (the offset is zero-based).
QUALITY. PRODUCTIVITY. INNOVATION.
Java Collections
A collection represents a group of objects
java.util package.
They are basically used to group multiple elements into a single unit. Some collections
allow duplicate elements while others do not. Some collections are ordered and others are
not.
What can we do with a Collection?
10
1.
2.
3.
4.
5.
Add objects to the collection.
Remove objects from the collection.
Find out if an object (or group of objects) is in the collection
Retrieve an object from the collection (without removing it).
Iterate through the collection, looking at each element (object) one after another.
10
QUALITY. PRODUCTIVITY. INNOVATION.
11
11
QUALITY. PRODUCTIVITY. INNOVATION.
Classification
Lists - Lists of things (classes that implement List)
Sets - Unique things (classes that implement Set)
12
Maps - Things with an unique ID (classes that implement Map)
12
QUALITY. PRODUCTIVITY.
INNOVATION.
Collection Interface concrete implementation
classes
Class
Map
HashMap
Set
List
Ordered
Sorted
No
No
Hashtable
No
No
TreeMap
Sorted
By natural order or
custom comparison rules
LinkedHashMap
By insertion order
or last
13 access order
No
HashSet
No
No
TreeSet
Sorted
By natural order or
custom comparison rules
LinkedHashSet
By insertion order
No
ArrayList
By index
No
Vector
By index
No
LinkedList
By index
No
13
QUALITY. PRODUCTIVITY. INNOVATION.
ArrayList
add (Object o) - adds an object to the ArrayList
ArrayList supports dynamic arrays that can
grow as needed.
In Java, standard arrays are of a fixed length.
After arrays are created, they cannot grow or
shrink, which means that you must know in
advance how many elements an array will
hold. But, sometimes, you may not know until
run time precisely how large of an array you
need.
Solution: ArrayList a variable-length array
of object references. That is, an ArrayList can
dynamically increase or decrease in size.
Array lists are created with an initial size.
When this size is exceeded, the collection is
automatically enlarged. When objects are
removed, the array may be shrunk.
A java ArrayList is used to store an ordered
group of elements where duplicates are
allowed.
Most important methods
add(int index, Object o) adds the object o the the array list at
the given index
get(int index) - retrieves object reference from ArrayList index
position
size() - returns ArrayList size
remove(int index) - removes element at specified position in the
list. Shifts any subsequent elements to the left
14
remove (Object o) - removes the object o from the list
set(int index, Object o)- used for updating an element; it
replaces the element present at the specified index with the
object o
int indexOf(Object o)- finds the index in the list of the first
occurrence of the specified element. If the element is not
present in the list returns -1
Object get(int index) returns the object of list which is present
at the specified index
clear() - removes all the elements
14
boolean contains(Object o)- checks whether the given object o
is present in the array list
QUALITY. PRODUCTIVITY. INNOVATION.
HashSet
implements the Set interface
doesnt maintain any order, the elements
would be returned in any random order.
doesnt allow duplicates. If you try to add a
duplicate element in HashSet, the old value
would be overwritten.
allows null values however if you insert more
than one nulls it would still return only one
null value.
is non-synchronized
boolean add(Element e) - adds the element e to the Set
void clear() removes all the elements from the Set
boolean contains(Object o) checks whether the specified
Object o is present in the list or not. If the object has been
15found it returns true, false otherwise.
boolean isEmpty() returns true if there is no element in the
Set
Most important methods
int size()- returns the number of elements of a Set
Boolean remove(Object o) removes the specified object from
the Set
15
QUALITY. PRODUCTIVITY. INNOVATION.
HashMap
void clear()- removes all the keys and values form the specified
map
HashMap implementation provides constanttime performance for the basic operations
(get and put), assuming the hash function
disperses the elements properly among the
buckets.
It is not an ordered collection which means it
does not return the keys and values in the
same order in which they have been inserted
into the HashMap.
It does not any kind of sorting to the stored
keys and Values
boolean containsKey(Object key) returns true or false based
on whether the specified key is found in the map
boolean containsValue(Object Value)- similar to containsKey
method, however it looks for the specified value instead of key
Value get(Object key) returns the value of the specified key
boolean isEmpty() checks whether the map is empty
16
Set keySet()- returns the Set of the keys fetched from the map
value put(Key k, Value v)-inserts key value mapping into the
map.
Most important methods
int size() returns size of the map
Collection values() returns a Collection of values of map
Value remove(Object key)- removes the key-value pair for the
specified key
16
void putAll(Map m) copies all the elements of a map into the
specified map m
QUALITY. PRODUCTIVITY. INNOVATION.
Q&A
17
QUALITY. PRODUCTIVITY. INNOVATION.