Method of The String Class

Exlpain the following method of the String class.

(1) length()

We can find the length of a given string using the method length().

Syntax:- str.length();

For example-

String s=new String(“Hello World”);
System.out.println(s.length());

It will print the value 11.

(2) concat

We can join or concatenating the two string.

Syntax:- str1.concat(str2);

For example-

String s1=new String(“Hello”);
String s2=new String(“World”);
System.out.println(s1.concat(s2));

It will print the HelloWorld.

(3) charAt(index)

String class extract the character from the string object. There is a method called charAt(index) with the help of which we can extract the character denoted by some index in the array.

Syntax – str.charAt(index);

For example –

String s=new String(“Hello”);
System.out.println(charAt(1));

It will print character e;

(4) equals

We use method equals() to know whether two strings are equal or not. This method is of Boolean type. If two strings are equal then it returns true otherwise it returns false.

Syntax- str1.equals(str2)

For example –

String s1=new String(“Hello”);
String s2=new String(“hello”);
System.out.println(s1.equals(s2));

It will return the false.

(5) equalsIgnoreCase

If we want to compare the two strings without caring for their case differences then we can use the method equalsIgnoreCase()

Syntax – str1.equalsIgnoreCase(str2)

For example -

String s1=new String(“Hello”);
String s2=new String(“hello”);
System.out.println(s1.equalsIgnoreCase(s2));

It will return the true.

(6) subString

We can look for the desired substring from the given string using a method subString(). The syntax of method substring() is as follows –

String substring(int start_index,int end_index);

(7) replace

We can replace the character by some desired character. For example –

String str=new String(“Nisha is Indian”);
String s=str.replace(‘i’,’a’);
System.out.println(s);

It will print Nasha as Inaaan.

(8) toUpperCase and toLowerCase

We can convert the given string to either upper case or lower case using the method toUpperCase() and toLowercase().

Syntax – str.toUppercase();
Str.toLowerCase();

Java Tips

See also

Do you have a Java Problem?
Ask It in The Java Forum

Java Books
Java Certification, Programming, JavaBean and Object Oriented Reference Books

Return to : Java Programming Hints and Tips

All the site contents are Copyright © www.erpgreat.com and the content authors. All rights reserved.
All product names are trademarks of their respective companies.
The site www.erpgreat.com is not affiliated with or endorsed by any company listed at this site.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
 The content on this site may not be reproduced or redistributed without the express written permission of
www.erpgreat.com or the content authors.