java strings tutorial

Bodhak java strings tutorial we are going to discuss in details about Strings, String class, String constant pool, String class methods, StringBuffer class, StringBuffer methods, StringBuilder class, StringBuilder class methods, Difference between String, StringBuffer and StringBuilder.

Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

 

java strings tutorial

The string is a class built into the Java language defined in the java.lang package. It represents character strings

Strings are immutable; that is, they cannot be modified once created. Whenever it looks as if a String object was modified actually a new String was created.

String class Constructors:

To create an empty String,  call the default constructor.

Syntax: String String();

Ex :  String s = new String();

 

Here, it will create an instance of String with no characters in it.

The String class provides 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, the constructor has the char array as an argument.

It is possible to specify a subrange of a character array as an initializer using the following constructor:

 

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

 

Here, start Index specifies the index at which the sub-range begins, and numChars specifies the number of characters to use.

 

The constructor can have a String object that contains the same character sequence as another String object using the following constructor:

String(String strObj)

 

Here, strObj is a String object.

String class methods:

String Length : length()

The length of a string is the number of characters that it contains. To obtain this value,  the length( ) method is used to find the length of a string.

Syntax:     int length( )  charAt( )

 

To extract a single character from a String, the charAt( ) method is used.

char charAt(int where)

Here, where is the index of the character that you want to obtain? The value of where must be nonnegative and specify a location within the string.charAt( ) returns the character at the specified location.

getChars( )

To extract more than one character at a time, getChars( ) method is used.