Basic String Class Functions in Java
Basic String Class Functions in Java
String class is defined in java.lang package. String objects are immutable, means once created
their value can not be changed. Although there are several String functions defined in String
class which can modify the value of a String object and the modified value is referred by another
String object. These String functions are called String manipulating functions.
1. int length () : A function of string class returns the number of characters in the invoking string
object, including space.
e.g String str=”this is java’; The output of the statement System.out.println(str); would be 12
2. String toString () function returns string version of any non string value. This function defined in
Object class which is defined in java.lang package and this class is super class of all java classes.
This function has several overloaded versions.
3. String valueOf () function also returns string version of primitive values. This has also several
overloaded versions.
4. char charAt (int index)- This function extract a single character from a string and returns it. This
function takes the location or index of the character in the string.
e.g String str=”This is java”;
char ch=str.charAt(2); will return the character ‘i’. Index always starts from 0.
5. boolean equals () - A function of string class takes one string as argument and the function is
invoked on another string object. This function compares the argument and the invoking string for
equality. If both are same it will return true otherwise false. This method is case sensitive.
“JAVA”.equals(“java”); will return false.
6. boolean equalsIgnoreCase () - This function has all the features same as equals () String
function excepting it is not case sensitive.
6. boolean startsWith ()- This function takes a string as argument and is invoked on another string.
If the invoking string starts with the argument string, it returns true otherwise false.
e.g Burdwan.startsWith(“Bu”); will return true
7. boolean endsWith () function also works like startsWith () method excepting it checks whether
the invoking string ends with the argument string.
e.g Burdwan.endsWith(“Bu”); will return false and Burdwan.startsWith(“an”); will return true
equals () function compares values of two string object whereas == operator or equality operator
checks whether both the objects refers to the same instance.
e.g String str1=”Hi”; and String str2=”Hi”;
In this case str1.equals(str2) will return true but str1==str2 will return false.
Again String str1=”Hi”; and String str2=str1;
Here both str1.equals(str2) and str1==str2 will return true as both str1 and str2 refers the same
location.
1
Basic String Class Functions in Java
charAt()
charAt() function returns the character located at the specified index.
String str = "studytonight";
System.out.println(str.charAt(2));
Output: u
NOTE: Index of a String starts from 0, hence str.charAt(2) means third character of the String str.
equalsIgnoreCase()
equalsIgnoreCase() determines the equality of two Strings, ignoring thier case (upper or lower case
doesn't matters with this fuction ).
String str = "java";
System.out.println(str.equalsIgnoreCase("JAVA"));
Output: true
indexOf()
indexOf() function returns the index of first occurrence of a substring or a character. indexOf()method
has four forms:
int indexOf(String str): It returns the index within this string of the first occurrence of the
specified substring.
int indexOf(int ch, int fromIndex): It returns the index within this string of the first occurrence of
the specified character, starting the search at the specified index.
int indexOf(int ch): It returns the index within this string of the first occurrence of the specified
character.
int indexOf(String str, int fromIndex): It returns the index within this string of the first
occurrence of the specified substring, starting at the specified index.
Example:
public class StudyTonight {
public static void main(String[] args) {
String str="StudyTonight";
System.out.println(str.indexOf('u')); //3rd form
System.out.println(str.indexOf('t', 3)); //2nd form
String subString="Ton";
System.out.println(str.indexOf(subString)); //1st form
System.out.println(str.indexOf(subString,7)); //4th form
}
}
Output:
2
11
5
-1
NOTE: -1 indicates that the substring/Character is not found in the given String.
length()
length() function returns the number of characters in a String.
String str = "Count me";
System.out.println(str.length());
Output : 8
replace()
replace() method replaces occurrences of character with a specified new character.
String str = "Change me";
System.out.println(str.replace('m','M'));
Output: Change Me
2
Basic String Class Functions in Java
substring()
substring() method returns a part of the string. substring() method has two forms,
public String substring(int begin);
toLowerCase()
toLowerCase() method returns string with all uppercase characters converted to lowercase.
String str = "ABCDEF";
System.out.println(str.toLowerCase());
Output: abcdef
toUpperCase()
This method returns string with all lowercase character changed to uppercase.
String str = "abcdef";
System.out.println(str.toUpperCase());
Output: ABCDEF
valueOf()
Overloaded version of valueOf() method is present in String class for all primitive data types and for
type Object.
NOTE: valueOf() function is used to convert primitive data types into Strings.
public class Example{
public static void main(String args[]){
int num = 35;
String s1 = String.valueOf(num); //converting int to String
System.out.println(s1+"IAmAString");
}
}
Output: 35IAmAString
But for objects, valueOf() method calls toString() function.
3
Basic String Class Functions in Java
toString()
toString() method returns the string representation of the object used to invoke this
method. toString() is used to represent any Java Object into a meaningful string representation. It is
declared in the Object class, hence can be overrided by any java class. (Object class is super class of
all java classes.)
public class Car {
public static void main(String args[])
{
Car c = new Car();
System.out.println(c);
}
public String toString()
{
return "This is my car object";
}
}
Output: This is my car object
Whenever we will try to print any object of class Car, its toString() function will be called. toString()
can also be used with normal string objects.
String str = "Hello World";
System.out.println(str.toString());
Output: Hello World
NOTE: If we don't override the toString() method and directly print the object, then it would print the
object id.
Example:
public class Car {
public static void main(String args[])
{
Car c = new Car();
System.out.println(c);
}
}
Output: studytonight.Car@15db9742 (here studytonight is a user-defined package).
trim()
This method returns a string from which any leading and trailing whitespaces has been removed.
String str = " hello ";
System.out.println(str.trim());
Output: hello
NOTE: If the whitespaces are between the string, for example: String s1 = "study
tonight"; then System.out.println(s1.trim()); will output "study tonight".
trim() method removes only the leading and trailing whitespaces.
4
Basic String Class Functions in Java
class strings
{
void str()
{
String name1="Aman";
String name2="Tania";
String name3="Aman";
String name4="aman";
}
}
5
Basic String Class Functions in Java
Output:
length of Aman is = 4
length of Tania is = 5
character at 3 in Aman is = n
character at 4 in Tania is = a
comparison of the 2 names is -19
comparison of the 2 names is 19
comparison of the 2 names is 0
comparison of the 2 names is 32
equality comparison of the 2 names is false
equality comparison of the 2 names is true
concatenation of the 2 names is AmanTania
concatenation of the 2 names is AmanTania
First occurence of 'a' in Taniais at index 1
Last occurence of 'a' in Tania is at index 4
First occurence of 'x' in Tania is at index -1
Substring 1 onwards in Tania is = ania
Note:
if
System.out.println("character at 5 in "+ name1 + " is = " + name1.charAt(5));
is also added to the above program, it ll throw an error:
This is so because charAt(5) points to 5th character which is beyond the length of the string = 4