String In Java


Java / Thursday, August 16th, 2018

String Handling

String in Java is a sequence of characters. Many other languages, strings implemented as character arrays, but in Java strings implemented as objects of type String. That’s make string handling in Java more convenient. Like, Java has methods to compare two strings, search for a sub-string, concatenate two strings, and change the case of letters within a string.

When you create a String object, you cannot change the characters that comprise the string. At first, this may seem to be problematic. However, don’t worry; you can still perform all types of string operations. When you need an altered version of created object a new String object is created which hold the modified version. The original string will remain unchanged.

But if you really want the modifiable string, there is another class of String called StringBuffer, whose objects contain strings that can be changed after they are created.

String and StringBuffer classes are available to all programs automatically as they are in java.lang package. Both the classes cannot be subclassed as they are declared final.

There are many constructors in String class. To create an empty String, use the default constructor. For example,
String str = new String();
That will create an object of String with no characters in it.

If you want to create strings that have initial values, the String class has a variety of constructors to handle this. To create a String initialized by an array of characters, use the constructor shown here:

String(char chars[])

Here is an example:
char chars[] = {‘x’, ‘y’, ‘z’};
String str = new String(chars);
The constructor initializes str with the string “xyz”.

You can use sub-range of a character array as an initializer using the following constructor:

String(char chars[], int startIndex, int numChars)

Here, starIndex specifies the index at which the sub-range begins, and numChars specifies the number of characters to use. Here is an example:
char chars = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’};
String str = new String(chars, 2, 3);
This initializes str with the string “cde”.

You can construct a String object using another String object using the following constructor:

String(String strObj)

String Methods

length()

This method is used to return the length of a string (number of characters present in the string). You must note that the length is an integer value.
Syntax:
int var_name = string_var.length();
Example:
String str = “Computer”;
int n = str.length();
Here, n=8, as number of characters available in the string str is 8.

charAt()

It returns a character from the given index of the string.
Syntax:
char var_name = string_var.charAt(index);
Example:
String str = “Computer”;
char ch = str.charAt(3);
Here, ch = ‘p’ as the character at 3rd index i.e., in 4th position is p.

indexOf()

This method returns the index of a character available in the string.
Syntax:
int var_name = string_var.indexOf(character); //default
Example:
String str = “UNDERSTANDING”;
int k = str.indexOf(‘N’);
Here, the value returned by the method is 1. Hence, the 1st appearance of ‘N’ in the string.
String st = “MALAYALAM”;
int p = st.indexOf(‘A’,4);
Now the method will return the index of ‘A’ available in the string after 4th index.
Hence, p = 5
String str = “COMPUTER”;
int p = str.indexOf(‘C’,3);
Here, the letter ‘C’ is not available after 3rd index in the string. So, it returns the value p = -1.

lastIndexOf()

This method is applied to find the index of the last occurrence of a character in a string.
Sysntax:
int var_name = string_var.lastIndexOf(character);
Example:
String str = “MALAYALAM”;
int n = str.lastIndexOf(‘A’);
It returns 7 to the integer variable n.

substring()

This method is used to extract a part of string.
Syntax:
String var_name = string_var.substring(index);
Example:
String str = “COMPUTER”;
String st = str.substring(3);
The method will return all the characters of the string starting from the 3rd index. Hence, st = “PUTER”.
String s = s.substring(3, 6);
It returns a part of the string from the 3rd index to the 6th index. Hence, p = “PUT”.

toLowerCase()

It returns the letters of the string in lower case. If any character is already in lower case or the character is a special character then it remains same.
Syntax:
String var_name = string_var.toLowerCase();
Example:
String str = “COMPUTER”;
String st = str.toLowerCase();
Here, st results in “computer”.

toUpperCase()

It returns the letters of the string in upper case. If any character is already in upper case or the character is a special character then it remains same.
Syntax:
String var_name = string_var.toUpperCase();
Example:
String str = “computer”;
String st = str.toLowerCase();
Here, st results in “COMPUTER”.

replace()

