Strings
Strings
• Example:
System.out.println("This is a String, too");
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
String Concatenation
• Concatenating Strings:
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.
void getChars(int sourceStart, int sourceEnd, char target[ ], int
targetStart)
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.
• 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");
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.