SlideShare a Scribd company logo
Page 1 of 19
Class Notes on Arrays and Strings (Week - 4)
Contents:-1DArray,CreatinganArray,Initialization,ArrayLength,2-DArray,Variable Size Arrays,Strings,StringArrays,
StringMethods,StringBufferClass,Manipulationof Strings,basicstringhandling concepts, -String(char(),compare(),
equals(),equalsIgnorecase(),indexOf(),length(),substring(),toCharArray(),toLowercCase(),tostring(),methods),concept
of mutable andimmutable string.
Arrays
An array is a very common type of data structure where in all elements must be of the same data type. Once
defined , the size of an array is fixed and cannot increase to accommodate more elements. The first element
of an array starts with zero.
An array is a container object that holds a fixed number of values of a single type. The length of an array is
established when the array is created. After creation, its length is fixed.
Characteristics of an Array:-
 An array is a group of contiguous or related data items that share a common name.
 Used when programs have to handle large amount of data.
 Each value is stored at a specific position.
 Position is called a index or superscript. Base index = 0.
 The ability to use a single name to represent a collection of items and refer to an item by specifying the
item number enables us to develop concise and efficient programs. For example, a loop with index as
the control variable can be used to read the entire array, perform calculations, and print out the
results.
An array of ten elements
Each item in an array is called an element, and each element is accessed by its numerical index. As shown in
the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed
at index 8.
Using and array in your program is a 3 step process -
1) Declaring your Array
2) Constructing your Array
3) Initializing your Array
Page 2 of 19
Syntax for Declaring Array Variables is
Form 1:
Type arrayname[];
Form 2:
Type[] arrayname;
Examples:
int[] students;
int students[];
Note: we don’t specify the size of arrays in the declaration.
Constructing an Array
After declaring arrays, we need to allocate memory for storage array items.In Java, this is carried out by using
“new” operator, as follows:
Arrayname = new type[size];
Examples:
students = new int[7];
InitialisationofArrays
Once arrays are created, they need to be initialised with some values before access their content. A general
form of initialisation is:
Arrayname [index/subscript] = value;
Example:
students[0] = 50;
students[1] = 40;
Like C, Java creates arrays starting with subscript 0 and ends with value one less than the size specified.Unlike
C, Java protects arrays from overruns and under runs. Trying to access an array beyond its boundaries will
generate an error message.
Arrays – Length
Arrays are fixed length. Length is specified at create time. In java, all arrays store the allocated size in a
variable named “length”. We can access the length of arrays as arrayName.length:
e.g. int x = students.length; // x = 7
The following program, ArrayDemo, creates an array of integers, puts some values in it, and prints each value to
standard output.
Page 3 of 19
class ArrayDemo {
public static void main(String[] args) {
// declares an array of integers
int[] anArray;
// allocates memory for 10 integers
anArray = new int[10];
// initialize first element
anArray[0] = 100;
// initialize second element
anArray[1] = 200;
// etc.
anArray[2] = 300;
anArray[3] = 400;
anArray[4] = 500;
anArray[5] = 600;
anArray[6] = 700;
anArray[7] = 800;
anArray[8] = 900;
anArray[9] = 1000;
System.out.println("Element at index 0: "
+ anArray[0]);
System.out.println("Element at index 1: "
+ anArray[1]);
System.out.println("Element at index 2: "
+ anArray[2]);
System.out.println("Element at index 3: "
+ anArray[3]);
System.out.println("Element at index 4: "
+ anArray[4]);
System.out.println("Element at index 5: "
+ anArray[5]);
System.out.println("Element at index 6: "
+ anArray[6]);
System.out.println("Element at index 7: "
+ anArray[7]);
System.out.println("Element at index 8: "
+ anArray[8]);
System.out.println("Element at index 9: "
+ anArray[9]);
}
}
The output from this program is:
Element at index 0: 100
Element at index 1: 200
Element at index 2: 300
Element at index 3: 400
Element at index 4: 500
Element at index 5: 600
Element at index 6: 700
Element at index 7: 800
Element at index 8: 900
Element at index 9: 1000
Page 4 of 19
In a real-world programming situation, you'd probably use one of the supported looping constructs to iterate
through each element of the array, rather than write each line individually as shown above. However, this
example clearly illustrates the array syntax.
Arrays – Another Example
// StudentArray.java: store integers in arrays and access
class StudentArray{
public static void main(String[] args) {
int[] students;
students = new int[7];
System.out.println("Array Length = " + students.length);
for ( int i=0; i < students.length; i++)
students[i] = 2*i;
System.out.println("Values Stored in Array:");
for ( int i=0; i < students.length; i++)
System.out.println(students[i]);
}
}
Arrays – Initializing at Declaration
Arrays can also be initialised like standard variables at the time of their declaration.
Type arrayname[] = {list of values};
Example:
int[] students = {55, 69, 70, 30, 80};
 Creates and initializes the array of integers of length 5.
 In this case it is not necessary to use the new operator.
