0% found this document useful (0 votes)
8 views20 pages

Java String Methods Explained

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views20 pages

Java String Methods Explained

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java String charAt

The java string charAt() method returns a char value at the given index number. The index
number starts from 0.

The signature of string charAt() method is given below:

public char charAt(int index)

Parameter:

index : index number, starts with 0

Returns: char value

Specified by: CharSequence interface

Throws:

IndexOutOfBoundsException : if index is negative value or greater than this string length.

1. public class CharAtExample{


2. public static void main(String args[]){
3. String name="javatpoint";
4. char ch=[Link](4);//returns the char value at the 4th index
5. [Link](ch);
6. }}

o/p: t

Java String compareTo


The java string compareTo() method compares the given string with current string
lexicographically. It returns positive number, negative number or 0.

If first string is greater than second string, it returns positive number (difference of character
value). If first string is less than second string, it returns negative number and if first string is
equal to second string, it returns 0.

1. s1 > s2 => positive number


2. s1 < s2 => negative number
3. s1 == s2 => 0
Signature: public int compareTo(String anotherString)

Parameters: anotherString: represents string that is to be compared with current string

1. public class LastIndexOfExample{


2. public static void main(String args[]){
3. String s1="hello";
4. String s2="hello";
5. String s3="meklo";
6. String s4="hemlo";
7. [Link]([Link](s2));
8. [Link]([Link](s3));
9. [Link]([Link](s4));
10. }}

o/p: 0
-5
-1

Java String concat


The java string concat() method combines specified string at the end of this string. It returns
combined string. It is like appending another string.

Signature: The signature of string concat() method is given below:

public String concat(String anotherString)

Parameter: anotherString : another string i.e. to be combined at the end of this string.

public class ConcatExample{

public static void main(String args[]){

String s1="java string";

[Link]("is immutable");

[Link](s1);

s1=[Link](" is immutable so assign it explicitly");

[Link](s1);

}}
o/p: java string
java string is immutable so assign it explicitly

Java String equals


The java string equals() method compares the two given strings based on the content of the
string. If any character is not matched, it returns false. If all characters are matched, it returns
true.

The String equals() method overrides the equals() method of Object class.

Signature: public boolean equals(Object anotherObject)

Parameter:

anotherObject : another object i.e. compared with this string.

public class EqualsExample{

public static void main(String args[]){

String s1="javatpoint";

String s2="javatpoint";

String s3="JAVATPOINT";

String s4="python";

[Link]([Link](s2));//true because content and case is same

[Link]([Link](s3));//false because case is not same

[Link]([Link](s4));//false because content is not same

}}

o/p: true
false
false
java - String equalsIgnoreCase() Method
Description:

This method compares this String to another String, ignoring case considerations. Two strings
are considered equal ignoring case if they are of the same length, and corresponding characters in
the two strings are equal ignoring case.

Syntax: Here is the syntax of this method:


public boolean equalsIgnoreCase(String anotherString)

Parameters:

Here is the detail of parameters:

anotherString -- the String to compare this String against

public class Test {

public static void main(String args[]) {


String Str1 = new String("This is really not immutable!!");
String Str2 = Str1;
String Str3 = new String("This is really not immutable!!");
String Str4 = new String("This IS REALLY NOT IMMUTABLE!!");
boolean retVal;

retVal = [Link]( Str2 );


[Link]("Returned Value = " + retVal );

retVal = [Link]( Str3 );


[Link]("Returned Value = " + retVal );

retVal = [Link]( Str4 );


[Link]("Returned Value = " + retVal );
}
}
o/p:Returned Value = true
Returned Value = true
Returned Value = true

Java String indexOf


The java string indexOf() method returns index of given character value or substring. If it is not
found, it returns -1. The index counter starts from zero.

Signature: There are 4 types of indexOf method in java. The signature of indexOf methods
are given below:
No. Method Description
1 int indexOf(char ch) returns index position for the given char value

returns index position for the given char value and from
2 int indexOf(char ch, int fromIndex)
index

3 int indexOf(String substring) returns index position for the given substring