This method is used to replace a character by another character or to replace a string by another string at all its occurrences in the given string.
Syntax:
String var_name = string_var.replace(char_to_replace, char_to_appear);
String var_name = string_var.replace(substring_to_replace, substring_to_appear);
String var_name = string_var.replace(start_index, substring_to_replace, substring_to_appear);
Example:
String str = “MXLXYXLXM”;
String st = str.replace(‘X’, ‘A’);
Here, each character ‘X’ of the string is replaced by ‘A’. hence, the new string st results in “MALAYALAM”.
String p = str.replace(3, ‘X’, ‘A’);
Replacement of the character ‘X’ with ‘A’ will take place starting from the 3rd index in the string. Hence, the resulting string in p will be “MXLAYALAM”.
String str = “The green bottle is in green bag”.
String st = str.replace(“green”, “red”);
Here, each sub string “green” of the given string is replaced by “red”. Hence, the new string p results in “The red bottle is in red bag”.

concat()

This method is applied to concatenate two strings together.
Syntax: String var_name = string_var1.concat(string_var2);
Example:
String x = “COMPUTER”;
String y = “APPLICATIONS”;
String z = x.concat(y);
Here, both the string x and y will be joined together. Hence, z results in “COMPUTERAPPLICATIONS”

equals()

This method is used to compare two strings together to check whether they are identical or not. It returns a boolean value true if both are same, false otherwise.
Syntax:
boolean var_name = string_var1.equals(string_var2);
Example:
String x = “COMPUTER”;
String y = “SCIENCE”;
boolean z = x.equals(y);
Here, z results in false.
String x = “COMPUTER”;
String y = “computer”;
if(x.equals(y))
String.out.println(“same”);
else
String.out.println(“different”);
The above program snippet displays the message ‘different’.
You must note that equals() method treats corresponding upper case and lower case characters differently.

equalsIgnoreCase()

This method is also used to compare two strings to check whether both are identical or not after ignoring the case (i,e., corresponding upper and lower case characters are treated to be the same). It also returns a boolean data as true of false.
Syntax:
Boolean var_name = string_var1.equalsIgnoreCase(string_var2);
Example:
String x = “COMPUTER”;
String y = “computer”;
boolean p = x.equalsIgnoreCase(y);
System.out.println(p);
The value printed out is true.

compareTo()

It is also a type of method which compares two strings. It not only checks the equality of the strings but also checks whether a string is bigger or smaller than the other.
Syntax:
int var_name = string_var1.campareTo(string_var2);
Example:
String x = “COMPUTER”;
String y = “SCIENCE”;
int n = x.compareTo(y);
Here, n = 0, if x and y both the strings are same.
n > 0, if string x is greater than string y.
n < 0, if string x is less than string y.
In the example shown above, the variable n will be assigned a negative value (i.e., n = -16), that is the difference between the ASCII values of the first character ‘C’ of the first string “COMPUTER” and ‘S’ of the string “SCEINCE”.
You must note that the comparisons are based on the order of the corresponding characters of the strings but not on the basis of the length of strings.

trim()

This method is used to remove leading and trailing blanks from the string. Other blanks, which are available in between the words, will remain unchanged.
Syntax:
String var_name = string_var.trim();
Example:
String x = “  COMPUTER  ”;
String y = x.trim();
System.out.println(“Original string: “+x);
System.out.println(“String after trancation: “+y);
Output:
Original string:  COMPUTER
String after trancation: COMPUTER

endswith()

This method is used to check whether a given string has a specified suffix or not. It returns a boolean value true or false accordingly.
Syntax:
boolean var_name = string_var1.endswith(string_var2);
Example:
String p = “COMPUTER IS FUN”;
String b = “FUN”;
Boolean x = p.endswith(b);
It will return x as true.

startwith()

This method returns a Boolean value true if a given string is used as the prefix to another string, false otherwise.
Syntax:
boolean var_name = string_var1.startwith(string_var2);
Example:
String p = “COMPUTER IS FUN”;
String b = “YOUR”;
Boolean x = p.startwith(b);
It will return x as false as string p does not start with YOUR.

Leave a Reply

Your email address will not be published. Required fields are marked *