String
String
String
By
Arvind Kumar
Asst. Professor, LPU
Introduction
• A string is a sequence of characters.
• Example:
System.out.println("This is a String, too");
• Objects of type String are immutable i.e. once a String object is created, its
contents cannot be altered.
Introduction
• In java, four predefined classes are provided that either represent
strings or provide functionality to manipulate them. Those classes
are:
– String
– StringBuffer
– StringBuilder
– StringTokenizer
public String ()
public String (String strObj)
public String (char chars[])
public String (byte asciiChars [])
public String (char chars[ ], int startIndex, int numChars)
public String (byte asciiChars[ ], int startIndex, int
numChars)
Examples
congrats
ongra
congrats
ABCDEFGH
EFGH
Methods of String class
• String Length:
length() returns the length of the string i.e. number of
characters.
int length()
Example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());
Character Extraction
Example:
char ch;
ch = "abc".charAt(1);
Methods Cont…
• getChars(): used to obtain set of characters from the string.
Output: NEELKAMA
Methods Cont…
• toCharArray(): returns a character array initialized by the
contents of the string.
char [] to Char Array();
Note:
• This method is defined in Object class and overridden in String class.
• equals(), in Object class, compares the value of reference not the content.
• Here, startIndex specifies the index at which point the search begins.
• For indexOf( ), the search runs from startIndex to the end of the
string.
• This method creates a new object that contains the invoking string
with the contents of str appended to the end.
Example:
String s1 = "one"; String s2 = s1.concat("two");
• The second form of replace( ) replaces one character sequence with another. It
has this general form:
String toLowerCase( )
String toUpperCase( )
Java String join
• The java string join() method returns a string joined with given
delimiter.
• StringBuilder is non-synchronized.
• StringBuilder(CharSequence seq)
• StringBuilder(int capacity)
• StringBuilder(String str)
Methods
• public StringBuilder append(String s)
The append() method is overloaded like append(char),
append(boolean), append(int), append(float), append(double)
etc.