String in java is a special
class of objects which represents characters. Java String is a immutable object
and immutable object cannot be modify. Therefore, when a String method used
that always returns a new String instead of modifying the existing. String in
java has its all attributes marked as final. If we go for concatenation,
another string object will be created and the value is going to assign for that
object, so we are going to have two objects.
Because String and its
attributes are declared as final, the system can pass the sensitive read-only
information without disturbing about alteration.
String Functions
Some of the most utilized function of String class are as follows:
String.length() – to find the length of a string value.
Example:
String Str=“Hello Java”;
Int L=Str.length(); // Value of L = 10
String.charAt(int) – extract a character from the said string from given position.
Example:
String Str=“Hello Java”;
System.out.println(Str.charAt(1)); // Output -> 'e'
String1.equals(String2) – check equality between two string and return a Boolean value as
result.
Example:
String Str=“Hello”;
System.out.println(Str.equals(“HELLO”)); // Output -> 'false'
String1.equalsIgnorecase(String2) - check equality between two strings while ignoring he case
difference and return a Boolean value as result.
Example:
String Str=“Hello”;
System.out.println(Str.equalsIgnorecase(“HELLO”)); //Output -> 'true'
String1.compareTo(String2) – Compare between two string( relevant to the ASCII values of each
character), if both equal it return 0, if String1 is smaller than String2 then
it will return a negative value and if String1 is bigger than String2
then it will return a positive value.
Example:
String Str=“Hello”;
System.out.println(Str.comapreTo(“HELLO”)); // "e - E" means 101 - 69 = -32
// it will return 32 as Ascii value of ‘e’
is 101 and the Ascii value of 'E' is 69 is
and difference is 32, therefore the value store in variable ‘Str’ is bigger than
the other string.
compareToIgnoreCase(String str)
int compareToIgnoreCase(String str) compares two strings while ignoring the case or rather compare two string lexicographically.
Example:
String Str="This is Test";
String Str1="THIS IS TEST";
int t=Str.compareToIgnoreCase(String Str1);//return 0.
compareToIgnoreCase(String str)
int compareToIgnoreCase(String str) compares two strings while ignoring the case or rather compare two string lexicographically.
Example:
String Str="This is Test";
String Str1="THIS IS TEST";
int t=Str.compareToIgnoreCase(String Str1);//return 0.
String.substring(int) – Extract all the string from given position until end.
Example:
String Str=“I love my contry”;
System.out.println(Str.substring(7)); //
Output : my country
String.substring(int,int) - Extract all the string from starting position up to left of end
position.
Example:
String Str=“I love my contry”;
System.out.println(Str.substring(0,6)); //
Output : I love
No comments:
Post a Comment