Class 10 ICSE - Java
Strings Methods
In java there are lot of string methods that allow us to perform operation on a string or we can say
sequence of char values.For example indexOf(int),it returns the index of first occurance of
specified character in the string.
So we will discuss strings methods which are performed on strings.
Length()
As the name suggest from length,means it is used to calculate the length of string,return type of
this
function is integer
We will understand this in program.
IndexOf(String)
As the name suggest index,means it will return index value of first character of the substring from
the
string, which is given to function as a parameter.If the character is not present in the string it will
return -1
Example:
charAt(int)
In this function we pass index value as a parameter and it will return the character at the given
index.Here the index value start from 0 and it will goes to n-1,where n is the length of string.The
starting index will be from 0.
Example:
replace(String,String)
This function takes two strings or characters as a parameters,and it will replace the old string with a new
string.
Here the
first parameter tells the old string or character which should be replaced, and second
parameter tells
by which string or character it should be replaced.
toLowerCase()
This function converts all the characters in a string in a
lowercase.
Example:
toUpperCase()
This function converts all the characters in a string in a
lowercase,and then returns the converted string.
Example:
compareTo()
This function is basically used to compare two strings.It works on the the basis of unicode of each
chaeracter in a string
This function returns on the basis of following conditions:-
-
It returns 0,if two strings are equal.
-
It returns positive(+),if firstmismatch character of first string is greater
than firstmismatch character of second String
-
It returns negative(-),if firstmismatch character of first string is lesser
than firstmismatch character of second String
Example:
In the above example, we can observe that:-
-
when String hello is compared to String "hello" , it will result zero,because these
String are equal
hello.compareTo("hello")
-
When String "hello" is compared to String "Hello", it will result to positive value
32,as
here we are taking difference of unicode(h) and unicode(H) which will output to
positive
value 32.
-
When String "hello" is compared to String "world", it will result to negative value
-15,as
here we are taking difference of unicode(h) and unicode(w) which will output to
negative
value .
hello.compareTo("hello")