int indexOf(String substring, int returns index position for the given substring and from
4
fromIndex) index

Parameters: ch: char value i.e. a single character e.g. 'a'

fromIndex: index position from where index of the char value or substring is returned

substring: substring to be searched in this string

public class IndexOfExample{

public static void main(String args[]){

String s1="this is index of example";

//passing substring

int index1=[Link]("is");//returns the index of is substring

int index2=[Link]("index");//returns the index of index substring

[Link](index1+" "+index2);//2 8

//passing substring with from index

int index3=[Link]("is",4);//returns the index of is substring after 4th index

[Link](index3);//5 i.e. the index of another is

//passing char value

int index4=[Link]('s');//returns the index of s char value


[Link](index4);//3

}}

o/p: 2 8
5
3

Java String length


The java string length() method length of the string. It returns count of total number of
characters. The length of java string is same as the unicode code units of the string.

Signature: The signature of the string length() method is given below:

public int length()

Specified by: CharSequence interface

public class LengthExample{

public static void main(String args[]){

String s1="javatpoint";

String s2="python";

[Link]("string length is: "+[Link]());//10 is the length of javatpoint string

[Link]("string length is: "+[Link]());//6 is the length of python string

}}

o/p:string length is: 10


string length is: 6

Java String substring


The java string substring() method returns a part of the string.

We pass begin index and end index number position in the java substring method where start
index is inclusive and end index is exclusive. In other words, start index starts from 0 whereas
end index starts from 1.

There are two types of substring methods in java string.


Signature

1. public String substring(int startIndex)


2. and
3. public String substring(int startIndex, int endIndex)

If you don't specify endIndex, java substring() method will return all the characters from
startIndex.

Parameters

startIndex : starting index is inclusive

endIndex : ending index is exclusive

 public class SubstringExample{


 public static void main(String args[]){
 String s1="javatpoint";
 [Link]([Link](2,4));//returns va
 [Link]([Link](2));//returns vatpoint
 }}
o/p: va
vatpoint

Java String toCharArray


The java string toCharArray() method converts this string into character array. It returns a
newly created character array, its length is similar to this string and its contents are initialized
with the characters of this string.

Signature

The signature or syntax of string toCharArray() method is given below:

public char[] toCharArray()

public class StringToCharArrayExample{

public static void main(String args[]){

String s1="hello";

char[] ch=[Link]();
for(int i=0;i<[Link];i++){

[Link](ch[i]);

} }}

o/p: hello

Java String toLowerCase()


The java string toLowerCase() method returns the string in lowercase letter. In other words, it
converts all characters of the string into lower case letter.

The toLowerCase() method works same as toLowerCase([Link]()) method. It


internally uses the default locale.

Signature

There are two variant of toLowerCase() method. The signature or syntax of string toLowerCase()
method is given below:

1. public String toLowerCase()


2. public String toLowerCase(Locale locale)

The second method variant of toLowerCase(), converts all the characters into lowercase using
the rules of given Locale.

public class StringLowerExample{

public static void main(String args[]){

String s1="JAVATPOINT HELLO stRIng";

String s1lower=[Link]();

[Link](s1lower);

}}

o/p:javatpoint hello string


String toString() Method
Description: This method returns itself a string

Syntax: Here is the syntax of this method:


public String toString()

Parameters: Here is the detail of parameters:


import [Link].*;

public class Test {


public static void main(String args[]) {
String Str = new String("Welcome to [Link]");

[Link]("Return Value :");


[Link]([Link]());
}
}
o/p:Return Value :Welcome to [Link]

Java String toUpperCase


The java string toUpperCase() method returns the string in uppercase letter. In other words, it
converts all characters of the string into upper case letter.

The toUpperCase() method works same as toUpperCase([Link]()) method. It


internally uses the default locale.

Signature

There are two variant of toUpperCase() method. The signature or syntax of string toUpperCase()
method is given below:

1. public String toUpperCase()


2. public String toUpperCase(Locale locale)

The second method variant of toUpperCase(), converts all the characters into uppercase using the
rules of given Locale.

public class StringUpperExample{

public static void main(String args[]){

String s1="hello string";


String s1upper=[Link]();

[Link](s1upper);

}}

