13. String Handling(String Class)
13. String Handling(String Class)
String Handling
Example:
System.out.println("This is a String, too");
Why String Handling?
String handling is required to perform following operations
on some string:
public String ()
public String (String)
public String (char [])
public String (byte [])
public String (char [], int offset, int no_of_chars)
public String (byte [], int offset, int no_of _bytes)
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.
Example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());
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");
Example:
char ch;
ch = "abc".charAt(1);
Methods Cont…
toCharArray(): returns a character array initialized by the
contents of the string.
public char [] toCharArray();
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.
String toLowerCase( )
String toUpperCase( )
Split()
Example:
String str = "have-fun-in-java@blogspot@in";
String [] s = str.split("-", -2);
for(String x: s) System.out.println(x);
Limit parameter can have 3 values:
limit > 0 : If this is the case then the pattern will be applied at
most limit-1 times, the resulting array’s length will not be
more than n, and the resulting array’s last entry will contain
all input beyond the last matched pattern.
limit < 0 : In this case, the pattern will be applied as many times
as possible, and the resulting array can be of any size.
Example:
String joinString1=String.join(“-”, “have",“fun",“in“, “java”);
System.out.println(joinString1);