Example of Arrays using initializationat declaration
// StudentArray.java: store integers in arrays and access
class StudentArray{
public static void main(String[] args) {
int[] students = {55, 69, 70, 30, 80};
System.out.println("Array Length = " + students.length);
System.out.println("Values Stored in Array:");
for ( int i=0; i < students.length; i++)
System.out.println(students[i]);
}
}
Page 5 of 19
Two-Dimensional Arrays
An array keeps track of multiple pieces of information in linear order, a one-dimensional list. However, the
data associated with certain systems (a digital image, a board game, etc.) lives in two dimensions. To visualize
this data, we need a multi-dimensional data structure, that is, a multi-dimensional array.
A two-dimensional array is really nothing more than an array of arrays (a three-dimensional array is an array of
arrays of arrays). Think of your dinner. You could have a one-dimensional list of everything you eat:
(lettuce, tomatoes, salad dressing, steak, mashed potatoes, string beans, cake, ice cream, coffee)
Or you could have a two-dimensional list of three courses, each containing three things you eat:
(lettuce, tomatoes, salad dressing) and (steak, mashed potatoes, string beans) and (cake, ice cream, coffee)
In the case of an array, our old-fashioned one-dimensional array looks like this:
int[] myArray = {0,1,2,3};
And a two-dimensional array looks like this:
int[][] myArray = { {0,1,2,3}, {3,2,1,0}, {3,5,6,1}, {3,8,3,4} };
For our purposes, it is better to think of the two-dimensional array as a matrix. A matrix can be thought of as a
grid of numbers, arranged in rows and columns, kind of like a bingo board. We might write the two-
dimensional array out as follows to illustrate this point:
int[][] myArray = { {0, 1, 2, 3},
{3, 2, 1, 0},
{3, 5, 6, 1},
{3, 8, 3, 4} };
We can use this type of data structure to encode information about an image. For example, the following
grayscale image could be represented by the following array:
int[][] myArray = { {236, 189, 189, 0},
{236, 80, 189, 189},
{236, 0, 189, 80},
{236, 189, 189, 80} };
Page 6 of 19
2D arrays manipulations
Declaration:
int myArray [][];
Creation:
myArray = new int[4][3]; // OR
int myArray [][] = new int[4][3];
Initialisation:
Single Value:
myArray[0][0] = 10;
Multiple values:
int tableA[2][3] = {{10, 15, 30}, {14, 30, 33}};
int tableA[][] = {{10, 15, 30}, {14, 30, 33}};
Variable Size Arrays
Java treats multidimensional arrays as “arrays of arrays”. It is possible to declare a 2D arrays as follows:
Arrays of Objects
Arrays can be used to store objects
Circle[] circleArray;
circleArray = new Circle[25];
The above statement creates an array that can store references to 25 Circle objects. Circle objects are not
created.
Create the Circle objects and stores them in the array.
//declare an array for Circle
Circle circleArray[] = new Circle[25];
int r = 0;
// create circle objects and store in array
for (r=0; r <25; r++)
circleArray[r] = new Circle(r);
Page 7 of 19
Strings in Java
Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming
language, strings are objects.
The Java platform provides the String class to create and manipulate strings.
Creating Strings:
The most direct way to create a string is to write:
String greeting = "Hello world!";
Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this
case, "Hello world!'.
As with any other object, you can create String objects by using the new keyword and a constructor. The String
class has eleven constructors that allow you to provide the initial value of the string using different sources,
such as an array of characters:
public class StringDemo{
public static void main(String args[]){
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
String helloString = new String(helloArray);
System.out.println( helloString );
}
}
This would produce following result:
Hello.
Following are some useful classes that Java provides for String operations.
 String Class
 StringBuffer Class
 StringTokenizer Class