o/p:HELLO STRING

Java String trim


The java string trim() method eliminates leading and trailing spaces. The unicode value of
space character is '\u0020'. The trim() method in java string checks this unicode value before and
after the string, if it exists then removes the spaces and returns the omitted string.

The string trim() method doesn't omits middle spaces.

Signature

The signature or syntax of string trim method is given below:

public String trim()

public class StringTrimExample{

public static void main(String args[]){

String s1=" hello string ";

[Link](s1+"javatpoint");//without trim()

[Link]([Link]()+"javatpoint");//with trim()

}}

o/p: hello string javatpoint


hello stringjavatpoint

Java String valueOf


The java string valueOf() method converts different types of values into string. By the help of
string valueOf() method, you can convert int to string, long to string, boolean to string, character
to string, float to string, double to string, object to string and char array to string.
Signature

The signature or syntax of string valueOf() method is given below:

public static String valueOf(boolean b)

public static String valueOf(char c)

public static String valueOf(char[] c)

public static String valueOf(int i)

public static String valueOf(long l)

public static String valueOf(float f)

public static String valueOf(double d)

public static String valueOf(Object o)

public class StringValueOfExample{

public static void main(String args[]){

int value=30;

String s1=[Link](value);

[Link](s1+10);//concatenating string with 10

}}

o/p:3010

What is mutable string

A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.

1) StringBuffer append() method

The append() method concatenates the given argument with this string.

