0% found this document useful (0 votes)
28 views17 pages

3 - Arrays and Strings

The document discusses arrays and strings in Java. It covers topics like one-dimensional and multidimensional arrays, array declaration syntax, assigning array references, array length, for-each loops for arrays, string fundamentals like immutability, string constructors, string length, special string operations like comparison, searching in strings, and changing case in strings. Examples are provided for each topic to demonstrate the concepts.

Uploaded by

aashish
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)
28 views17 pages

3 - Arrays and Strings

The document discusses arrays and strings in Java. It covers topics like one-dimensional and multidimensional arrays, array declaration syntax, assigning array references, array length, for-each loops for arrays, string fundamentals like immutability, string constructors, string length, special string operations like comparison, searching in strings, and changing case in strings. Examples are provided for each topic to demonstrate the concepts.

Uploaded by

aashish
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/ 17

ARRAY AND STRINGS

Learning Objective:

● Arrays: one dimensional and multidimensional


● Alternative Array Declaration
● Assigning Array References
● Length of an array
● The For-Each style for loop for Array
● String Fundamentals
● String Constructors
● Special String Operations, String Length, String Comparison
● String Buffer and String Builder

Arrays: One Dimensional and Multidimensional Array’s

An array is a group of like-typed variables that are referred to by a common name.


Arrays of any type can be created and may have one or more dimensions.

A one-dimensional array is, essentially, a list of like-typed variables. To create an array,


first an array variable of the desired type must be created. The general form of a
one-dimensional array declaration is
type var-name[ ];

Here, ‘type’ declares the base type of the array.

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];

Consider the following example,

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

There is a second form that may be used to declare an array:


type[ ] var-name;
Here, the square brackets follow the type specifier, and not the name of the array variable.
For example, the following two declarations are equivalent,

2
int al[ ] = new int[3];
int[ ] a2 = new int[3];

The following declarations are also equivalent:

char twod1[ ][ ] = new char[3][4];


char[ ][ ] twod2 = new char[3][4];

Alternative Array Declaration Syntax

An array can be declared alternatively as shown below,

data_type [] array_name;

For example, the following declarations of array are equivalent,

int a[] = new int[5];

int [] b = new int[5];

Similarly, the following declarations are also equivalent,

int a[][] = new int[5][4];

int [][] b = new int[5][4];

Assigning Array References

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:

double[] b = new double[3];


for (int i = 0; i < 3; i++) {
b[i] = a[i];
}

Alternatively java.util.Arrays provides a method copyOf to copy contents of one array to another
array.

double[] b = Arrays.copyOf(a, 3);

where the second parameter is the number of elements you want to copy.

Length Member of an Array

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,

int [] a = new int[10];

int arrayLength = a.length;

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.

The For-Each style for loop for Array

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

Consider the following program,

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.

The String Constructors


Java defines string class in a package java.lang.String. The strings can be built in various
ways using different constructors of String class. The different string constructors are given
below,

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

Special String Operations


There are many useful methods provided by java to perform special operations, the list of
some methods are listed below,

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.

char charAt(int index) Used to extract single character from string


void getChars() used to extract more than one character.
extract characters from String object and then
byte [] getbyte()
convert the characters in a byte array

Searching and Comparing Strings


To search a string, java provides indexOf() and lastIndexOf() method. The indexOf()will
return the index of the first occurrence of a character variable in the invoked string, whereas,
lastIndexOf() will return the index of the last occurrence of a character variable in the invoked
string.

Output:
Length of str : 40
indexOf(i) : 8
lastIndexOf(i) : 38
indexOf(e, 2) : 6
lastIndexOf(e, 40) : 6
indexOf(in, 2) : 28

Similar to searching java provides 2 methods for comparing the strings,


Method Description
equals() compares the original content of the string. It compares values of string for
equality.

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.

Consider the following program,

Output:
true
false
0
-18
18

Changing the case of Characters within the String


The following program illustrates the converting lowercase letters to uppercase letters
with in string,

9
Output:
String in lowercase: india
Converting case: INDIA

String Buffer and String Builder

A modifiable string is supported by StringBuffer. String, as you may know, represents


immutable, fixed-length character sequences. StringBuffer, on the other hand, represents writable
and growable character sequences. Characters and substrings can be inserted in the middle or
appended to the end of a StringBuffer. StringBuffer will automatically expand to accommodate
such additions, and it frequently has more characters preallocated than are actually required to
allow for expansion.

StringBuffer Constructors

StringBuffer defines these four constructors:

● StringBuffer( ) - The default constructor (the one with no parameters) allocates 16


characters space without reallocation.
10
● StringBuffer(int size)- This version of constructor sets the size of the buffer explicitly

● 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.

● StringBuffer(CharSequence chars)- This form of constructor creates an object that


contains the character sequence contained in chars and reserves space for 16 more
characters.

Example 1:

length( ) and capacity( )

● Length() method returns the current length of a StringBuffer


● Capacity() method shows the total allocated capacity.

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:

● void ensureCapacity(int minCapacity)

● 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:

charAt( ) and setCharAt( )

● 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:

StringBuilder() - It creates an empty String Builder with a capacity of 16 by default.


StringBuilder(String str)- With the specified string, it creates a String Builder.
StringBuilder(int length)-It creates an empty String Builder with the length set to the specified
capacity.

Example 1:
StringBuilder append() method
The StringBuilder append() method concatenates the given argument with this String.

Output:

Hello Great learning

Example 2:

StringBuilder insert() method

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

You might also like