Session 8
Session 8
Describe an array
Explain declaration, initialization, and instantiation of a
single-dimensional array
Explain declaration, initialization, and instantiation of a
multi-dimensional array
Explain the use of loops to process an array
Describe ArrayList and accessing values from an
ArrayList
Describe String and StringBuilder classes
Explain command line arguments
Describe Wrapper classes, autoboxing, and unboxing
Consider a situation where in a user wants to store the marks of ten students.
For this purpose, the user can create ten different variables of type integer
and store the marks in them.
What if the user wants to store marks of hundreds or thousands of students?
In such a case, one would need to create as many variables.
This can be a very difficult, tedious, and time consuming task.
Here, it is required to have a feature that will enable storing of all the marks in
one location and access it with similar variable names.
Array, in Java, is a feature that allows storing multiple values of similar type in
the same variable.
An array is a special data store that can hold a fixed number of values of a single
type in contiguous memory locations.
It is implemented as objects.
The size of an array depends on the number of values it can store and is specified
when the array is created.
After creation of an array, its size or length becomes fixed. Following figure shows
an array of numbers:
The figure displays an array of ten integers storing values such as, 20, 100, 40, and so on.
Each value in the array is called an element of the array.
The numbers 0 to 9 indicate the index or subscript of the elements in the array.
The length or size of the array is 10. The first index begins with zero.
Since the index begins with zero, the index of the last element is always length - 1.
The last, that is, tenth element in the given array has an index value of 9.
Each element of the array can be accessed using the subscript or index.
Array can be created from primitive data types such as int, float, boolean as well as from
reference type such as object.
The array elements are accessed using a single name but with different subscripts.
This induces less overhead on the system while searching for values.
The use of arrays has the following benefits:
Arrays are the best way of operating on multiple data elements of the same
type at the same time.
Memory is assigned to an array only at the time when the array is actually used.
Thus, the memory is not consumed by an array right from the time it is declared.
Single-dimensional Multi-dimensional
arrays arrays
A single-dimensional array has only one dimension and is visually represented as
having a single column with several rows of data.
Each element is accessed using the array name and the index at which the element
is located.
Following figure shows the array named marks and its elements with their values and
indices:
An exception is an abnormal event that occurs during the program execution and disrupts
the normal flow of instructions.
Declaring an Array
Declaring an array notifies the compiler that the variable will contain an array of the
specified data type. It does not create an array.
The syntax for declaring a single-dimensional array is as follows:
Syntax
datatype[] <array-name>;
where,
datatype: Indicates the type of elements that will be stored in the array.
[]: Indicates that the variable is an array.
array-name: Indicates the name by which the elements of the array will be
accessed.
For example,
int[] marks;
Similarly, arrays of other types can also be declared as follows:
byte[] byteArray;
float[] floatsArray;
boolean[] booleanArray;
char[] charArray;
String[] stringArray;
Instantiating an Array
Syntax
datatype[] <array-name> = new datatype[size];
where,
new: Allocates memory to the array.
size: Indicates the number of elements that can be stored in the array.
For example,
int[] marks = new int[4];
Initializing an Array
Since, array is an object that can store multiple values, array needs to be initialized
with the values to be stored in it.
Array can be initialized in the following two ways:
During creation:
• To initialize a single-dimensional array during creation, one must specify the values to be
stored while creating the array as follows: int[ ] marks = {65, 47, 75, 50};
• Notice that while initializing an array during creation, the new keyword or size is not
required.
• This is because all the elements to be stored have been specified and accordingly the
memory gets automatically allocated based on the number of elements.
After creation:
Another way of creating an array is to split all the three stages as follows:
int marks[]; // declaration
marks = new int[4]; // instantiation
marks[0] = 65; // initialization
Following code snippet demonstrates an example of single-dimensional array:
package session8;
public class OneDimension {
//Declare a single-dimensional array named marks
int marks[]; // line 1
/**
* Instantiates and initializes a single-dimensional array
*
* @return void
*/
public void storeMarks() {
// Instantiate the array
marks = new int[4]; // line 2
System.out.println(“Storing Marks. Please wait...”);
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Syntax
datatype[][] <array-name> = new datatype [rowsize][colsize];
where,
datatype: Indicates the type of elements that will be stored in the array.
rowsize and colsize: Indicates the number of rows and columns that the
array will contain.
new: Keyword used to allocate memory to the array elements.
For example,
int[][] marks = new int[4][2];
The array named marks consists of four rows and two columns.
A multi-dimensional array can be initialized in the following two ways:
During creation
To initialize a multi-dimensional array during creation, one must specify the values to
be stored while creating the array as follows:
int[][] marks = {{23,65}, {42,47}, {60,75}, {75,50}};
While initializing an array during creation, the elements in rows are specified in a set of
curly brackets separated by a comma delimiter.
Also, the individual rows are separated by a comma separator.
This is a two-dimensional array that can be represented in a tabular form as shown in
the following figure:
After creation
A multi-dimensional array can also be initialized after creation and
instantiation.
For example,
int[][] marks = new int[4][2];
marks[0][0] = 23; // first row, first column
marks[0][1] = 65; // first row, second column
marks[1][0] = 42;
marks[1][1] = 47;
marks[2][0] = 60;
marks[2][1] = 75;
marks[3][0] = 75;
marks[3][1] = 50;
The element 23 is said to be at position (0,0), that is, first row and first column.
Therefore, to store or access the value 23, one must use the syntax marks[0][0].
Similarly, for other values, the appropriate row-column combination must be used.
Similar to row index, column index also starts at zero. Therefore, in the given scenario,
an attempt to write marks[0][2] would result in an exception as the column size is
2 and column indices are 0 and 1.
Following code snippet demonstrates an example of two-dimensional array:
package session8;
public class TwoDimension {
/**
* Stores marks in a two-dimensional array
*
* @return void
*/
public void storeMarks() {
// Instantiate the array
marks = new int[4][2]; // line 2
System.out.println(“Storing Marks. Please wait...”);
/**
* Displays marks from a two-dimensional array
*
* @return void
*/
public void displayMarks() {
/**
* Displays marks from a two-dimensional array
*
* @return void
*/
public void displayMarks() {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
In the code, a for loop has been used to iterate the array from zero to
marks.length.
The property, length, of the array object is used to obtain the size of the array.
Within the loop, each element is displayed by using the element name and the
variable count, that is, marks[count].
Following code snippet depicts the revised displayMarks() method of the
two-dimensional array marks[][]:
...
public void displayMarks(){
System.out.println(“Marks are:”);
// outer loop
for (int row = 0; row < marks.length; row++) {
// inner loop
for (int col = 0; col < marks[row].length; col++) {
System.out.println(marks[row][col]);
}
}
}
...
The outer loop keeps track of the number of rows and inner loop keeps track of the
number of columns in each row.
Following figure shows the output of the two-dimensional array marks[][], after
using the for loop:
One can also use the enhanced for loop to iterate through an array.
Following code snippet depicts the modified displayMarks() method of
single-dimensional array marks[] using the enhanced for loop:
...
public void displayMarks() {
System.out.println(“Marks are:”);
System.out.println(value);
}
}
...
The loop will print all the values of marks[] array till marks.length without
having to explicitly specify the initializing and terminating conditions for iterating
through the loop.
Following code snippet demonstrates the calculation of total marks of each student by
using the for loop and the enhanced for loop together with the two-dimensional
array marks[][]:
...
public void totalMarks() {
// Display the marks using for loop and enhanced for loop
for (int row = 0; row < marks.length; row++) {
System.out.println(“Roll no.” + (row+1));
int sum = 0;
Also, addition and deletion of values can be performed easily. Java provides the
concept of collections to address this problem.
A collection is a single object that groups multiple elements into a single unit.
The core Collection interfaces that encapsulate different types of collections are
shown in the following figure:
The general-purpose implementations are summarized in the following table:
Interfaces Hash Resizable Tree Linked list Hash table +
table array Linked list
Set HashSet - TreeSet - LinkedHashSet
List - ArrayList - LinkedList -
Queue - - - - -
Map HashMap - TreeMap - LinkedHashMap
The ArrayList class is a frequently used collection that has the following
characteristics:
It is flexible and can be increased or decreased in size as needed.
It can be traversed by using for loop, enhanced for loop, or other iterators.
ArrayList extends AbstractList and implements the interfaces such as
List, Cloneable, and Serializable.
The Arraylist collection provides methods to manipulate the size of the array.
Methods that append one or more elements to the end of the list.
Methods that insert one or more elements at a position within the list.
A for loop
Iterator
ListIterator
Iterator interface provides methods for traversing a set of data.
It can be used with arrays as well as various classes of the Collection framework.
The Iterator interface provides the following methods for traversing a collection:
Syntax
Collections.sort(<list-name>);
/**
* Stores marks in ArrayList
*
* @return void
*/
public void storeMarks(){
System.out.println(“Storing marks. Please wait...”);
marks.add(67); // line 2
marks.add(50);
marks.add(45);
marks.add(75);
}
/**
* Displays marks from ArrayList
*
* @return void
*/
public void displayMarks() {
System.out.println(“Marks are:”);
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
The Iterator object imarks is instantiated in line 3 and attached with the marks
ArrayList using marks.iterator().
It is used to iterate through the collection.
The Iterator interface provides the hasNext() method to check if there are any
more elements in the collection as shown in line 4.
The method, next() is used to traverse to the next element in the collection.
The retrieved element is then displayed to the user in line 5.
The static method, sort() of Collections class is used to sort the ArrayList
marks in line 6 and print the values on the screen.
Following figure shows the output of the code:
Similarly, to store names of multiple persons, one can create a two-dimensional array.
However, the number of characters in an array must be fixed during creation.
This is not possible since the names of persons may be of variable sizes.
Also, manipulating the character array would be tedious and time consuming.
Java provides the String data type to store multiple characters without creating an
array.
String literals such as “Hello” in Java are implemented as instances of the
String class.
Strings are constant and immutable, that is, their values cannot be changed once
they are created.
A simple String instance can be created by enclosing a string literal inside double
quotes as shown in the following code snippet:
...
String name = “Mary”;
// This is equivalent to:
char name[] = {‘M’, ‘a’, ‘r’, ’y’};
...
An instance of a String class can also be created using the new keyword, as shown
in code snippet:
String str = new String();
The code creates a new object of class String, and assigns its reference to the
variable str.
Java also provides special support for concatenation of strings using the plus (+)
operator and for converting data of other types to strings as depicted in the following
code snippet:
...
String str = “Hello”; String str1 = “World”;
// The two strings can be concatenated by using the operator ‘+’
System.out.println(str + str1);
One can convert a character array to a string as depicted in the following code snippet:
char[] name = {‘J’, ‘o’, ‘h’, ‘n’}; String empName = new String(name);
The java.lang.String class is a final class, that is, no class can extend it.
The java.lang.String class differs from other classes, in that one can use ‘+=’
and ‘+’ operators with String objects for concatenation.
If the string is not likely to change later, one can use the String class.
Thus, a String class can be used for the following reasons:
The threads will only read them, which is normally a thread safe operation.
If the string is likely to change later and it will be shared between multiple threads, one
can use the StringBuffer class.
The use of StringBuffer class ensures that the string is updated correctly.
However, the drawback is that the method execution is comparatively slower.
If the string is likely to change later but will not be shared between multiple threads,
one can use the StringBuilder class.
The StringBuilder class can be used for the following reasons:
length(String str)
• The length() method is used to find the length of a string. For example,
• String str = ”Hello”;
• System.out.println(str.length()); // output: 5
charAt(int index)
• The charAt() method is used to retrieve the character value at a specific index.
• The index ranges from zero to length() – 1.
• The index of the first character starts at zero. For example,
• System.out.println(str.charAt(2)); // output: ‘l’
concat(String str)
indexOf(String str)
• The indexOf() method returns the index of the first occurrence of the specified
character or string within a string.
• If the character or string is not found, the method returns -1. For example,
• System.out.println(str.indexOf(“e”)); // output: 1
lastIndexOf(String str)
• The lastIndexOf() method returns the index of the last occurrence of a specified
character or string from within a string.
• The specified character or string is searched backwards that is the search begins from
the last character. For example,
• System.out.println(str.lastIndexOf(“l”)); // output: 3
trim()
• The trim() method returns a new string by trimming the leading and trailing
whitespace from the current string. For example,
• String str1 = ” Hello “;
• System.out.println(str1.trim()); // output: ‘Hello’
• The trim() method will return ‘Hello’ after removing the spaces.
Following code snippet demonstrates the use of String class methods:
public class Strings {
/**
* Displays strings using various String class methods
*
* @return void
*/
public void displayStrings(){
// using various String class methods System.out.println(“String
length is:”+ str.length()); System.out.println(“Character at index 2
is:”+ str.charAt(2)); System.out.println(“Concatenated string is:”+
str.concat(“World”)); System.out.println(“String comparison is:”+
str.compareTo(“World”)); System.out.println(“Index of o is:”+
str.indexOf(“o”)); System.out.println(“Last index of l is:”+
str.lastIndexOf(“l”)); System.out.println(“Replaced string is:”+
str.replace(‘e’,’a’)); System.out.println(“Substring is:”+
str.substring(2, 5));
System.out.println(“Integer to String is:”+ strLength.toString()) ;
String str1=” Hello “; System.out.println(“Untrimmed
string is:”+ str1); System.out.println(“Trimmed string
is:”+ str1.trim());
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Internally, the system treats these objects as a variable-length array containing a sequence of
characters.
The length and content of the sequence of characters can be changed through methods
available in the StringBuilder class.
The StringBuilder class also provides a length() method that returns the length of the
character sequence in the class.
Unlike strings a StringBuilder object also has a property capacity that specifies the
number of character spaces that have been allocated.
The capacity is returned by the capacity() method and is always greater than or equal to
the length.
The capacity will automatically expand to accommodate the new strings when added to the
string builder.
append()
• The append() method is used to append values at the end of the
StringBuilder object.
• This method accepts different types of arguments, including char, int, float,
double, boolean, and so on, but the most common argument is of type
String.
• For example,
• StringBuilder str = new StringBuilder(“JAVA ”);
• System.out.println(str.append(“SE ”);
// output: JAVA SE
• System.out.println(str.append(7); // output: JAVA SE
7
insert()
• For example,
• StringBuilder str = new StringBuilder(“JAVA 7 ”);
• System.out.println(str.insert(5, “SE”);
// output: JAVA SE 7
delete()
• The delete() method deletes the specified number of characters from the
invoking StringBuilder object.
• For example,
• StringBuilder str = new StringBuilder(“JAVA SE 7”);
• System.out.println(str.delete(4,7); // output: JAVA 7
reverse()
• The reverse() method is used to reverse the characters within a
StringBuilder object.
• For example,
• StringBuilder str = new StringBuilder(“JAVA SE 7”);
• System.out.println(str.reverse());
// output: 7 ES AVAJ
Following code snippet demonstrates the use of methods of the StringBuilder
class:
package session8;
public class StringBuilders {
/**
* Displays strings using various StringBuilder methods
*
* @return void
*/
public void displayStrings(){
String arrays can be created in Java in the same manner as arrays of primitive data types.
However, no memory is allocated to store the characters that make up the individual strings.
Loops can be used to initialize as well as display the values of a String array.
The args[] array accepts the arguments and stores them at appropriate locations
in the array.
The length of the array is determined from the number of arguments passed at runtime.
The basic purpose of command line arguments is to specify the configuration information for
the application.
The main() method is the entry point of a Java program, where objects are created and
methods are invoked.
The static main() method accepts a String array as an argument as depicted in the
following code snippet:
The parameter of the main() method is a String array that represents the
command line arguments.
The size of the array is set to the number of arguments specified at runtime.
All command line arguments are passed as strings.
Following code snippet demonstrates an example of command line arguments:
package session8;
public class CommandLine {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
To run the program with command line arguments using NetBeans IDE, perform the
following steps:
• Right-click the project name in the Projects tab and click Properties.
1 • The Project Properties dialog box is displayed.
In other words, the wrapper classes allow accessing primitive data types as objects.
The wrapper classes for the primitive data types are: Byte, Character,
Integer, Long, Short, Float, Double, and Boolean.
The primitive types and the corresponding wrapper types are listed in the following
table:
What is the need for wrapper classes?
For example, most of the collections store objects and not primitive data types.
Many of the activities reserved for objects will not be available to primitive data
types.
Also, many utility methods are provided by the wrapper classes that help to
manipulate data.
Wrapper classes convert primitive data types to objects, so that they can be stored
in any type of collection and also passed as parameters to methods.
typeValue()
• The typeValue() method can also be used to return the value of an object as
its primitive type.
Some of the wrapper classes and their methods are listed in the following table:
The difference between creation of a primitive type and a wrapper type is as follows:
The first statement declares and initializes the int variable x to 10.
The second statement instantiates an Integer object y and initializes it with the
value 20.
In this case, the reference of the object is assigned to the object variable y.
The memory assignment for the two statements is shown in the following figure:
It is clear from the figure that x is a variable that holds a value whereas y is an object
variable that holds a reference to an object.
The six methods of type parseXxx() available for each numeric wrapper type are
in close relation to the valueOf() methods of all the numeric wrapper classes
including Boolean.
The two type of methods, that is, parseXxx() and valueOf(), take a String
as an argument.
If the String argument is not properly formed, both the methods throw a
NumberFormatException.
These methods can convert String objects of different bases if the underlying
primitive type is any of the four integer types.
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
The class Wrappers consists of the calcResult() method that accepts two
numbers and an operator as the parameter.
The main() method is used to convert the String arguments to int type by using
the Integer wrapper class.
Next, the object, objWrap of Wrappers class is created to invoke the
calcResult() method with three arguments namely, num1, num2, and args[2]
which is the operator specified by the user as the third argument.
To run the class, specify the command line values as 35, 48, and - in the Arguments
box as shown in the following figure:
When the program is executed, the first two arguments are stored in the args[0]
and args[1] elements and then, converted to integers.
The third argument is stored in the args[2] element.
It is the operator to be applied on the numbers.
The output of the code is shown in the following figure:
Autoboxing
The automatic conversion of primitive data types such as int, float, and so on to
their corresponding object types such as Integer, Float, and so on during
assignments and invocation of methods and constructors is known as autoboxing.
For example,
ArrayList<Integer> intList = new ArrayList<Integer>();
intList.add(10); // autoboxing
Integer y = 20; // autoboxing
Unboxing
The automatic conversion of object types to primitive data types is known as unboxing.
For example,
int z = y; // unboxing
Using autoboxing and unboxing, one can make use of the methods of wrapper
classes as and when required.
Following code snippet demonstrates an example of autoboxing and unboxing:
package session8;
public class AutoUnbox {
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
Character chBox = ‘A’; // Autoboxing a character
char chUnbox = chBox; // Unboxing a character
The class AutoUnbox consists of two variable declarations chBox and chUnbox.
chBox is an object type and chUnbox is a primitive type of character variable.
Following figure shows the output of the code:
The figure shows that both primitive as well as object type variable give the same
output.
However, the variable of type object, that is chBox, can take advantage of the
methods available with the wrapper class Character which are not available with
the primitive type char.
An array is a special data store that can hold a fixed number of values of a single type
in contiguous memory locations.
A single-dimensional array has only one dimension and is visually represented as
having a single column with several rows of data.
A multi-dimensional array in Java is an array whose elements are also arrays.
A collection is an object that groups multiple elements into a single unit.
Strings are constant and immutable, that is, their values cannot be changed once they
are created.
StringBuilder objects are similar to String objects, except that they are mutable.
Java provides a set of classes known as Wrapper classes for each of its primitive data
type that ‘wrap’ the primitive type into an object of that class.
The automatic conversion of primitive types to object types is known as autoboxing
and conversion of object types to primitive types is known as unboxing.