You are on page 1of 50

BITS Pilani

BITS Pilani
Hyderabad Campus

Dr.Aruna Malapati Asst Professor Department of CSIS

BITS Pilani
Hyderabad Campus

OBJECT ORIENTED PROGRAMMING Text handling in java

Todays Agenda
Characters Strings using
String Class String Buffer Class

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Handling text in Java


The Java platform contains three classes that you can use when working with character data: Character -- A class whose instances can hold a single character value. This class also defines handy methods that can manipulate or inspect single-character data. String -- A class for working with immutable (unchanging) data composed of multiple characters. StringBuffer -- A class for storing and manipulating mutable data composed of multiple characters.
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

Characters
An object of Character type contains a single character value. You use a Character object instead of a primitive char variable when an object is required -- for example, when passing a character value into a method that changes the value or when placing a character value into a data structure, such as a vector, that requires objects. Example : CharacterDemo.java

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Why two string classes?


The Java platform provides two classes, String and StringBuffer, that store and manipulate strings -character data consisting of more than one character. The String class provides for strings whose value will not change. The StringBuffer class provides for strings that will be modified; you use string buffers when you know that the value of the character data will change. You typically use string buffers for constructing character data dynamically.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Strings
java.lang package, which does not require an import statement. A Java String is read-only and once created the contents cannot be modified. String class provides many operations for manipulating strings.
Constructors Utility Comparisons Conversions

An object of the String class represents a string of characters.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Declaring and Allocating Strings


The String class has seven different constructors. The simplest method to create a String object is to enclose the string literal in quotes and assign the value to a String object. Creation of a String through assignment does not require the use of the new operator, for example String str = "abc"; String language = "Java";

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Declaring and Allocating Strings


Alternatively, String objects can be created through constructors. The following constructors are supported: public String() Constructs a new String with the value "" containing no characters. The value is not null. example String s1 = new String();

public String( String value ) Constructs a new String that contains the same sequence of characters as the specified String argument. Example String s2 = new String( "abc" );
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

Declaring and Allocating Strings


public String( char[] value ) Constructs a new String containing the same sequence of characters contained in the character array argument. char data[] = { 'a', 'b', 'c' }; String s4 = new String( data );

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

String Constructors

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Immutability
Characters in Strings can not be changed after the Strings are created Once created, a string cannot be changed: none of its methods changes the string. Such objects are called immutable. Immutable objects are convenient because several references can point to the same object safely: there is no danger of changing an object through one reference without the others being aware of the change.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Advantages Of Immutability

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

String Objects
String objects are immutable -- they cannot be changed once they have been created. References to string objects may be changed.
String str1 = new String (I like dogs.); String str2 = new String(I prefer cats.); str1 = str2; //reassign reference

Automatic garbage collection will reclaim unreferenced objects


CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

String Operations in Java


Following are some useful classes that Java provides for String operations. String Class StringBuffer Class StringTokenizer Class

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

The String Methods


Since String is a class, objects that are instances of it have methods. One of those methods is the length() method. this can be depicted by the following figure:

Note: objects in general contain data and methods


the data (in this case) being the literal string Hello one of the methods being the length() method.
to invoke the length() method of a String object, you specify the variable name followed by a dot followed by the method name, e.g., value.length();
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

The String class