class A{

public static void main(String args[]){


StringBuffer sb=new StringBuffer("Hello ");

[Link]("Java");//now original string is changed

[Link](sb);//prints Hello Java

StringBuffer capacity() method

The capacity() method of StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of character increases from its current capacity,
it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will
be (16*2)+2=34.

class A{

public static void main(String args[]){

StringBuffer sb=new StringBuffer();

[Link]([Link]());//default 16

[Link]("Hello");

[Link]([Link]());//now 16

[Link]("java is my favourite language");

[Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2

[Link] Method
Returns the character at a specified index.

Package: [Link]

public synchronized char charAt(


int index);
Parameters: index

The index of the character.

public class MyClass


{
public static void main(String[] args)
{
// Construct a StringBuffer object:
StringBuffer s = new StringBuffer(
/* 01234567890123456789012345678901234 */
"To learn a language, start with J#.");
int idx = 33;

// Display the character at index 33:


[Link]("The character at the position " +
idx + " is: \"" + [Link](idx) + "\".");
}
}

/*
Output:
The character at the position 33 is: "#".
*/

[Link] Method
Deletes the characters within a specified range in a StringBuffer object and returns the new
StringBuffer object.

Package: [Link]

public synchronized [Link] delete(


int start,
int end);

Parameters
start : The starting index.

end : The ending index.

// [Link]
// [Link] example

public class MyClass


{
public static void main(String[] args)
{
// Construct a StringBuffer object:
StringBuffer s = new StringBuffer(
/* 012345678901234567890123456789012 */
"To learn J#, start with keywords.");
int start = 0;
int end = 13;

// Delete chars from start to end:


s = [Link](start,end);

// Catenate a string and display the buffer:


[Link]("Always " + s);
}
}

/*
Output:
Always start with keywords.
*/

[Link] Method
Deletes the character at a specified index.

Package: [Link]

public synchronized [Link] deleteCharAt(


int index);

Parameters:
index : The index of the character to be deleted.

// [Link]
// [Link] example

public class MyClass


{
public static void main(String[] args)
{
// Construct a StringBuffer object:
StringBuffer s = new StringBuffer(
/* 012345678901234567890123456789012 */
"To learn J#, start with keywords.");
int index = 32;

// Delete the char at position 32:


s = [Link](index);

// Catenate a string and display the buffer:


[Link](s + "!");
}
}

/*
Output:
To learn J#, start with keywords!
*/
[Link] Method
Ensures that the buffer capacity is not less than a specified minimum.

Package: [Link]

public synchronized void ensureCapacity(


int minimumCapacity);

Parameters
minimumCapacity : The minimum capacity.

// Ensure that capacity is not less than 32:


[Link](32);

[Link] Method
Copies the characters within a specified range from a StringBuffer object to a destination
character array at a specified position.

Package: [Link]

public synchronized void getChars(


int srcBegin,
int srcEnd,
char[] dst,
int dstBegin);

Parameters
srcBegin : The beginning position of the range.

srcEnd: The ending position of the range.

dst : The destination character array.

dstBegin : The insertion position.

Example

In this example, two characters are copied from the StringBuffer object, src, to a destination
character array, dst. The destination array contains the string "J#."

// [Link]
// [Link] example
public class MyClass
{
public static void main(String[] args)
{
// Construct a StringBuffer object:
StringBuffer src = new StringBuffer(
/* 012345678901234567890123456789012 */
"To learn J#, start with keywords.");

// Declare a new char array:


char[] dst = new char[2];

// Copy the chars #9 and #10 to dst:


[Link](9,11,dst,0);

// Display dst:
[Link](dst);
}
}

/*
Output:
J#
*/

StringBuffer insert() method

The insert() method inserts the given string with this string at the given position.

class A{

public static void main(String args[]){

StringBuffer sb=new StringBuffer("Hello ");

[Link](1,"Java");//now original string is changed

[Link](sb);//prints HJavaello

1. [Link] Method
Returns the length of the StringBuffer object.

Package: [Link]
public int length();
// [Link]
// [Link] example

public class MyClass


{
public static void main(String[] args)
{
// Construct two StringBuffer objects:
StringBuffer s1 = new StringBuffer("Hello world!");
StringBuffer s2 = new StringBuffer("Hi there.");

// Display the length of each buffer:


[Link](s1 + " = " + [Link]() + " characters");
[Link](s2 + " = " + [Link]() + " characters");
}
}

/*
Output:
Hello world! = 12 characters
Hi there. = 9 characters
*/

[Link] Method
Changes a character at a specified index in a StringBuffer object.

Package: [Link]

public synchronized void setCharAt(


int index,
char ch);

Parameters
index :The index of the character to be changed.

Ch: The new character.

// [Link]
// [Link] example

public class MyClass


{
public static void main(String[] args)
{
// Construct a StringBuffer object:
StringBuffer s = new StringBuffer("Hello world!");

// Change w to W:
[Link](6,'W');

// Display the buffer:


[Link](s);
}
}

/*
Output:
Hello World!
*/

[Link] Method
Changes the length of a StringBuffer object to a specified length.

Package: [Link]

public synchronized void setLength(


int newLength);

Parameters
newLength : The new length of the buffer.

Example
// [Link]
// [Link] example

public class MyClass


{
public static void main(String[] args)
{
// Construct a StringBuffer object:
StringBuffer s = new StringBuffer("Hello world!");

// Change the length to 5 characters:


[Link](5);

// Display the buffer:


[Link](s);
}
}

/*
Output:
Hello
*/

[Link] Method (Int32)


Returns a substring that starts at a specific index in a StringBuffer object.

Package: [Link]
public [Link] substring(
int start);

Parameters
start :The starting index of the substring.

Return Value

The substring that starts at start and extends to the end of the string.

// [Link]
// [Link] example

public class MyClass


{
public static void main(String[] args)
{
// Construct a StringBuffer object:
StringBuffer s = new StringBuffer("Hello world!");

// Display the substring:


[Link]("In \"" + s +
"\", the substring starting at the 6th character is: "
+ [Link](6));
}
}

/*
Output:
In "Hello world!", the substring starting at the 6th character is: world!
*/

[Link] Method
Converts a StringBuffer object to a String object.

Package: [Link]

public [Link] toString();

Return Value

The String object equivalent to the value stored in the StringBuffer object.

// [Link]
// [Link] example
public class MyClass
{
public static void main(String[] args)
{
// Construct a StringBuffer object:
StringBuffer s = new StringBuffer("Hello there");

// Append a char to the buffer:


[Link]('!');

// Convert to a String object and display it:


[Link]([Link]());
}
}

/*
Output:
Hello there!
*/

You might also like