A Collection of characters forms a String. The characters may be alphabets, special characters or numbers too.
Some of the built-in classes are
- · String
- · StringBuilder
- · StringBuffer
Common methods for each class are given below.
String:
String is
a sequence of characters which are immutable. To create an object using String literally,
use the below code.
String a =” Welcome”;
If you want to create a string object using “new” keyword, just
follow the code given as follows.
String a = new String (“Welcome”);
If you are using character array, this code helps you.
char[] cA = { 'W', 'e', 'l', 'c', 'o',’m’,’e’ };
String a = new String(cA);
Let us code an example for Byte Array.
Byte[] bA = {87,101,108,99,111,109,101}; //ASCII value for
welcome
String b = new String (bA);
Common methods for String:
import java.lang.String.*;
class StringEg
{
public static void
main(String args[])
{
String a = new
String ("Welcome to the world of Java");
System.out.println("The String is:"+a);
System.out.println("The length of the String is:"+a.length());
System.out.println("The 3rd position character in the String
is:"+a.charAt(3));
System.out.println("The substring index
is:"+a.indexOf("world"));
System.out.println("The String in lowercase
is:"+a.toLowerCase());
System.out.println("The String in Uppercase
is:"+a.toUpperCase());
System.out.println("The concatenated string
is:"+a.concat("Programming "));
}
}
Output:
C:\raji\blog>javac StringEg.java
C:\raji\blog>java StringEg
The String is:Welcome to the world of Java
The length of the String is:28
The 3rd position character in the String is:c
The substring index is:15
The String in lowercase is:welcome to the world of java
The String in Uppercase is:WELCOME TO THE WORLD OF JAVA
The concatenated string is:Welcome to the world of
JavaProgramming
Note: String is thread safe.
StringBuilder:
This
string content can be modified. It has mutable sequence of characters. The methods
in this ‘StringBuilder’ is given below.
Methods:
Insert(): it inserts the given string into the specified
postion.
Delete(): it removes a specified sub string.
Append(): This function appends the given string into the
string.
Reverse():This reverses the entire string.
toString(): It converts the StringBuilder into String.
Note: It is mutable but not thread safe. Suitable for single
thread operations.
StringBuffer:
It handles
multi thread in safe manner. The common methods are listed below.
Methods:
toString(): This function converts the StringBuffer into
String.
Append():It adds the given string into StringBuffer.
Reverse():The entire String is reversed.
Insert(): It adds the string into specific position.
Delete():It removes the set of characters.
Replace(): It replaces the set of characters.
It is useful for multi-threaded environments.
No comments:
Post a Comment