Declaring a String: String message = "Welcome to Java!" String message = new String("Welcome to Java!); String s = new String(); String Comparisons String Concatenation Substrings String Length Retrieving Individual Characters in a String

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

String comparison
Equals String s1 = "Welcome"; String s2 = "welcome"; if (s1.equals(s2)) { // s1 and s2 have the same contents } if (s1 = = s2) { // s1 and s2 have the same reference }
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

String comparison
Use s1.compareTo(s2) return 0 if s1 is equal to s2 less than 0 if s1 is lexicographically less than s2 greater than 0 if s1 is lexicographically greater than s2 Example: s1="abc" and s2="abe" s1.compareTo(s2) return -2

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

String Concatenation
String s3 = s1.contact(s2); String s3 = s1 + s2;
String s3 =s1.concat(s2); concatenate s1 and s2 to s3 Alternatively, Use plus sign "+" to concatenate String myString=message+" and " + " HTML";

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Substrings
String is an immutable class; its values cannot be changed individually. String s1 = "Welcome to Java"; String s2 = s1.substring(0,10) + "HTML"; public String substring(int beginIndex, int endIndex) return a substring from beginIndex to endIndex-1 public Stringsubstring(int beginIndex) return a substring from beginIndex to the end of the string

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Example
classCheckString { public static void main(String[]args) { String statement="I like to check out a book now."; Stringst=statement.substring(0,22) +"magazine"+statement.substring(26); System.out.println(st); } }

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Finding String Length


Finding string length using the length()method: message = "Welcome"; message.length() (returns7)

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Retrieving Individual Characters in a String


Do not use message[0] Use message.charAt(index) Index starts from 0

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

String operations summary


int length() char charAt(int index) indexOf( ) & lastIndexOf( ) indexOf(char ch) // first position of 'ch' indexOf(String str) // first position of 'str' lastIndexOf(char ch) // last position of 'ch' lastIndexOf(String str) // last position of 'str' startsWith(String prefix) & endsWith(String suffix ) String Substring (int) & String Substring (int startindex, int lastindex) public String toLowerCase() & public String toUpperCase() public String trim() - Returns a copy of the string, with leading and trailing whitespace omitted. public String replace(char oldChar, char newChar) - Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar. Concatenation (+) returns a string StringMethods.java
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

StringBuffer Class
StringBuffer objects can be altered directly. A String object is always a fixed string. How to create StringBuffer objects?
StringBuffer string1 = Hello How are you;//not allowed StringBuffer string1 = new StringBuffer(Hello How are you);

StringBuffer contains a block of memory called buffer which may or may not contain a string and if it does, the string need not occupy all of the buffer. String buffers are preferred when heavy modification of character strings is involved (appending, inserting, deleting, modifying etc).
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

StringBuffer Constructors
The final class StringBuffer provides three constructors that create and initialize StringBuffer objects and set their initial capacity. StringBuffer(String s)
The contents of the new StringBuffer object are the same as the contents of the String object passed as argument. The initial capacity of the string buffer is set to the length of the argument string, plus room for 16 more characters.

StringBuffer(int length)
The new StringBuffer object has no content. The initial capacity of the string buffer is set to the value of the argument length, which cannot be less than 0.

StringBuffer()
This constructor also creates a new StringBuffer object with no content. The initial capacity of the string buffer is set for 16 characters.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

int length() int capacity()


int length() returns the current length of string buffer int capacity() returns the allocated capacity Example :

StringBuffer strbuf = new StringBuffer(); System.out.println(strbuf.length()); System.out.println(strbuf.capacity());

No size Mentioned 0 16

StringBuffer strbuf1 = new StringBuffer("Object"); System.out.println(strbuf1.length()); 6 System.out.println(strbuf1.capacity()); 22

No size Mentioned

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

void ensureCapacity(int capacity)


Useful if you know in advance the size of buffer Used to preallocate room for a certain number of characters after StringBuffer object has been created. <<capacity>> specifies the size of buffer StringBuffer strbuf = new StringBuffer(); System.out.println(strbuf.length()); System.out.println(strbuf.capacity()); strbuf.ensureCapacity(10); System.out.println(strbuf.capacity());

0 16 16
6 22 50
BITS Pilani, Hyderabad Campus

StringBuffer strbuf1 = new StringBuffer("Object"); System.out.println(strbuf1.length()); System.out.println(strbuf1.capacity()); strbuf1.ensureCapacity(50); System.out.println(strbuf1.capacity());


CS/IS F213 First Semester 2012-13

StringBuffer s1 = new StringBuffer("Java"); System.out.println(s1.length()); System.out.println(s1.capacity()); s1.ensureCapacity(50); System.out.println(s1.length()); System.out.println(s1.capacity());

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

char charAt(int where) void setCharAt(int where, char ch)


charAt() method is same as String class i.e returns a char from index where setCharAt() method sets the character ch at the where index. <<where>> should be >= 0 and should not specify a position beyond the end of the buffer

StringBuffer strbuf = new StringBuffer("Object oriented"); System.out.println(strbuf); strbuf.setCharAt(10,'X'); System.out.println(strbuf);

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Inserting charcters
Insert() method can be used for inserting characters Insert() method is also overloaded 1. StringBuffer insert(int index , String str); 2. StringBuffer insert(int index , char ch); 3. StringBuffer insert(int index, Object obj); << index >> must be within permitted range and should be positive

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

StringBuffer strbuf = new StringBuffer("Java"); strbuf.insert(3," "); System.out.println(strbuf);

Jav a

StringBuffer strbuf = new StringBuffer("Java"); strbuf.insert(4," "); System.out.println(strbuf); System.out.println(strbuf.length());

Java 5

StringBuffer strbuf = new StringBuffer("Java"); strbuf.insert(2, Programming "); JaProgrammingva System.out.println(strbuf); 15 System.out.println(strbuf.length()); StringBuffer strbuf = new StringBuffer("Java"); strbuf.insert(2,new circle(10)); System.out.println(strbuf); System.out.println(strbuf.length());
CS/IS F213 First Semester 2012-13

?
BITS Pilani, Hyderabad Campus

class Test { public static void main(String args[]) { StringBuffer strbuf = new StringBuffer("Object");

strbuf.append(" oriented");
System.out.println(strbuf); strbuf.append(6.1); System.out.println(strbuf); } Object oriented

Object oriented6.1

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Appending New Contents into a String Buffer


StringBuffer strBuf= new StringBuffer(); strBuf.append("Welcome"); strBuf.append(' '); strBuf.append("to"); strBuf.append(' '); strBuf.append("Java"); strBuf.insert(11,"HTML and "); After position 10, or at 11, insert the literal string "HTML and "

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

StringBuffer Methods

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Methods in StringBuffer

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

StringTokenizer Class java.util.StringTokenizer;


Used for Parsing a Formatted Input String Parsing : Division of text into set of discrete parts known as tokens Token convey a semantic meaning Individual tokens are separated by Delimiters Delimiters can be specified by a delimiter String and each character in delimiter String is treated as a separate delimiter A provision is provided by which you can treat individual delimiters as tokens also Space , Tab, newline and carriage return << Default

Set of Delimiters>>

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Example
String str = "BITS CS F213,Object Oriented Programming,Lecture Session 13;F-103,LTC ; If Only Comma (,) is taken as delimiter: NO OF TOKENS = 4 Tokens : {BITS CS F213} {Object Oriented Programming} {Lecture Session 13; F-103} {LTC} If Only Semicolon (;) is taken as delimiter NO OF TOKENS = 2 Tokens : ?

If Both Comma(,) and Semicolon (;) are taken as delimiters: NO OF TOKENS = 5 Tokens : ? Delimiters themselves are not taken as

Tokens

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

StringTokennizer Constructors
1. 2. 3. 1. 2. 3. 4. StringTokennizer(String str) << str> String to be tokennized. No delimiter is specified so default set delimiters will beassumed. Delimiters will not be considered as tokens StringTokennizer(String str, String delimiters) << delimiters>> specify a delimiter String. Single or multiple characters can be specified as delimiters. If the delimiter String is :,; then colon, comma and semicolon are used as delimiters Individual character in the the delimiter String is separately treated as a delimiters. By Default Delimiters will not be considered as tokens

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

StringTokennizer Constructors cont


StringTokennizer(String str, String delimiters, boolean delimAsToken) 1. First Two parameters are same as previous constructor. Third parameter delimAsToken indicates whether delimiters are to be taken as tokens or not. 2. Delimiters will be considered as tokens if delimAsToken is true otherwise will be ignored if false

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

StringTokenizer Methods
1. Int countTokens()
Counts the number of tokens in StringTokennizer based upon delimiters

2. boolean hasMoreTokens() / boolean hasMoreElements()


Helpful in parsing a String. Returns true if there are one or more tokens left otherwise false.

3. String nextToken()
Returns the next token in String form Used in conjunction with hasMoreTokens() method

4. Object nextElement()
Same as nextToken() but returns next Token in Object Form not in String Form
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

String str = "BITS CS F213,Object Oriented Programming,Lecture Session 13;F-103,LTC ; StringTokenizer strT1 = new StringTokenizer(str); // No Delimiters Specified System.out.println("Number Of Tokens :"+strT1.countTokens()); System.out.println("Individual Tokens"); while(strT1.hasMoreTokens()) System.out.println(strT1.nextToken());

Number Of Tokens :3 Individual Tokens BITS CS F213,Object Oriented Programming,Lecture Session 13;F-103,LTC
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

String str = "BITS CS F213,Object Oriented Programming,Lecture Session 13;F-103,LTC ; StringTokenizer strT1 = new StringTokenizer(str,;); // Semicolon (;) is Specified as delimiter System.out.println("Number Of Tokens :"+strT1.countTokens()); System.out.println("Individual Tokens"); while(strT1.hasMoreTokens()) System.out.println(strT1.nextToken());

Number Of Tokens :2 Individual Tokens BITS CS F213,Object Oriented Programming,Lecture Session 13 F-103,LTC
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

String str = "BITS CS F213,Object Oriented Programming,Lecture Session 13;F-103,LTC ; StringTokenizer strT1 = new StringTokenizer(str,,); // Comma (,) is Specified as delimiter System.out.println("Number Of Tokens :"+strT1.countTokens()); System.out.println("Individual Tokens"); while(strT1.hasMoreTokens()) System.out.println(strT1.nextToken());

Number Of Tokens :4 Individual Tokens BITS CS F213 Object Oriented Programming Lecture Session 13;F-103 LTC
CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus

String str = "BITS CS F213,Object Oriented Programming,Lecture Session 13;F-103,LTC ; StringTokenizer strT1 = new StringTokenizer(str,;,); // Both Semicolon (;) and Comma (,) are Specified as delimiters System.out.println("Number Of Tokens :"+strT1.countTokens()); System.out.println("Individual Tokens"); while(strT1.hasMoreTokens()) System.out.println(strT1.nextToken()); Number Of Tokens :5 Individual Tokens BITS CS F213 Object Oriented Programming Lecture Session 13 F-103 LTC

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

String str = "BITS CS F213,Object Oriented Programming,Lecture Session 13;F-103,LTC;BPHC,2012-13 ; StringTokenizer strT1 = new StringTokenizer(str,;,, true); // Both Semicolon (;) and Comma (,) are Specified as delimiters // Delimiters then selves are tokens now System.out.println("Number Of Tokens :"+strT1.countTokens()); System.out.println("Individual Tokens"); while(strT1.hasMoreTokens()) System.out.println(strT1.nextToken());

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Number Of Tokens :13 Individual Tokens BITS CS F213 , Object Oriented Programming , Lecture Session 13 ; F-103 , LTC ; BPHC , 2012-13

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

Example
//TestStringTokenizer.java: DemonstrateStringTokenizer import java.util.StringTokenizer; public classTestStringTokenizer { // Main method public static void main(String[]args) { // Create a string and stringtokenizer String s = "I am learning Java. Show me how to useStringTokenizer."; StringTokenizer st= newStringTokenizer(s); // Retrieve and display tokens System.out.println("The total number of words is " + st.countTokens()); while (st.hasMoreTokens()) System.out.println(st.nextToken()); } CS/IS F213 First Semester 2012-13 BITS Pilani, Hyderabad Campus }

Summary
In java strings are immutable objects. Use String buffer class to make the string mutable. The string buffer can be used when we want to modify stings. The string tokeneizer class allows us to break the given strings into tokens.

CS/IS F213 First Semester 2012-13

BITS Pilani, Hyderabad Campus

You might also like