Java Strings

String is a sequence of characters. It is used to store text.

Once a object of string is created then it will never be changed that’s why Strings are immutable in nature.

String can be created easily. For Example: String str=”Hello all of you”;

You can create string in two ways:

1. By string literal

2. By new keyword

In string literal, string is created by using double quotes.

String str = ”Hello world”;

You can use the new operator followed by a space and then class name and then in parentheses you can include values used to initialize the fields of the object.

String str=new String(“Hello World”);

Methods of String:

1. int length() – Returns the no characters in the string.

Syntax: str.length();

For Example: “tutsfinder”.length(); //retursn 10

2. chartAt(int i) – Returns the character at ith index

Syntax: str.charAt(i);

For example: “tutsfinder”.charAt(4); //returns f

3. substring(int i) – Returns the substring from the ith index to the end of the string.

Syntax: str.substring(i);

Example: “tutsfinder”.substring(4); // returns finder

4. substring(int i,int j) – Returns the string from ith index to j-1 index.

Syntax: str.substring(i,j);

For example: “tutsfinder”.substring(4,7) //returns find

5. concat(str) – Concatenates specified string to the end of the string.

For Example:

String s1=”tuts”;

String s2=”finder”;

S1.concat(s2); //returns tutsfinder

6. indexOf(String str) – Returns the index within the string of the first occurrence of the specified string, starting at the specified string.

For example:

String s=new String(“Java Tutorials”);

s.indexOf(“Tutorials”); //returns 5

7. toLowerCase() – Coverts all the characters in the string to Lower case.

Syntax: str.toLowerCase();

8. toUpperCase() – Converts all the characters in the string to Upper case.

Syntax: str.toUpperCase();

9. trim() – It removes the whitespaces from the string and returns the copy of that string. It does not white spaces in the middle.

Syntax: str.trim();

10. replace(old char, new char) - Replaces the old character with new character and returns the new string.


String str=”Java”

str.replace(‘a’,’x’);  //returns Jxvx