String
String
By
Dr. G Prabhakar Raju
Asst. Professor, AU
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
Example:
int age = 9;
String s = "He is " + age + " years old.";
System.out.println(s);
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.
CDEFG
BCD
concat( ): used to concatenate two strings.
String concat(String str)
• 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( )