L7 - String
L7 - String
By
Arvind Kumar
Asst. Professor, LPU
Blank
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.
Blank
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
int length()
Example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());
Blank
Character Extraction
Example:
char ch;
ch = "abc".charAt(1);
Blank
Methods Cont…
• getChars(): used to obtain set of characters from the string.
Output: NEELKAMA
Blank
Methods Cont…
• toCharArray(): returns a character array initialized by the
contents of the string.
char [] toCharArray();
}
System.out.println(c);
Blank
String Comparison
• equals(): used to compare two strings for equality.
Comparison is case-sensitive.
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( )
Blank
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)
Blank
Important
• When the length of StringBuilder becomes larger than the
capacity then memory reallocation is done:
• Example
• String S1 = “ABCDFGB”
• String S2 = “BCJDYZBC”
• Count = 3
Blank
Let’s Do It
• Write an application that prompts the user for three first names
and concatenates them in every possible two-name
combination so that new parents can easily compare them to
find the most pleasing baby name.
• Save the file as BabyNameComparison.java.
Blank
Let’s Do It
• Eg.
silent
listen
Let’s Do It