String in Java

In this article, we are going to learn about String in Java. It is important to learn about Strings in an entirely different article because it has got a lot of applications in Java. Thus, it is highly significant to know what strings are, how they function in Java, their various methods and implementations. 


The String is a class in Java. All strings are objects of this class, which represent a sequence of characters written inside double-quotes. The String class is used to create and manipulate strings. They are used for storing text in Java and also work the same as an array of char values. E.g. – In Java, “hello”, “world”, “hello world”, all are strings. 

A string in Java is immutable, i.e., once created, their values cannot be changed. We will be discussing some methods used in String and it may seem that the string is being modified but what really happens is that a new string is created and returned containing the result of the string operation.

Strings are stored in a special memory area known as “string pool”.

Creating a String in Java

There are 2 methods of creating strings in Java.

1. Using String Literal

We can create a String using the following code-

class Strings {
    public static void main (String args[]) {
        String s = "Java Programming";

This is the most common way of creating a Java string. If we try to create another string with the exact same value as an existing string, then instead of the creation of another string, only a reference will be created pointing to the same location of the already existing string in memory. To enunciate this point, take a look at this example-

class Strings {
    public static void main (String args[]) {
        String str1 = "Java Programming";
                 String str2 = “Java Programming”;

When str2 was created it found the same value stored in the string memory pool under the name of str1 so, instead of creating a new object, it referenced the memory location of str1.

2. Using new keyword

They can also be created using the “new” keyword because, as mentioned earlier, String is a class and all strings are basically objects. Example-

class Strings {
    public static void main (String args[]) {
        String str1 = new String("Java Programming");
        char arr[] = {'h', 'e', 'l', 'l', 'o'};
        String str2 = new String(arr);

Using the “new” keyword allocates free memory to the string every time it is created. If we try to create another string object having the same value as an existing string in the pool using the keyword “new”, a new object will be created at a different memory location, unlike the case without using “new”.

String Class Methods

There are numerous methods used in strings. These methods are stored in the java.lang.String class where java.lang is a package. We will go through each of the methods explaining them in detail with sample programs.

1. int length()

This method returns the length of the string.

String str = "artoftesting";
int ln = str.length();
System.out.println("The length of the string is - " + ln);

2. int compareTo(String)

This method is used for comparing two strings and returns 0 if both are equal, a positive value if str1 is alphabetically or lexicographically greater than str2 and a negative value if it is the other way round. It is case-sensitive.

String str1 = "HELLO";
String str2 = "hello";
Output: 32

3. int compareToIgnoreCase(String)

As the name suggests, it performs the same functions as the above-mentioned method but it ignores the case, i.e., it is not case-sensitive. So the above code, replaced with this method, will give output as 0.

4. boolean equals(String)

This method gives us true if two strings are equal otherwise false.

String str1 = "HELLO";
String str2 = "hello";
Output: false

5. boolean equalsIgnoreCase(String)

Just like before, this performs the same function as equals() but is not case-sensitive. Thus the above example if implemented by equalsIgnoreCase() will give output as true.

6. String concat(String)

This method is used to concatenate two strings. The second string will be appended to the end of the first string. Finally, it returns the resultant string after concatenation.

String str1 = "Java";
String str2 = "Programming";
Output: JavaProgramming

We can also use the ‘+’ operator to concatenate two strings like this-

str1 + str2 
str1 + " " + str2

We have often used this in print statements.

7. String toUpperCase()

This method is used to convert a string to upper case, i.e., all capital letters. Basically, it returns the updated string with all letters in the upper case.

String str = "Java";
Output: JAVA

8. String toLowerCase()

Just like the above method, it changes the case of the string but to the lower case.

String str = "JAvA";
Output: java

9. char charAt(int)

This method is used to find the character present at a particular index specified by the user. Remember that the index of a string starts from 0 and ends at length()-1, just like in arrays. The index specified can be any value from 0 to length()-1. The spaces in a string are also considered at characters and are given an index so, do not miss that.

String str = "JAVA ProgramMING";
Output: P

If you try to access the index less than 0 or greater than the allowed index, you will get a StringIndexOutOfBoundsException.

10. String format()

String in Java provides format() which returns a String object and allows you to create a formatted string that can be reused. This format is similar to the printf() in C and Java.

String str = "Java Program";

// Combining two strings
String str1 = String.format("The value of string is %s", str);

// Outputs float number upto 10 decimal places
String str2 = String.format("The value of float is %.10f", 23.73925);

// Outputs float number with 14 digits before the decimal point and 3 after it.
String str3 = String.format("The value of float2 is %14.3f", 23.73925);

// Printing the formatted strings

11. String substring()

This method is used to get a substring of the string, i.e., a part of the string. There are two syntaxes to use this method.

a. String substring(int beginIndex) – It is used to get the substring from the beginIndex till the end of the string.

String str = "Java Programming";
Output: Programming

b. String substring(int beginIndex, int endIndex) – It is used to get the substring from beginIndex till endIndex-1.

String str = "Java Programming";
System.out.println(str.substring(5, 12));
Output: Program

12. boolean contains(String)

This method is used to check if the string contains a particular substring or not. It returns true if the substring is present in the String else returns false. It is case-sensitive and takes only strings as arguments, not characters.

String str = "Java Programming";
Output: true

13. String replace(String1, String2)

This method is used for replacing all occurrences of string1 in the string with string2.

String str = "Java Programming";
str = str.replace("a", "i");
Output: Jivi Progrimmimg

14. String replaceFirst(string1, string2)

This method is used to replace only the first occurrence of string1 with string2.

String str = "Java is a good language. I love Java";
String newstr1 = str.replaceFirst("Java", "JAVA");
String newstr2 = str.replaceFirst("a", "A");

Java is a good language. I love Java
JAVA is a good language. I love Java
JAva is a good language. I love Java

15. String replaceAll()

This method is exactly like replace() and replaces all occurrences of string1 with string2. Example to remove all spaces-

String str = "Java is a good language. I love Java";
String replaceString=str.replaceAll("\\s","");

16. int indexOf(String)

This method is used for finding the index of a character or a string from a given string. It returns the index of the first occurrence of the character/string. It is case-sensitive.

String str = "JAVA ProgramMING";

If the string/character is not found in the string -1 is returned.

17. String trim()

This method is used to remove all the extra spaces from the beginning and end of a string but not the middle.

String str = "  Java Programming    ";
System.out.println(str + str.length());
System.out.println(str.trim() + str.length());
Java Programming    22
Java Prgramming22

Note that the trimmed string has been printed but the length of the string remains unchanged. Can you guess why that happened? Because String is immutable. The actual string will never change. Only the modified result is stored in another temporary variable and returned without making any changes in the original string.

You’ll notice that if we print the string again, it will be the same with spaces. Thus, one method to permanently save your changes is to save the result in another string and use it or save it in the same string and the value will be rewritten.

String s = str.trim();
System.out.println(s + s.length());


str = str.trim();
System.out.println(str + str.length());
Output: Java Programming16

18. String valueOf()

This method is used to convert any data type to String type. It can convert double, float, int, char, and objects to String type.

double n = 34.96348;
String ns = String.valueOf(n);
System.out.println(ns + 20);
Output: 34.9634820

19. boolean startsWith(String)

This method is used to check whether a given string starts with a particular substring. It returns true if the string starts with the substring else returns false. It is case-sensitive.

String str = "Java Programming";
System.out.println(str.startsWith("Java")); // true

20. boolean endsWith(String)

Similar to the above-mentioned method, the endsWith() checks whether the given string ends with a particular substring and returns a boolean value. It is also case-sensitive.

String str = "Java Programming";
System.out.println(str.endsWith("min")); // false

21. int lastIndexOf()

This method is used to find the last occurrence of a character or a string in a given string. It returns the index of the last occurrence of the character/string. It is also case-sensitive. There are two types-

a. int lastIndexOf(String)

String str = "Java Programming";
System.out.println(str.lastIndexOf("a")); //Outputs 10

b. int lastIndexOf(String, int beginIndex) – It starts searching from beginIndex.It considers the beginIndex as the end of the string and returns the last occurrence of the String or character.

String str = "Java Programming";
System.out.println(str.lastIndexOf(‘a’,5)); //Outputs 3

22. boolean isEmpty()

This method is used to check whether a string is empty or not. It returns a boolean value. A string is said to be empty if its length is 0.

String str = "Java Programming";
String s = "";
System.out.println(str.isEmpty()); // false
System.out.println(s.isEmpty()); // true

23. int hashCode()

This method is used to return the hashcode of a string. Every string can be converted to an integer value called the hashcode which can be very useful for checking the equality of two large strings. It is calculated by a certain formula.

Hashcodes for two exactly equal strings will always have the same hashcode. While this method can be very beneficial, it is not flawless. The hashcodes of two unequal strings can sometimes coincide as they are based on a mathematical formula. Although the probability of happening is very less.

String str2 = "hello";
String str3 = "hello";
String str4 = "Hello";
String str5 = str4;
System.out.println("Hash Code of:\n");
System.out.println("Empty string: " + str1.hashCode());
System.out.println(str2 + ": " + str2.hashCode());
System.out.println(str3 +": " + str3.hashCode());
System.out.println(str4 + ": " + str4.hashCode());
System.out.println(str5 + ": " + str5.hashCode());
System.out.println("\nAa: " + "Aa".hashCode());
System.out.println("BB: " + "BB".hashCode());
Hash code of: 
Empty string: 0
hello: 99162322
hello: 99162322
Hello: 69609650
Hello: 69609650

Aa: 2112
BB: 2112

24. String[] split()

This method is used to split a string based on a delimiter/regular expression. It returns an array of Strings after splitting the given string based on the delimiter. There are two types of split() in Java Strings-

a. String split(String) – This method simply splits the string based on the delimiter given in the form of a string with no limitation on the number of split strings.

String s = "I Love Java Programming";
String[] strarr = s.split(" "); // Delimiter is space
for (String i : strarr)

b. String split(String, int) – This method limits the number of strings to be split based on the delimiter. It will return only the limited number of strings in the array as per the limit given even if splits are possible after that.

String s = "I Love Java Programming";

// Delimiter is space with limit 2
String[] strarr = s.split(" ", 2);

for (String i : strarr)
Love Java Programming

25. char[] toCharArray()

This method converts a given string to an array of characters. The length of the character array will be the same as the length of the String. This method returns a newly allocated character array.

String s = "Java";
char[] schararr = s.toCharArray();
for (char i : schararr) 

26. String toString()

This method is used to basically convert a string to itself. It returns itself, so technically no conversion takes place. It does not accept any parameters. Since this method performs no changes on the string, it need not be called explicitly, it is usually called implicitly.

String str = "Java Programming";
String str2 = str.toString();
Java Programming

27. String join()

This method is used to join strings together using a delimiter. The first argument specifies the delimiter to be used and the rest are the strings to be joined together. If null is present as one of the strings then only an empty string will be added.

String str=String.join("^","Java","Is","Awesome");  
String str2=String.join("^","Java","","Awesome");


With this, we have come to the end of the topic “String in Java”. We learned what strings are in Java, how to create strings, manipulate them using the various string methods. The methods stated above may look a lot but a little practice can make you almost perfect and acquainted with all these methods.

Their applications are important to know because they will be very useful while writing Java programs and using Strings. I hope you liked the article and practice, experiment, and enjoy learning.

Don’t miss out
Core Java Tutorial Series

Leave a Comment