Strings in Java

In java, the string is not a data type, However, Java has a String class.Java allows us to create a String class object for string handling. In java, strings are class objects which are implemented using two classes String and String Buffer. Java string is an instantiated object of the String class.

The String class contains many useful methods for string-processing applications.A String method is called by writing a String object, a dot, the name of the method and a pair of parentheses to enclose any

String declaration and creation can be done as follows.

String string_name;
string_name=new String(β€œstring”);
String str=new String( β€œ string”);

If a String method returns a value, then it can be placed anywhere
that a value of its type can be used.

You can find the code here

Note: In string, the count always starts from zero when referring to the position or index of

a character in a string

Now lets have a walk through of some string methods.

1. To find string length.

The string length function is used to find the length of the string.


You can find the code here

2. String concatenation.

Uses the + operator on two strings in order to connect them to form one longer string. In string we can combine any numbers of strings for concatenation.

Example 1

You can find the code here

The following code explains that greeting is equal to “Hello “, and javaClass is equal to “class”, then greeting + javaClass is equal to “HelloClass”.

Example 2

You can find the code here

Here I have listed some most commonly used String methods.

No. Method call  Action performed
S2 = s1.toLowerCase( ); Converts the string s1 to all lowercase
S2 = s1.toUpperCase( ); Converts the string s1 to all uppercase
S2 = s1.replace(β€˜x’, β€˜y’ ); Replace all appearance of x with y
S2=s1.trim( ) Remove white spaces at the beginning and end of the  string s1
s1.equals( ) Returns true if s1 is equal to s2(case sensitive)
S1.equalsIgnoreCase( ) Returns true if s1 is equal to s2,ignoring the case of  characters( upper or lower )
int l = s1.length( ) Gives the length of string s1
S1.charAt( ) Gives nth character of s1 
S1.compareTo( s2 Returns negative ,if s1 < s2 , Positive , if s1 >s2,  Zero is s1 equals s2
10 S1.concat( ) Concatenates s1 and s2
11 S1.substring( n ) Give substring starting from nth character
12 S1.substring(n , m ) Give substring starting from nth character up to  mth(not including mth)
13 String. valueOf( p Creates a string object of the parameter p
14 p. toString( ) Creates string representation of the object p
15 S1.indexOf ( β€˜x’ ) Gives the position of the first occurrence of β€˜x’ in the  string s1
16 S1.indexOf( β€˜x’ , n ) Gives the position of β€˜x’ that occurs after nth position  in the string s1 
17 String .valueOf( variable) Converts the parameter value to string representation

Rutu Shah