3 - Arrays and Strings
3 - Arrays and Strings
Learning Objective:
It is possible to combine the declaration of the array variable with the allocation of the
array itself, as shown here,
1
int month_days[ ] = new int[12];
In Java, multidimensional arrays are actually arrays of arrays. Consider the following example,
Output:
01234
56789
10 11 12 13 14
15 16 17 18 19
2
int al[ ] = new int[3];
int[ ] a2 = new int[3];
data_type [] array_name;
Whenever an array variable is assigned to another array variable, it simply copies the
reference, not the copy of array contents. For example,
int[] a = {10,20,30};
int [] b = a;
The above statements create an array of three integers and make two different variables refer to
it, as shown below,
10 20 30
0 1 2
3
Any changes made through either variable will be seen by the other. For example, if we
set a[0] = 100, and then display b[0], the result is 100. Because a and b are different names for
the same thing, they are sometimes called aliases.
If we actually want to copy the array, not just the reference, then we have to create a new array
and copy the elements from one to the other, like this:
Alternatively java.util.Arrays provides a method copyOf to copy contents of one array to another
array.
where the second parameter is the number of elements you want to copy.
The array length is usually the number of elements present in an array. There is no
method available in java to find the length of the array, but we can make use of attribute ‘length’
to find the array length. For example,
The array with name ‘a’ holds 10 integer elements, wherein the variable arrayLength is assigned
with the length of the array ‘a’ calculated using the ‘length’ attribute. So, the arrayLength will
also contain the value of 10.
Apart from using the traditional for-loop for traversing the array, Java supports the use of
for-each loop to traverse the array in a different form. The syntax of for-each loop is as given
below,
4
for(type var : arrayName){
//contents of loop
Output:
Printing Array Values using For-each Loop
125 132 95 116 110
String Fundamentals
Strings are basically an array of characters. In the case of Java, Strings are formed as an
object and are immutable (cannot grow). Whenever a change to a string is made, a completely
new string is created. Also every string constant is actually a string object. For example,
System.out.println(“Welcome to the World”);
Here the string “Welcome to the World” is a string constant.
Constructor Description
String() Default constructor for empty string
String(String var) Creates a string value given on the heap
Creates String objects and stores the array of
String(char [] arr)
characters in it
creates and initializes a string object with a
String(char [] arr, int startIndex, int count)
subrange of a character array
5
Consider the following program,
Output:
String1 =
String2 = Hello Java
String3 = Java
String4 = ndo
String Length
Java supports a method length() in order to find the length of the string. Basically the
length of a string defines the number of characters present within the string. The signature of the
length() method is as given below,
public int length();
Consider the following example that illustrates the working of length() in case of strings,
6
Output:
Length of string1 is 11
Length of string2 is 8
char charAt(int index) returns char value for the particular index
returns true or false after matching the
boolean contains(CharSequence s)
sequence of char values.
checks the equality of string with the given
boolean equals(Object another)
object.
boolean isEmpty() checks if the string is empty.
String concat(String str) concatenates the specified string.
String toLowerCase() returns a string in lowercase.
String toUpperCase() returns a string in uppercase.
removes beginning and ending spaces of this
String trim()
string.
7
Character Extraction
There are several ways which are provided by java to extract characters from String class
objects. String is treated as an object in Java, so we can’t directly access the characters that
comprise a string. For doing this String class provides various predefined methods.
Output:
Length of str : 40
indexOf(i) : 8
lastIndexOf(i) : 38
indexOf(e, 2) : 6
lastIndexOf(e, 40) : 6
indexOf(in, 2) : 28
8
compareTo compares values lexicographically and returns an integer value that describes
if the first string is less than, equal to or greater than the second string.
Suppose s1 and s2 are two String objects. If:
o s1 == s2 : The method returns 0.
o s1 > s2 : The method returns a positive value.
o s1 < s2 : The method returns a negative value.
Output:
true
false
0
-18
18
9
Output:
String in lowercase: india
Converting case: INDIA
StringBuffer Constructors
● StringBuffer(String str)- This constructor takes a String argument, which sets the initial
contents of the StringBuffer object and reserves space for 16 more characters without
reallocation. When no specific buffer length is specified, StringBuffer allocates space for
16 additional characters because reallocation is a time-consuming process.
Example 1:
General form
int length( )
int capacity( )
11
Output:
buffer = Hello
length = 5
capacity = 21
Example 2:
ensureCapacity( )
● You can use ensureCapacity( ) to set the size of a StringBuffer after it has been
constructed if you want to preallocate space for a certain number of characters. This is
useful if you know ahead of time that you will be appending a large number of small
strings to a StringBuffer. ensureCapacity( ) has the following general syntax:
● Here, minCapacity indicates the minimum size of the buffer. (A buffer larger than
minCapacity may be allocated for reasons of efficiency.) The formula for increasing the
capacity
● (old-capacity * 2) + 2.
12
Output:
default capacity of buffer: 16
string1: hello
capacity: 21
new capacity: 21
string2: programming
old capacity: 27
new capacity: 56
Example 3:
● The charAt( ) method returns the value of a single character from a StringBuffer.
● setCharAt allows you to change the value of a character within a StringBuffer ( ). The
following are their general forms:
13
● char charAt(int where)
● void setCharAt(int where, char ch)
● Where specifies the index of the character to be obtained for charAt( ). For setCharAt( ),
where specifies the index of the character to be changed and ch specifies the character's
new value. Where must be nonnegative and must not specify a location beyond the end of
the string for either method.
Output:
buffer before = Hello
charAt(1) before = e
buffer after = Hi
charAt(1) after = i
StringBuilder
StringBuilder is similar to StringBuffer with one major difference: it is not thread-safe because it
is not synchronized. StringBuilder has the advantage of being faster. StringBuffer must be used
instead of StringBuilder in cases where a mutable string will be accessed by multiple threads and
no external synchronization is used.
14
StringBuilder defines three constructors:
Example 1:
StringBuilder append() method
The StringBuilder append() method concatenates the given argument with this String.
Output:
Example 2:
The StringBuilder insert() method replaces the given string at the specified position with this
string.
15
Output:
HJavaello
Example 3:
StringBuilder replace() method
The replace() method of the StringBuilder replaces the given string with the specified beginIndex
and endIndex.
16
Output: HJavalo
17