Although character arrays have the advantage of being able to query their length, they themselves are too
primitive and don’t support a range of common string operations. For example, copying a string, searching for
specific pattern etc.
Recognising the importance and common usage of String manipulation in large software projects, Java
supports String as one of the fundamental data type at the language level. Strings related book keeping
operations (e.g., end of string) are handled automatically.
Note: The String class is immutable, so that once it is created a String object cannot be changed. If there is a
necessity to make a lot of modifications to Strings of characters then you should use String Buffer Classes.
Page 8 of 19
String Length:
Methods used to obtain information about an object are known as accessor methods. One accessor method
that you can use with strings is the length() method, which returns the number of characters contained in the
string object.
After the following two lines of code have been executed, len equals 17:
public class StringDemo {
public static void main(String args[]) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
}
}
This would produce following result:
String Length is : 17
Concatenating Strings:
The String class includes a method for concatenating two strings:
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also use the concat()
method with string literals, as in:
"My name is ".concat("Zara");
Strings are more commonly concatenated with the + operator, as in:
"Hello," + " world" + "!"
which results in:
"Hello, world!"
Let us look at the following example:
public class StringDemo {
public static void main(String args[]) {
String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
}
}
Page 9 of 19
This would produce following result:
Dot saw I was Tod
Creating Format Strings:
You have printf() and format() methods to print output with formatted numbers. The String class has an
equivalent class method, format(), that returns a String object rather than a PrintStream object.
Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to
a one-time print statement. For example, instead of:
System.out.printf("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
you can write:
String fs;
fs = String.format("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
System.out.println(fs);
String Array In Java
In this section, you will learn how to use string array in Java. Here, you will see how to declare a string array
and the syntax for using in the program. This section provides you a simple java program which illustrates
about the string array in very efficient manner.
Program Description:
Following code of the program declares a string array and store some strings like "chandan", "tapan", "Amar",
"santosh", and "deepak" to it. And in the main method these string are displayed one by one by retrieving
from the specified string array named names. In this program all the string values are stored in the names
string array at the declaration time.
Here is the code of this program:
class StringCharacter
{
static String[] names={"chanan","tapan","Amar","santosh","deepak"};
public static void main(String args[]){
for(int i=0;i<5;i++){
System.out.println(names[i]);
}
}
}
Page 10 of 19
Output of program:
C:>javac StringCharacter.java
C:>java StringCharacter
chanan
tapan
Amar
santosh
deepak
C:>
You can also initialize Strings Arrays by using new operator as shown below
String city[] = new String[5];
city[0] = new String(“Melbourne”);
city[1] = new String(“Sydney”);
String class – Constructors
The String class supports several constructors. To create an empty String, you call the default constructor. For
example,
String s = new String();
will create an instance of String with no characters in it. Frequently, you will want to create strings that have
initial values. The String class provides a variety of constructors to handle this. To create a String initialized by
an array of characters, use the constructor shown here:
String(char chars[ ])
Here is an example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
This constructor initializes s with the string "abc".
You can specify a subrange of a character array as an initializer using the following constructor:
String(char chars[ ], int startIndex, int numChars)
Here, startIndex specifies the index at which the subrange begins, and numChars specifies the number of
characters to use. Here is an example:
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
Page 11 of 19
This initializes s with the characters cde.
You can construct a String object that contains the same character sequence as another String object using
this constructor:
String(String strObj)
Here, strObj is a String object. Consider this example:
// Construct one String from another.
class MakeString {
public static void main(String args[]) {
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
The output from this program is as follows:
Java
Java
As you can see, s1 and s2 contain the same string.
Even though Java's char type uses 16 bits to represent the Unicode character set, the typical format for strings
on the Internet uses arrays of 8-bit bytes constructed from the ASCII character set. Because 8-bit ASCII strings
are common, the String class provides constructors that initialize a string when given a byte array. Their forms
are shown here:
String(byte asciiChars[ ])
String(byte asciiChars[ ], int startIndex, int numChars)
Here, asciiChars specifies the array of bytes. The second form allows you to specify a subrange. In each of
these constructors, the byte-to-character conversion is done by using the default character encoding of the
platform. The following program illustrates these constructors:
// Construct string from subset of char array.
class SubStringCons {
public static void main(String args[]) {
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}
}
Page 12 of 19
This program generates the following output:
ABCDEF
CDE
Extended versions of the byte-to-string constructors are also defined in which you can specify the character
encoding that determines how bytes are converted to characters. However, most of the time, you will want to
use the default encoding provided by the platform.
Note: The contents of the array are copied whenever you create a String object from an array. If you modify
the contents of the array after you have created the string, theString will be unchanged.
String Methods:
Here is the list methods supported by String class (go to link for details):
SN Methods with Description
1 char charAt(intindex)
Returnsthe character at the specifiedindex.
2 intcompareTo(Objecto)
ComparesthisStringto anotherObject.
3 intcompareTo(StringanotherString)
Comparestwostringslexicographically.
4 intcompareToIgnoreCase(Stringstr)
Comparestwostringslexicographically,ignoringcase differences.
5 Stringconcat(Stringstr)
Concatenatesthe specifiedstringtothe endof thisstring.
6 booleanendsWith(Stringsuffix)
Testsif thisstringendswiththe specifiedsuffix.
7 booleanequals(ObjectanObject)
Comparesthisstringto the specifiedobject.
8 booleanequalsIgnoreCase(StringanotherString)
ComparesthisStringto anotherString,ignoringcase considerations.
9 byte getBytes()
EncodesthisStringintoa sequence of bytesusingthe platform'sdefaultcharset,storingthe resultintoanewbyte
array.
10 byte[] getBytes(StringcharsetName
EncodesthisStringintoa sequence of bytesusingthe namedcharset,storingthe resultintoanew byte array.
11 voidgetChars(intsrcBegin,intsrcEnd,char[] dst,intdstBegin)
Copiescharactersfromthisstringintothe destinationcharacterarray.
12 inthashCode()
Returnsa hash code for thisstring.
13 intindexOf(intch)
Returnsthe index withinthisstringof the firstoccurrence of the specifiedcharacter.
14 intindexOf(intch,intfromIndex)
Returnsthe index withinthisstringof the firstoccurrence of the specifiedcharacter,startingthe searchatthe
specifiedindex.
15 intindexOf(Stringstr)
Returnsthe index withinthisstringof the firstoccurrence of the specifiedsubstring.
16 intindexOf(Stringstr,intfromIndex)
Returnsthe index withinthisstringof the firstoccurrence of the specifiedsubstring,startingatthe specifiedindex.
Page 13 of 19
17 Stringintern()
Returnsa canonical representationforthe stringobject.
18 intlastIndexOf(intch)
Returnsthe index withinthisstringof the lastoccurrence of the specifiedcharacter.
19 intlastIndexOf(intch,intfromIndex)
Returnsthe index withinthisstringof the lastoccurrence of the specifiedcharacter,searchingbackwardstartingat
the specifiedindex.
20 intlastIndexOf(Stringstr)
Returnsthe index withinthisstringof the rightmostoccurrence of the specifiedsubstring.
21 intlastIndexOf(Stringstr,intfromIndex)
Returnsthe index withinthisstringof the lastoccurrence of the specifiedsubstring,searchingbackwardstartingat
the specifiedindex.
22 intlength()
Returnsthe lengthof thisstring.
23 booleanmatches(Stringregex)
Tellswhetherornotthisstringmatchesthe givenregularexpression.
24 booleanregionMatches(booleanignoreCase,inttoffset,Stringother,intooffset,intlen)
Testsif two stringregionsare equal.
25 booleanregionMatches(inttoffset,Stringother,intooffset,intlen)
Testsif two stringregionsare equal.
26 Stringreplace(charoldChar,charnewChar)
Returnsa newstringresultingfromreplacingall occurrencesof oldCharinthisstringwithnewChar.
27 StringreplaceAll(Stringregex,Stringreplacement
Replaceseachsubstringof thisstringthatmatchesthe givenregularexpressionwiththe givenreplacement.
28 StringreplaceFirst(Stringregex,Stringreplacement)
Replacesthe firstsubstringof thisstringthatmatchesthe givenregularexpressionwiththe givenreplacement.
29 String[] split(Stringregex)
Splitsthisstringaroundmatchesof the givenregularexpression.
30 String[] split(Stringregex, intlimit)
Splitsthisstringaroundmatchesof the givenregularexpression.
31 booleanstartsWith(Stringprefix)
Testsif thisstringstarts withthe specifiedprefix.
32 booleanstartsWith(Stringprefix,inttoffset)
Testsif thisstringstarts withthe specifiedprefixbeginningaspecifiedindex.
33 CharSequence subSequence(intbeginIndex,intendIndex)
Returnsa newcharacter sequence thatisa subsequence of thissequence.
34 Stringsubstring(intbeginIndex)
Returnsa newstringthat isa substringof thisstring.
35 Stringsubstring(intbeginIndex,intendIndex)
Returnsa newstringthat isa substringof thisstring.
36 char[] toCharArray()
Convertsthisstringtoa newcharacterarray.
37 StringtoLowerCase()
Convertsall of the characters inthisStringto lowercase usingthe rulesof the defaultlocale.
38 StringtoLowerCase(Locale locale)
Convertsall of the characters inthisStringto lowercase usingthe rulesof the givenLocale.
39 StringtoUpperCase()
Convertsall of the characters inthisStringto uppercase usingthe rulesof the defaultlocale.
40 StringtoUpperCase(Localelocale)
Convertsall of the characters inthis Stringto uppercase usingthe rulesof the givenLocale.
41 Stringtrim() Returnsa copyof the string,withleadingandtrailingwhitespace omitted.
Page 14 of 19
toString() Method
toString() method is a special method that can be defined in any class. This method should return a String
argument. When an object is used in a String concatenation operation or when specified in print statement,
this method gets invoked automatically.
toString() Method–Example
class Circle {
double x,y,r;
public Circle(double centreX, double centreY, double radius ) {
x = centreX ; y = centreY; r = radius;
}
public String toString()
{
String s = “I am a Circle with centre [“ + x + “,” + y + “] and
radius [“+ r + “]”;
return s;
}
}
class CircleTest {
Circle c = new Circle(10,20, 30);
System.out.println( c );
// I am a circle with centre [10.0,20.0] and radius [30.0]
}
StringBufferClass
Unlike the String class, StringBuffer class is mutable (changeable).Use StringBufferClass class in operations
where the string has to be modified.
Page 15 of 19
StringBuffer class – Constructors
public StringBuffer() Constructs a StringBuffer with an empty string.
public StringBuffer(String str) Constructs a StringBuffer with initial value of str.
StringBuffer class – Some operations
public int length() Returns the length of the buffer
public void setCharAt(int index, char ch) Replaces the character at the specified position
s1.setLength(int n)
Truncates or extends the buffer.
If(n<s1.length(), s1 is truncated; else zeros are added to s1.
public StringBuffer append(String str) Appends the string to this string buffer.
public StringBuffer append(int i)
Append of other data items (float, char, etc.)
is supported.
Appends the string representation of the int argument to this
string buffer.
Java StringBuffer Examples
StringBuffer is a mutable sequence of characters. It is like a String but the contents of the StringBuffer can be
modified after creation.
StringBuffer Capacity
Every StringBuffer object has a capacity associated with it. The capacity of the StringBuffer is the number of
characters it can hold. It increases automatically as more contents added to it.
StringBuffer’s current capacity can be obtained using following method.
int capacity()
This method returns the current capacity of the StringBuffer object.
For example,
StringBuffer stringBuffer = new StringBuffer(“Hello World”);
System.out.println(stringBuffer.capacity());
Page 16 of 19
This will print 27 (11 + 16) on console when executed.
The actual number of characters in StringBuffer can be obtained by following method.
int length()
Returns the actual number of characters contained in the StringBuffer object.
For example,
StringBuffer stringBuffer = new StringBuffer(“Hello World”);
System.out.println(stringBuffer.length());
System.out.println(stringBuffer.capacity());
This will print,
11
27
on console when run.
Specifying initial capacity of StringBuffer
Initial capacity of the StringBuffer object can be specified using following method.
void ensureCapacity(int initialCapacity)
Ensures that the StringBuffer’s initial capacity would be grater than or equal to the specified initial capacity.
The new capacity of the StringBuffer is the maximum of,
1) The initialCapacity argument passed and
2) ( Old capacity * 2 ) + 2
StringBuffer Constructors
StringBuffer object can be created using following StringBuffer constructors.
1) StringBuffer()
Creates empty StringBuffer object having initial capacity of 16.
For example,
StringBuffer stringBuffer = new StringBuffer();
Here, capacity of stringBuffer object would be 16.
Page 17 of 19
2) StringBuffer(int capacity)
Creates empty StringBuffer object having initial capacity specified.
For example,
StringBuffer stringBuffer = new StringBuffer(50);
Here, capacity of stringBuffer object would be 50.
This constructor may throw NegativeArraySizeException if the passed argument is less than 0.
3) StringBuffer(String content)
Creates new StringBuffer object having contents same as the argument string object. The initial capacity of the
newly created StringBuffer object will be the length of the argument string object + 16.
For example,
String str = “Hello”;
StringBuffer stringBuffer = new StringBuffer(str);
Here, capacity of stringBuffer object would be 5 + 16 = 21.
String concatenation and StringBuffer
In Java, String concatenation operator (+) is internally implemented using StringBuffer.
For Example,
String str = “Hello” + “World”;
Would be executed as,
String str = new
StringBuffer().append(“Hello”).append(“World”).toString();
First an empty StringBuffer will be created and then operands of the + operator would be appended using
append method of the StringBuffer. Finally toString() method of the StringBuffer would be called to convert it
to string object and the same will be returned.
String concatenation using this approach is very expensive in nature, because it involves creation of temporary
StringBuffer object. Then that temporary object’s append method gets called and the resulting StringBuffer
would be converted back to String using toString() method.
When to use String and when StringBuffer?
If there is a need to change the contents frequently, StringBuffer should be used instead of String because
StringBuffer concatenation is significantly faster than String concatenation.
Page 18 of 19
Inserting a String in Middle of Existing StringBuffer
StringBuffer str = new StringBuffer(“Object Language”);
String aString = new String(str.toString());
Int pos = aString.indexOf(“ Language”);
str.insert(pos, “ Oriented “);
What will output of at this point?
System.out.println(“Modified String:”+str);
What will be string after executing (modifying character)?
str.setChar(6,’-’);
For more example on StringBuffer visit:
http://www.java-examples.com/java-stringbuffer-examples
StringTokenizer
 Breaks string into parts, using delimiters.
 The sequence of broken parts are the tokens of the string.
 More than one delimiter can be specified.
 The tokens can be extracted with or without the delimiters.
StringTokenizer – Functionality
 Consider the following String
CREATE_USER:1234567;John;Smith
 Separate the tokens(Here Delimiters are: “:;”)
CREATE_USER
1234567
John
Smith
StringTokenizer – Constructors
public StringTokenizer(String str, String delim,
boolean returnTokens)
Creates a SringTokenizer with the specified delimiter. If
returnTokens is true the delimiters are also returned.
public StringTokenizer(String str, String delim) Delimiters are not returned
public StringTokenizer(String str) Delimiters are (“ tnrf”)
public boolen hasMoreTokens() Returns true if more tokens are found.
Page 19 of 19
public String nextToken() Returns the next token of the String.
public String nextToken(String delim) Switches the delimiter set to characters in delim and returns
the next token.
public int countTokens() Returns the count of remaining tokens.
StringTokenizer – example
import java.util.StringTokenizer;
class TokenizerExample {
public static void main(string[] args)
{
String str = “CREATE_USER:123456;John;Smith”;
StringTokenizer tokens = new StringTokenizer(str, “:;”);
while ( tokens.hasMoreTokens() )
System.out.println(tokens.nextToken());
}
}
 Output of the program
CREATE_USER
123456
John
Smith

More Related Content

PDF
Class notes(week 4) on arrays and strings
PPTX
Java arrays
PDF
Java Arrays
PPT
Lec 25 - arrays-strings
PPT
Java Arrays
PDF
An Introduction to Programming in Java: Arrays
PDF
intorduction to Arrays in java
Class notes(week 4) on arrays and strings
Java arrays
Java Arrays
Lec 25 - arrays-strings
Java Arrays
An Introduction to Programming in Java: Arrays
intorduction to Arrays in java

What's hot (20)

PDF
Arrays in Java | Edureka
PPT
Array in Java
PPTX
Arrays in java
PPT
L10 array
PPT
Arrays Class presentation
PPTX
Array in C# 3.5
PDF
Arrays in Java
PPT
Mesics lecture 8 arrays in 'c'
PPTX
Java arrays
PPTX
Arrays in Java
PDF
PPTX
Array in Java
PPTX
Two-dimensional array in java
PPTX
Array in c#
PPT
PDF
javaarray
PPTX
Arrays basics
PDF
Array in Java
PDF
Aj unit2 notesjavadatastructures
Arrays in Java | Edureka
Array in Java
Arrays in java
L10 array
Arrays Class presentation
Array in C# 3.5
Arrays in Java
Mesics lecture 8 arrays in 'c'
Java arrays
Arrays in Java
Array in Java
Two-dimensional array in java
Array in c#
javaarray
Arrays basics
Array in Java
Aj unit2 notesjavadatastructures
Ad

Similar to Class notes(week 4) on arrays and strings (20)

PPTX
Unit-2.Arrays and Strings.pptx.................
PPTX
Arrays in Java with example and types of array.pptx
PDF
Introduction to Arrays in C
PPTX
Array in C
PPTX
arrays in c# including Classes handling arrays
PPTX
Arrays in java
DOCX
Java R20 - UNIT-3.docx
PDF
PDF
Arrays a detailed explanation and presentation
PPTX
SessionPlans_f3efa1.6 Array in java.pptx
PPTX
CH1 ARRAY (1).pptx
PPTX
Computer programming 2 Lesson 13
PDF
PDF
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
DOCX
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
PDF
Array and Collections in c#
PPTX
Arrays in Data Structure and Algorithm
PDF
Java chapter 6 - Arrays -syntax and use
PPTX
Programming in c Arrays
Unit-2.Arrays and Strings.pptx.................
Arrays in Java with example and types of array.pptx
Introduction to Arrays in C
Array in C
arrays in c# including Classes handling arrays
Arrays in java
Java R20 - UNIT-3.docx
Arrays a detailed explanation and presentation
SessionPlans_f3efa1.6 Array in java.pptx
CH1 ARRAY (1).pptx
Computer programming 2 Lesson 13
Java R20 - UNIT-3.pdf Java R20 - UNIT-3.pdf
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
Array and Collections in c#
Arrays in Data Structure and Algorithm
Java chapter 6 - Arrays -syntax and use
Programming in c Arrays
Ad

More from Kuntal Bhowmick (20)

PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
PDF
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
PDF
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
PPT
1. introduction to E-commerce
DOCX
Computer graphics question for exam solved
PDF
DBMS and Rdbms fundamental concepts
PDF
Java questions for interview
PDF
Java Interview Questions
PDF
Operating system Interview Questions
PDF
Computer Network Interview Questions
PDF
C interview questions
PDF
C question
PDF
Distributed operating systems cs704 a class test
DOCX
Cs291 assignment solution
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loops
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
1. introduction to E-commerce
Computer graphics question for exam solved
DBMS and Rdbms fundamental concepts
Java questions for interview
Java Interview Questions
Operating system Interview Questions
Computer Network Interview Questions
C interview questions
C question
Distributed operating systems cs704 a class test
Cs291 assignment solution

Recently uploaded (20)

PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PPTX
CH1 Production IntroductoryConcepts.pptx
PDF
Digital Logic Computer Design lecture notes
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPT
Project quality management in manufacturing
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPT
introduction to datamining and warehousing
PPTX
Geodesy 1.pptx...............................................
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PDF
PPT on Performance Review to get promotions
PPTX
additive manufacturing of ss316l using mig welding
PPTX
Safety Seminar civil to be ensured for safe working.
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPTX
Lecture Notes Electrical Wiring System Components
PPTX
Artificial Intelligence
UNIT-1 - COAL BASED THERMAL POWER PLANTS
CH1 Production IntroductoryConcepts.pptx
Digital Logic Computer Design lecture notes
Automation-in-Manufacturing-Chapter-Introduction.pdf
Embodied AI: Ushering in the Next Era of Intelligent Systems
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Project quality management in manufacturing
Operating System & Kernel Study Guide-1 - converted.pdf
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
introduction to datamining and warehousing
Geodesy 1.pptx...............................................
Foundation to blockchain - A guide to Blockchain Tech
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPT on Performance Review to get promotions
additive manufacturing of ss316l using mig welding
Safety Seminar civil to be ensured for safe working.
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
Lecture Notes Electrical Wiring System Components
Artificial Intelligence

Class notes(week 4) on arrays and strings

  • 1. Page 1 of 19 Class Notes on Arrays and Strings (Week - 4) Contents:-1DArray,CreatinganArray,Initialization,ArrayLength,2-DArray,Variable Size Arrays,Strings,StringArrays, StringMethods,StringBufferClass,Manipulationof Strings,basicstringhandling concepts, -String(char(),compare(), equals(),equalsIgnorecase(),indexOf(),length(),substring(),toCharArray(),toLowercCase(),tostring(),methods),concept of mutable andimmutable string. Arrays An array is a very common type of data structure where in all elements must be of the same data type. Once defined , the size of an array is fixed and cannot increase to accommodate more elements. The first element of an array starts with zero. An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. Characteristics of an Array:-  An array is a group of contiguous or related data items that share a common name.  Used when programs have to handle large amount of data.  Each value is stored at a specific position.  Position is called a index or superscript. Base index = 0.  The ability to use a single name to represent a collection of items and refer to an item by specifying the item number enables us to develop concise and efficient programs. For example, a loop with index as the control variable can be used to read the entire array, perform calculations, and print out the results. An array of ten elements Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8. Using and array in your program is a 3 step process - 1) Declaring your Array 2) Constructing your Array 3) Initializing your Array
  • 2. Page 2 of 19 Syntax for Declaring Array Variables is Form 1: Type arrayname[]; Form 2: Type[] arrayname; Examples: int[] students; int students[]; Note: we don’t specify the size of arrays in the declaration. Constructing an Array After declaring arrays, we need to allocate memory for storage array items.In Java, this is carried out by using “new” operator, as follows: Arrayname = new type[size]; Examples: students = new int[7]; InitialisationofArrays Once arrays are created, they need to be initialised with some values before access their content. A general form of initialisation is: Arrayname [index/subscript] = value; Example: students[0] = 50; students[1] = 40; Like C, Java creates arrays starting with subscript 0 and ends with value one less than the size specified.Unlike C, Java protects arrays from overruns and under runs. Trying to access an array beyond its boundaries will generate an error message. Arrays – Length Arrays are fixed length. Length is specified at create time. In java, all arrays store the allocated size in a variable named “length”. We can access the length of arrays as arrayName.length: e.g. int x = students.length; // x = 7 The following program, ArrayDemo, creates an array of integers, puts some values in it, and prints each value to standard output.
  • 3. Page 3 of 19 class ArrayDemo { public static void main(String[] args) { // declares an array of integers int[] anArray; // allocates memory for 10 integers anArray = new int[10]; // initialize first element anArray[0] = 100; // initialize second element anArray[1] = 200; // etc. anArray[2] = 300; anArray[3] = 400; anArray[4] = 500; anArray[5] = 600; anArray[6] = 700; anArray[7] = 800; anArray[8] = 900; anArray[9] = 1000; System.out.println("Element at index 0: " + anArray[0]); System.out.println("Element at index 1: " + anArray[1]); System.out.println("Element at index 2: " + anArray[2]); System.out.println("Element at index 3: " + anArray[3]); System.out.println("Element at index 4: " + anArray[4]); System.out.println("Element at index 5: " + anArray[5]); System.out.println("Element at index 6: " + anArray[6]); System.out.println("Element at index 7: " + anArray[7]); System.out.println("Element at index 8: " + anArray[8]); System.out.println("Element at index 9: " + anArray[9]); } } The output from this program is: Element at index 0: 100 Element at index 1: 200 Element at index 2: 300 Element at index 3: 400 Element at index 4: 500 Element at index 5: 600 Element at index 6: 700 Element at index 7: 800 Element at index 8: 900 Element at index 9: 1000
  • 4. Page 4 of 19 In a real-world programming situation, you'd probably use one of the supported looping constructs to iterate through each element of the array, rather than write each line individually as shown above. However, this example clearly illustrates the array syntax. Arrays – Another Example // StudentArray.java: store integers in arrays and access class StudentArray{ public static void main(String[] args) { int[] students; students = new int[7]; System.out.println("Array Length = " + students.length); for ( int i=0; i < students.length; i++) students[i] = 2*i; System.out.println("Values Stored in Array:"); for ( int i=0; i < students.length; i++) System.out.println(students[i]); } } Arrays – Initializing at Declaration Arrays can also be initialised like standard variables at the time of their declaration. Type arrayname[] = {list of values}; Example: int[] students = {55, 69, 70, 30, 80};  Creates and initializes the array of integers of length 5.  In this case it is not necessary to use the new operator. Example of Arrays using initializationat declaration // StudentArray.java: store integers in arrays and access class StudentArray{ public static void main(String[] args) { int[] students = {55, 69, 70, 30, 80}; System.out.println("Array Length = " + students.length); System.out.println("Values Stored in Array:"); for ( int i=0; i < students.length; i++) System.out.println(students[i]); } }
  • 5. Page 5 of 19 Two-Dimensional Arrays An array keeps track of multiple pieces of information in linear order, a one-dimensional list. However, the data associated with certain systems (a digital image, a board game, etc.) lives in two dimensions. To visualize this data, we need a multi-dimensional data structure, that is, a multi-dimensional array. A two-dimensional array is really nothing more than an array of arrays (a three-dimensional array is an array of arrays of arrays). Think of your dinner. You could have a one-dimensional list of everything you eat: (lettuce, tomatoes, salad dressing, steak, mashed potatoes, string beans, cake, ice cream, coffee) Or you could have a two-dimensional list of three courses, each containing three things you eat: (lettuce, tomatoes, salad dressing) and (steak, mashed potatoes, string beans) and (cake, ice cream, coffee) In the case of an array, our old-fashioned one-dimensional array looks like this: int[] myArray = {0,1,2,3}; And a two-dimensional array looks like this: int[][] myArray = { {0,1,2,3}, {3,2,1,0}, {3,5,6,1}, {3,8,3,4} }; For our purposes, it is better to think of the two-dimensional array as a matrix. A matrix can be thought of as a grid of numbers, arranged in rows and columns, kind of like a bingo board. We might write the two- dimensional array out as follows to illustrate this point: int[][] myArray = { {0, 1, 2, 3}, {3, 2, 1, 0}, {3, 5, 6, 1}, {3, 8, 3, 4} }; We can use this type of data structure to encode information about an image. For example, the following grayscale image could be represented by the following array: int[][] myArray = { {236, 189, 189, 0}, {236, 80, 189, 189}, {236, 0, 189, 80}, {236, 189, 189, 80} };
  • 6. Page 6 of 19 2D arrays manipulations Declaration: int myArray [][]; Creation: myArray = new int[4][3]; // OR int myArray [][] = new int[4][3]; Initialisation: Single Value: myArray[0][0] = 10; Multiple values: int tableA[2][3] = {{10, 15, 30}, {14, 30, 33}}; int tableA[][] = {{10, 15, 30}, {14, 30, 33}}; Variable Size Arrays Java treats multidimensional arrays as “arrays of arrays”. It is possible to declare a 2D arrays as follows: Arrays of Objects Arrays can be used to store objects Circle[] circleArray; circleArray = new Circle[25]; The above statement creates an array that can store references to 25 Circle objects. Circle objects are not created. Create the Circle objects and stores them in the array. //declare an array for Circle Circle circleArray[] = new Circle[25]; int r = 0; // create circle objects and store in array for (r=0; r <25; r++) circleArray[r] = new Circle(r);
  • 7. Page 7 of 19 Strings in Java Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and manipulate strings. Creating Strings: The most direct way to create a string is to write: String greeting = "Hello world!"; Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Hello world!'. As with any other object, you can create String objects by using the new keyword and a constructor. The String class has eleven constructors that allow you to provide the initial value of the string using different sources, such as an array of characters: public class StringDemo{ public static void main(String args[]){ char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'}; String helloString = new String(helloArray); System.out.println( helloString ); } } This would produce following result: Hello. Following are some useful classes that Java provides for String operations.  String Class  StringBuffer Class  StringTokenizer Class Although character arrays have the advantage of being able to query their length, they themselves are too primitive and don’t support a range of common string operations. For example, copying a string, searching for specific pattern etc. Recognising the importance and common usage of String manipulation in large software projects, Java supports String as one of the fundamental data type at the language level. Strings related book keeping operations (e.g., end of string) are handled automatically. Note: The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters then you should use String Buffer Classes.
  • 8. Page 8 of 19 String Length: Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object. After the following two lines of code have been executed, len equals 17: public class StringDemo { public static void main(String args[]) { String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); System.out.println( "String Length is : " + len ); } } This would produce following result: String Length is : 17 Concatenating Strings: The String class includes a method for concatenating two strings: string1.concat(string2); This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in: "My name is ".concat("Zara"); Strings are more commonly concatenated with the + operator, as in: "Hello," + " world" + "!" which results in: "Hello, world!" Let us look at the following example: public class StringDemo { public static void main(String args[]) { String string1 = "saw I was "; System.out.println("Dot " + string1 + "Tod"); } }
  • 9. Page 9 of 19 This would produce following result: Dot saw I was Tod Creating Format Strings: You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object. Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of: System.out.printf("The value of the float variable is " + "%f, while the value of the integer " + "variable is %d, and the string " + "is %s", floatVar, intVar, stringVar); you can write: String fs; fs = String.format("The value of the float variable is " + "%f, while the value of the integer " + "variable is %d, and the string " + "is %s", floatVar, intVar, stringVar); System.out.println(fs); String Array In Java In this section, you will learn how to use string array in Java. Here, you will see how to declare a string array and the syntax for using in the program. This section provides you a simple java program which illustrates about the string array in very efficient manner. Program Description: Following code of the program declares a string array and store some strings like "chandan", "tapan", "Amar", "santosh", and "deepak" to it. And in the main method these string are displayed one by one by retrieving from the specified string array named names. In this program all the string values are stored in the names string array at the declaration time. Here is the code of this program: class StringCharacter { static String[] names={"chanan","tapan","Amar","santosh","deepak"}; public static void main(String args[]){ for(int i=0;i<5;i++){ System.out.println(names[i]); } } }
  • 10. Page 10 of 19 Output of program: C:>javac StringCharacter.java C:>java StringCharacter chanan tapan Amar santosh deepak C:> You can also initialize Strings Arrays by using new operator as shown below String city[] = new String[5]; city[0] = new String(“Melbourne”); city[1] = new String(“Sydney”); String class – Constructors The String class supports several constructors. To create an empty String, you call the default constructor. For example, String s = new String(); will create an instance of String with no characters in it. Frequently, you will want to create strings that have initial values. The String class provides a variety of constructors to handle this. To create a String initialized by an array of characters, use the constructor shown here: String(char chars[ ]) Here is an example: char chars[] = { 'a', 'b', 'c' }; String s = new String(chars); This constructor initializes s with the string "abc". You can specify a subrange of a character array as an initializer using the following constructor: String(char chars[ ], int startIndex, int numChars) Here, startIndex specifies the index at which the subrange begins, and numChars specifies the number of characters to use. Here is an example: char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; String s = new String(chars, 2, 3);
  • 11. Page 11 of 19 This initializes s with the characters cde. You can construct a String object that contains the same character sequence as another String object using this constructor: String(String strObj) Here, strObj is a String object. Consider this example: // Construct one String from another. class MakeString { public static void main(String args[]) { char c[] = {'J', 'a', 'v', 'a'}; String s1 = new String(c); String s2 = new String(s1); System.out.println(s1); System.out.println(s2); } } The output from this program is as follows: Java Java As you can see, s1 and s2 contain the same string. Even though Java's char type uses 16 bits to represent the Unicode character set, the typical format for strings on the Internet uses arrays of 8-bit bytes constructed from the ASCII character set. Because 8-bit ASCII strings are common, the String class provides constructors that initialize a string when given a byte array. Their forms are shown here: String(byte asciiChars[ ]) String(byte asciiChars[ ], int startIndex, int numChars) Here, asciiChars specifies the array of bytes. The second form allows you to specify a subrange. In each of these constructors, the byte-to-character conversion is done by using the default character encoding of the platform. The following program illustrates these constructors: // Construct string from subset of char array. class SubStringCons { public static void main(String args[]) { byte ascii[] = {65, 66, 67, 68, 69, 70 }; String s1 = new String(ascii); System.out.println(s1); String s2 = new String(ascii, 2, 3); System.out.println(s2); } }
  • 12. Page 12 of 19 This program generates the following output: ABCDEF CDE Extended versions of the byte-to-string constructors are also defined in which you can specify the character encoding that determines how bytes are converted to characters. However, most of the time, you will want to use the default encoding provided by the platform. Note: The contents of the array are copied whenever you create a String object from an array. If you modify the contents of the array after you have created the string, theString will be unchanged. String Methods: Here is the list methods supported by String class (go to link for details): SN Methods with Description 1 char charAt(intindex) Returnsthe character at the specifiedindex. 2 intcompareTo(Objecto) ComparesthisStringto anotherObject. 3 intcompareTo(StringanotherString) Comparestwostringslexicographically. 4 intcompareToIgnoreCase(Stringstr) Comparestwostringslexicographically,ignoringcase differences. 5 Stringconcat(Stringstr) Concatenatesthe specifiedstringtothe endof thisstring. 6 booleanendsWith(Stringsuffix) Testsif thisstringendswiththe specifiedsuffix. 7 booleanequals(ObjectanObject) Comparesthisstringto the specifiedobject. 8 booleanequalsIgnoreCase(StringanotherString) ComparesthisStringto anotherString,ignoringcase considerations. 9 byte getBytes() EncodesthisStringintoa sequence of bytesusingthe platform'sdefaultcharset,storingthe resultintoanewbyte array. 10 byte[] getBytes(StringcharsetName EncodesthisStringintoa sequence of bytesusingthe namedcharset,storingthe resultintoanew byte array. 11 voidgetChars(intsrcBegin,intsrcEnd,char[] dst,intdstBegin) Copiescharactersfromthisstringintothe destinationcharacterarray. 12 inthashCode() Returnsa hash code for thisstring. 13 intindexOf(intch) Returnsthe index withinthisstringof the firstoccurrence of the specifiedcharacter. 14 intindexOf(intch,intfromIndex) Returnsthe index withinthisstringof the firstoccurrence of the specifiedcharacter,startingthe searchatthe specifiedindex. 15 intindexOf(Stringstr) Returnsthe index withinthisstringof the firstoccurrence of the specifiedsubstring. 16 intindexOf(Stringstr,intfromIndex) Returnsthe index withinthisstringof the firstoccurrence of the specifiedsubstring,startingatthe specifiedindex.
  • 13. Page 13 of 19 17 Stringintern() Returnsa canonical representationforthe stringobject. 18 intlastIndexOf(intch) Returnsthe index withinthisstringof the lastoccurrence of the specifiedcharacter. 19 intlastIndexOf(intch,intfromIndex) Returnsthe index withinthisstringof the lastoccurrence of the specifiedcharacter,searchingbackwardstartingat the specifiedindex. 20 intlastIndexOf(Stringstr) Returnsthe index withinthisstringof the rightmostoccurrence of the specifiedsubstring. 21 intlastIndexOf(Stringstr,intfromIndex) Returnsthe index withinthisstringof the lastoccurrence of the specifiedsubstring,searchingbackwardstartingat the specifiedindex. 22 intlength() Returnsthe lengthof thisstring. 23 booleanmatches(Stringregex) Tellswhetherornotthisstringmatchesthe givenregularexpression. 24 booleanregionMatches(booleanignoreCase,inttoffset,Stringother,intooffset,intlen) Testsif two stringregionsare equal. 25 booleanregionMatches(inttoffset,Stringother,intooffset,intlen) Testsif two stringregionsare equal. 26 Stringreplace(charoldChar,charnewChar) Returnsa newstringresultingfromreplacingall occurrencesof oldCharinthisstringwithnewChar. 27 StringreplaceAll(Stringregex,Stringreplacement Replaceseachsubstringof thisstringthatmatchesthe givenregularexpressionwiththe givenreplacement. 28 StringreplaceFirst(Stringregex,Stringreplacement) Replacesthe firstsubstringof thisstringthatmatchesthe givenregularexpressionwiththe givenreplacement. 29 String[] split(Stringregex) Splitsthisstringaroundmatchesof the givenregularexpression. 30 String[] split(Stringregex, intlimit) Splitsthisstringaroundmatchesof the givenregularexpression. 31 booleanstartsWith(Stringprefix) Testsif thisstringstarts withthe specifiedprefix. 32 booleanstartsWith(Stringprefix,inttoffset) Testsif thisstringstarts withthe specifiedprefixbeginningaspecifiedindex. 33 CharSequence subSequence(intbeginIndex,intendIndex) Returnsa newcharacter sequence thatisa subsequence of thissequence. 34 Stringsubstring(intbeginIndex) Returnsa newstringthat isa substringof thisstring. 35 Stringsubstring(intbeginIndex,intendIndex) Returnsa newstringthat isa substringof thisstring. 36 char[] toCharArray() Convertsthisstringtoa newcharacterarray. 37 StringtoLowerCase() Convertsall of the characters inthisStringto lowercase usingthe rulesof the defaultlocale. 38 StringtoLowerCase(Locale locale) Convertsall of the characters inthisStringto lowercase usingthe rulesof the givenLocale. 39 StringtoUpperCase() Convertsall of the characters inthisStringto uppercase usingthe rulesof the defaultlocale. 40 StringtoUpperCase(Localelocale) Convertsall of the characters inthis Stringto uppercase usingthe rulesof the givenLocale. 41 Stringtrim() Returnsa copyof the string,withleadingandtrailingwhitespace omitted.
  • 14. Page 14 of 19 toString() Method toString() method is a special method that can be defined in any class. This method should return a String argument. When an object is used in a String concatenation operation or when specified in print statement, this method gets invoked automatically. toString() Method–Example class Circle { double x,y,r; public Circle(double centreX, double centreY, double radius ) { x = centreX ; y = centreY; r = radius; } public String toString() { String s = “I am a Circle with centre [“ + x + “,” + y + “] and radius [“+ r + “]”; return s; } } class CircleTest { Circle c = new Circle(10,20, 30); System.out.println( c ); // I am a circle with centre [10.0,20.0] and radius [30.0] } StringBufferClass Unlike the String class, StringBuffer class is mutable (changeable).Use StringBufferClass class in operations where the string has to be modified.
  • 15. Page 15 of 19 StringBuffer class – Constructors public StringBuffer() Constructs a StringBuffer with an empty string. public StringBuffer(String str) Constructs a StringBuffer with initial value of str. StringBuffer class – Some operations public int length() Returns the length of the buffer public void setCharAt(int index, char ch) Replaces the character at the specified position s1.setLength(int n) Truncates or extends the buffer. If(n<s1.length(), s1 is truncated; else zeros are added to s1. public StringBuffer append(String str) Appends the string to this string buffer. public StringBuffer append(int i) Append of other data items (float, char, etc.) is supported. Appends the string representation of the int argument to this string buffer. Java StringBuffer Examples StringBuffer is a mutable sequence of characters. It is like a String but the contents of the StringBuffer can be modified after creation. StringBuffer Capacity Every StringBuffer object has a capacity associated with it. The capacity of the StringBuffer is the number of characters it can hold. It increases automatically as more contents added to it. StringBuffer’s current capacity can be obtained using following method. int capacity() This method returns the current capacity of the StringBuffer object. For example, StringBuffer stringBuffer = new StringBuffer(“Hello World”); System.out.println(stringBuffer.capacity());
  • 16. Page 16 of 19 This will print 27 (11 + 16) on console when executed. The actual number of characters in StringBuffer can be obtained by following method. int length() Returns the actual number of characters contained in the StringBuffer object. For example, StringBuffer stringBuffer = new StringBuffer(“Hello World”); System.out.println(stringBuffer.length()); System.out.println(stringBuffer.capacity()); This will print, 11 27 on console when run. Specifying initial capacity of StringBuffer Initial capacity of the StringBuffer object can be specified using following method. void ensureCapacity(int initialCapacity) Ensures that the StringBuffer’s initial capacity would be grater than or equal to the specified initial capacity. The new capacity of the StringBuffer is the maximum of, 1) The initialCapacity argument passed and 2) ( Old capacity * 2 ) + 2 StringBuffer Constructors StringBuffer object can be created using following StringBuffer constructors. 1) StringBuffer() Creates empty StringBuffer object having initial capacity of 16. For example, StringBuffer stringBuffer = new StringBuffer(); Here, capacity of stringBuffer object would be 16.
  • 17. Page 17 of 19 2) StringBuffer(int capacity) Creates empty StringBuffer object having initial capacity specified. For example, StringBuffer stringBuffer = new StringBuffer(50); Here, capacity of stringBuffer object would be 50. This constructor may throw NegativeArraySizeException if the passed argument is less than 0. 3) StringBuffer(String content) Creates new StringBuffer object having contents same as the argument string object. The initial capacity of the newly created StringBuffer object will be the length of the argument string object + 16. For example, String str = “Hello”; StringBuffer stringBuffer = new StringBuffer(str); Here, capacity of stringBuffer object would be 5 + 16 = 21. String concatenation and StringBuffer In Java, String concatenation operator (+) is internally implemented using StringBuffer. For Example, String str = “Hello” + “World”; Would be executed as, String str = new StringBuffer().append(“Hello”).append(“World”).toString(); First an empty StringBuffer will be created and then operands of the + operator would be appended using append method of the StringBuffer. Finally toString() method of the StringBuffer would be called to convert it to string object and the same will be returned. String concatenation using this approach is very expensive in nature, because it involves creation of temporary StringBuffer object. Then that temporary object’s append method gets called and the resulting StringBuffer would be converted back to String using toString() method. When to use String and when StringBuffer? If there is a need to change the contents frequently, StringBuffer should be used instead of String because StringBuffer concatenation is significantly faster than String concatenation.
  • 18. Page 18 of 19 Inserting a String in Middle of Existing StringBuffer StringBuffer str = new StringBuffer(“Object Language”); String aString = new String(str.toString()); Int pos = aString.indexOf(“ Language”); str.insert(pos, “ Oriented “); What will output of at this point? System.out.println(“Modified String:”+str); What will be string after executing (modifying character)? str.setChar(6,’-’); For more example on StringBuffer visit: http://www.java-examples.com/java-stringbuffer-examples StringTokenizer  Breaks string into parts, using delimiters.  The sequence of broken parts are the tokens of the string.  More than one delimiter can be specified.  The tokens can be extracted with or without the delimiters. StringTokenizer – Functionality  Consider the following String CREATE_USER:1234567;John;Smith  Separate the tokens(Here Delimiters are: “:;”) CREATE_USER 1234567 John Smith StringTokenizer – Constructors public StringTokenizer(String str, String delim, boolean returnTokens) Creates a SringTokenizer with the specified delimiter. If returnTokens is true the delimiters are also returned. public StringTokenizer(String str, String delim) Delimiters are not returned public StringTokenizer(String str) Delimiters are (“ tnrf”) public boolen hasMoreTokens() Returns true if more tokens are found.
  • 19. Page 19 of 19 public String nextToken() Returns the next token of the String. public String nextToken(String delim) Switches the delimiter set to characters in delim and returns the next token. public int countTokens() Returns the count of remaining tokens. StringTokenizer – example import java.util.StringTokenizer; class TokenizerExample { public static void main(string[] args) { String str = “CREATE_USER:123456;John;Smith”; StringTokenizer tokens = new StringTokenizer(str, “:;”); while ( tokens.hasMoreTokens() ) System.out.println(tokens.nextToken()); } }  Output of the program CREATE_USER 123456 John Smith