Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
218 views

Basic String Class Functions in Java

The document discusses several key functions of the String class in Java, including length(), charAt(), compareTo(), equals(), concat(), and others. It provides examples of using each function and describes what they return. For instance, it notes that length() returns the number of characters in a string. charAt() returns the character at the specified index. compareTo() compares two strings alphabetically and returns negative, zero, or positive numbers. equals() checks if two strings are equal while ignoring case. concat() concatenates two strings.

Uploaded by

GreatAkbar1
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
218 views

Basic String Class Functions in Java

The document discusses several key functions of the String class in Java, including length(), charAt(), compareTo(), equals(), concat(), and others. It provides examples of using each function and describes what they return. For instance, it notes that length() returns the number of characters in a string. charAt() returns the character at the specified index. compareTo() compares two strings alphabetically and returns negative, zero, or positive numbers. equals() checks if two strings are equal while ignoring case. concat() concatenates two strings.

Uploaded by

GreatAkbar1
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

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

Difference between equals () function and == operator.

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);

public String substring(int begin, int end);


/*
character of begin index is inclusive and character of end index is exclusive.
*/
The first argument represents the starting point of the subtring. If the substring() method is called with
only one argument, the subtring returned, will contain characters from specified starting point to the
end of original string.
But, if the call to substring() method has two arguments, the second argument specify the end point of
substring.
String str = "0123456789";
System.out.println(str.substring(4));
Output: 456789
System.out.println(str.substring(4,7));
Output : 456

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).

toString() with Concatenation


Whenever we concatenate any other primitive data type, or object of other classes with a String
object, toString() function or valueOf() function is called automatically to change the other object or
primitive type into string, for successful concatenation.
int age = 10;
String str = "He is" + age + "years old.";
In above case 10 will be automatically converted into string for concatenation using valueOf()function.

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";

System.out.println("length of "+ name1 + " is = " + name1.length());


System.out.println("length of "+ name2 + " is = " + name2.length());

System.out.println("character at 3 in "+ name1 + " is = " + name1.charAt(3));


System.out.println("character at 4 in "+ name2 + " is = " + name2.charAt(4));

System.out.println("comparison of the 2 names is " + name1.compareTo(name2));


System.out.println("comparison of the 2 names is " + name2.compareTo(name1));
System.out.println("comparison of the 2 names is " + name3.compareTo(name1));
System.out.println("comparison of the 2 names is " + name4.compareTo(name1));

System.out.println("equality comparison of the 2 names is " + name2.equals(name1));


System.out.println("equality comparison of the 2 names is " + name3.equals(name1));

System.out.println("concatenation of the 2 names is " + name1.concat(name2));


System.out.println("concatenation of the 2 names is " + name1+name2);

System.out.println("First occurence of 'a' in " + name2 + "is at index " +


name2.indexOf('a'));

System.out.println("Last occurence of 'a' in " + name2 + " is at index " +


name2.lastIndexOf('a'));
System.out.println("First occurence of 'x' in " + name2 + " is at index " +
name2.indexOf('x'));
System.out.println("Substring 1 onwards in " + name2 + " is = " + name2.substring(1));

}
}

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:

java.lang.StringIndexOutOfBoundsException: String index out of range: 5


at java.lang.String.charAt(String.java:686)
at strings.str(strings.java:16)

This is so because charAt(5) points to 5th character which is beyond the length of the string = 4

You might also like