String Handling and Library Class Notes
String Handling and Library Class Notes
STRINGS(ISC)
A string is a sequence of one or more characters enclosed in double quotes. In Java, strings are class objects instantiated
using two classes defined in java.lang:
1. String
2. StringBuffer
Initialization:
1. Using a String literal:
String s = new String(“May”) ;
String s = “May” ;
String x = new String(s) ; // creates String x from String s
M e th o d F o rm a t D e s c rip tio n + E x a m p le
System.out.println a.length ;
((
(
)
()
System.out.println "Java".length ;
)
)
)(
))
System.out.println "Computer".charAt 4 ;
(
)
)
(51)
M e th o d F o rm a t D e s c r ip t io n + E x a m p le
re tu rn s th e p o s itio n fo r th e la s t o c c u re n ce o f th e s p e c ifie d
c h a ra c te r.
in t la s tI n d e x O f in t c h
)
S trin g y = " M is s is s ip p i" ;
S y s te m .o u t.p rin tln y .la s tI n d e x O f 's ' ;
)
)
re tu rn s th e s u b s trin g th a t b e g in s fro m th e n th in d e x .
S t r in g s u b s t r in g in t n S trin g x = " H a lfy e a rly " ;
)
S y s te m .o u t.p rin tln x .s u b s trin g 4 ;
(
)
)
re tu rn s th e s u b s trin g th a t b e g in s fro m th e n th c h a ra c te r u p to
S t r in g s u b s t r in g in t n , in t m m -1 th c h a ra c te r.
(
)
S y s te m .o u t.p rin tln " H e llo " .s u b strin g 0 ,4 ;
)
)
re tu rn s t r u e , if tw o s trin g o b je c ts a re e x a c tly s a m e , in c lu d -
b o o le a n e q u a ls S trin g s in g th e ir c a s e .
(
)
)
s a m e a s a b o v e , b u t d iffe rin g o n ly in th e ir c a s e .
b o o le a n e q u a ls I g n o re C a s e S trin g s S trin g a = " R u n " ; S trin g b = " ru n " ;
(
)
)
c o m p a re s tw o s trin g s o f s a m e c a s e in d ic tio n a ry o rd e r.
s 1 .c o m p a re T o s 2 re tu rn s < 0 s 1 <s 2 ,> 0
)
in t c o m p a re T o S trin g o b j s 1 >s 2 ,0 s1=s2 .
(
)
S y s te m .o u t.p rin tln " lo c k " .c o m p a re T o " lo o k " ; // - 1 2
((
))
)
S y s te m .o u t.p rin tln " lo c " .c o m p a re T o " lo c k " ; // - 1
)
s a m e a s a b o v e , b u t ig n o re s th e c a s e o f th e le tte rs .
in t c o m p a re T o I g n o re C a s e S trin g
(
)
)
re tu rn s a n e w s trin g a fte r re p la c in g a ll o c c u re n c e s o f th e
S trin g re p la c e c h a r o ld ,ch a r n e w o ld c h a ra c te r w ith th e n e w c h a ra c te r in a g iv e n s trin g .
(
)
re tu rn s a n e w s trin g a fte r re p la c in g a ll o c c u re n c e s o f a n o ld
s u b s trin g w ith th e n e w s u b strin g o f th e in v o k e d s trin g .
S trin g re p la c e S trin g o ld ,S trin g n e w
(
)
)
re tu rn s a n e w a fte r re m o v in g a n y le a d in g o r tra ilin g s p a c e s
S trin g trim fro m th e in v o k e d s trin g .
(
)
)
)
(
)
)
(
)
)
c h a r c h a [ ] = s .to C h a rA rra y ;
(
)
)
)
re tu rn s a s trin g re p re s e n ta tio n o f th e a rg u m e n t w h ic h m a y
b e o f a n y p rim itiv e o r re fe re n c e d a ta ty p e .
in t iv = 4 ; d o u b le fv = 0 .5 ;
S t r in g v a lu e O f a rg
(
))
S trin g y = S trin g .v a lu e O f fv ;
S y s te m .o u t.p rin tln x + y ; // " 4 0 . 5 "
(
(52)
Using ‘ + ’ operator:
For e.g.,
int m = 5 , n = 7 ;
System.out.println(m + n + “ = m+n”) ;
System.out.println(“m + n = “ + m + n) ;
System.out.println(“m + n = “ +(m + n)) ;
String x = “Con” ; String y = “cate” ;
System.out.println(x.concat(y) + “nation”) ; // "Concatenation"
Initialization:
Syntax: String array-name[ ] = { “String1”, “String2”,…,”StringN” };
Accession:
Each individual string can be accessed as:
System.out.println(mth[1]) ; // “Feb”
System.out.println(arr[2].length( )) ; // 5
S tr in g S trin g B u ffe r
Creation (Syntax):
1) StringBuffer sb = new StringBuffer( ) ; // creates an empty string with default buffer size of 16 characters
2) StringBuffer sb = new StringBuffer(25) ; // creates an empty string with buffer size of 25 characters
Initialization:
1) StringBuffer sb = new StringBuffer(“June”) ; // creates a string “June” with buffer capacity of 20 characters
length of string + default buffer size)
2) StringBuffer x = sb ;
3) StringBuffer sb = new StringBuffer(sc.next( )) ;
2. void setLength(int n) – sets the length of the string within a buffer to store n characters. For e.g.
(54)
StringBuffer sb = new StringBuffer(“Nightmare”) ;
sb.setLength(5) ;
System.out.println(“String = “+sb) ; // “Night”
3. void setCharAt(int i, char c) – replaces the character at the specified index with character c of a given buffered
string. For e.g.
StringBuffer sb = new StringBuffer(“match maker”) ;
sb.setCharAt(0, ‘c’) ;
sb.setCharAt(6, ‘t’) ;
System.out.println(“String = “+sb) ; // “catch taker”
4 StringBuffer reverse( ) – reverses the characters within a given buffered string. For e.g.
StringBuffer sb = new StringBuffer(“not war”) ;
sb.reverse( ) ;
System.out.println(“String = “+sb) ; // “raw ton”
5. StringBuffer append(String s) – adds a specified string at the end of the given buffered string. For e.g.
StringBuffer sb = new StringBuffer(“Nation”) ;
StringBuffer x = sb.append(“al”) ;
System.out.println(“String = “+x) ; // “National”
7. StringBuffer delete(int n, int m) – deletes a sequence of characters starting from the nth chr. upto (m–1)th
character of a given buffered string. For e.g.
StringBuffer sb = new StringBuffer(“Today”) ;
System.out.println(sb.delete(0, 2)) ; // “day”
8. StringBuffer deleteCharAt(int i) – deletes a character at the specified index of a given buffered string. For e.g.
StringBuffer sb = new StringBuffer(“sunday”) ;
System.out.println(sb.deleteCharAt(0)) ; // “unday”
9. StringBuffer replace(int n, int m, String s) – replaces a sequence of characters starting from the nth chr. upto
(m–1)th character of a given buffered string, with the specified string. For e.g.
StringBuffer sb = new StringBuffer(“This is a test”);
sb.replace(5,7,”was”) ;
System.out.println(sb) ; // “This was a test”
Method Description
countTokens( ) Returns the number of tokens to be parsed, using the current set of delimiters.
The split( ) Method: It breaks or splits the invoked string into multiple string objects based on the given delimiter
pattern and returns the strings in the form of an array.
Syntax: String [ ] split (String expr)
Here, expr specifies a pattern of one or more delimiters like comma(“,“), semicolon(“;“), colon(“:“), or a period (“.”).
E.g.2:
String str = "This is sentence. This is a question, right ? Yes! It is. " ;
String delims = "[ .,?!] + " ;
String temp[ ] = str.split(delims) ;
for(int i = 0 ; i < temp.length ; i++) System.out.println(temp[i]) ;
(57)
C ITY MONTESSORI SCHOOL
SECTOR-D, LDA COLONY, KANPUR ROAD, LUCKNOW (INDIA)
The package statement in a program groups all the following classes into a user defined package. For e.g.
package MyPackage ;
The import statement makes a class or classes of a package available to the current program. For e.g.
import java. util . Scanner ;
import java . io. * ;
Streams: Java performs I/O through streams. Commonly used I/O streams present in java.io are:
i) System.in – object of InputStream for input purpose.
ii) System.out – object of OutputStream for printing purpose.
iii) System.err – object of OutputStream for error messages.
2) java.lang package: It is the default package which gets included at the start of any Java program. It stores the
basic functions of the language. Commonly used classes in java.lang are:
a) Wrapper Classes:
i) They are a collection of classes that provide a mechanism to "wrap" primitive types into an object . Java has
a wrapper class for each of the eight primitive data types:
Primitive type Wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
The wrapper object can be created by instantiating the wrapper class with the new operator. For e.g.
Character c = new Character('T') ; // creates a Character object with intial value 'T'
Integer y = new Integer(33) ; // creates a Integer object with initial value 33
(58)
Common Wrapper methods:
a) Wrapper.valueOf( ): takes a value (or string) as an argument and returns a newly created wrapped object
of the class that invoked the method. For e.g.
Character c = Character.valueOf(‘c’) ; // assigns 'c' to the Character object c
Float f = Float.valueOf(“3.14f”); // assigns 3.14 to the Float object f
b) typeValue( ) - such as intValue( ), doubleValue( ), charValue( ), etc. Each one of them returns a primitive
type equal to value of the wrapper object. For e.g.
int x = 25 ; Integer y = new Integer(42) ;
System.out.println(x + y.intValue( )) ; // 67
System.out.println(y.doubleValue( )) ; // 42.0
c) parseType(String str) - such as parseInt( ), parseDouble( ), parseFloat( ), etc. Each of them returns a
primitive type equivalent of the number contained in the String argument. For e.g.
int x = Integer.parseInt("1234") ; // converts a string integer into an int
d) Wrapper.toString( ) - such as Integer.toString( ), Double.toString( ), etc. Each of them accepts a primitive
type argument and returns its equivalent String representation. For e.g.
String s = Integer.toString (1234) ; // converts an int into a String object "1234"
System.out.println(“d = “ + Double.toString(3.14)) ; // result is “d = 3.14”
ii) The Character class: provides methods to manipulate and process characters.
Method Description
Returns true, if ch is a letter, otherwise it
boolean isLetter(char ch)
returns false.
Returns true, if ch is a digit, otherwise it
boolean isDigit(char ch)
returns false.
Returns true, if ch is a letter or a digit,
boolean isLetterOrDigit(char ch)
otherwise it returns false.
Returns true, if ch is a lowercase letter,
boolean isLowerCase(char ch)
otherwise it returns false.
Returns true, if ch is a uppercase letter,
boolean isUpperCase(char ch)
otherwise it returns false.
Returns true, if ch is whitespace, other wise
boolean isWhitespace(char ch)
it returns false.
char toLowerCase(char ch) Returns lowercase equivalent of ch
char toUpperCase(char ch) Returns uppercase equivalent of ch
class abc {
public static void main( ) {
char ch[ ] = {‘R’, ‘0’, '\t'} ;
System.out.println (Character.isLetter(ch[0]) ;
System.out.println (Character.isDigit(ch[1]) ;
System.out.println (Character.isUpperCase(ch[0]) ;
System.out.println (Character.toLowerCase(ch[0]) ;
System.out.println (Character.isLetterOrDigit(‘?’) ;
System.out.println (Character.isWhitespace(ch[2]) ;
}
}
b) String and StringBuffer classes: used to represent Strings in Java.
3) java.util package: It is a collection of utility classes.
a. Date – To create and manipulate calendar dates in system independent fashion.
b. StringTokenizer – Converts a string of text into tokens or words.
c. Scanner – It is used for text input processing from a keyboard, a file or a String. For e.g.
Scanner sc = new Scanner(System.in) ; // sc is a Scanner class object
d. Random – Implements a random number generator.
(59)