String in Java

  • Last Updated: January 26, 2024
  • By: javahandson
  • Series
img

String in Java

In this article, we will learn what is a String in Java and different ways of creating a String and its methods. We will also learn what is the difference between String Literal and String Object. If you want to learn more about other Java, Java 8, or Spring concepts then please check the above menu options.

 

The string represents a group of characters. Ex. Name, Address, etc.

In C/C++ a string represents an array of characters but in Java string is not a character array. It is an object of the String class. In Java every class is treated as a user-defined data type hence String is also a data type. We can declare a string like below.

String str = "JavaHandsOn";

Here str is a variable and it's data type is String.

Ways of creating String

There are 3 ways of creating a string

1. We can assign a group of characters to a variable of String data type.

String str = "JavaHandsOn"; // string literal

A string literal is a group of characters enclosed in double-quotes. We can split the above statement into 2 parts as well.

String str; // declaring the variable
str = "JavaHandsOn"; // assigning the value to the variable

In this string literal approach the string value will be stored in the string constant pool area i.e. “JavaHandsOn” will be stored in the string constant pool area.

Note* The string constant pool area is a part of heap memory.

2. As we know String is a class hence we can create a string object using a new operator and we can assign value to the string in the String constructor argument.

String str = new String("JavaHandsOn");

In this approach, the “JavaHandsOn” value is stored in the heap area.

3. We can convert an array of characters in a string. We just have to pass the character array as an argument to the String constructor.

char[] arr = {'J','a','v','a','H','a','n','d','s','O','n'};
String str = new String(arr);

Write a program to create a string in all the above-mentioned ways.

package com.java.handson.strings;

public class StringDemo {
    public static void main(String[] args) {

        String str1 = "JavaHandsOn";
        String str2 = new String("JavaHandsOn");
        char[] arr = {'J','a','v','a','H','a','n','d','s','O','n'};
        String str3 = new String(arr);

        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);
    }
}
Output:
JavaHandsOn
JavaHandsOn
JavaHandsOn

Difference between String Literal and String Object

String LiteralString Object
String literal is a group of characters enclosed in double quotes and they are directly assigned to a variable.String Object is created using a new operator and the string value is passed as an argument to its constructor.
String literal is stored in string constant pool area.The string object is stored in the heap area.
No new memory will be assigned to the variable if we create a new String variable using the same literal value. This new variable will point to the same memory location of the string constant pool area.New memory will be assigned to the variable if we create a new String variable using the new operator and the same value. This new variable will point to a different memory location of the heap area.
String Literal Vs String Object

 

Below is the diagram that will help you to understand the above points in a better way.

String Literal Vs String Object

Write a program to understand the difference between a string literal and a string object.

package com.java.handson.strings;

public class StringDemo {
    public static void main(String[] args) {

        String s1 = new String("JavaHandsOn");
        String s2 = "JavaHandsOn";

        String s3 = new String("JavaHandsOn");
        String s4 = "JavaHandsOn";

        if (s1 == s2) {
            System.out.println("s1 is equal to s2");
        }
        else {
            System.out.println("s1 is not equal to s2");
        }

        if (s1 == s3) {
            System.out.println("s1 is equal to s3");
        }
        else {
            System.out.println("s1 is not equal to s3");
        }

        if (s2 == s3) {
            System.out.println("s2 is equal to s3");
        }
        else {
            System.out.println("s2 is not equal to s3");
        }

        if (s2 == s4) {
            System.out.println("s2 is equal to s4");
        }
        else {
            System.out.println("s2 is not equal to s4");
        }
    }
}
Output:
s1 is not equal to s2
s1 is not equal to s3
s2 is not equal to s3
s2 is equal to s4 

In the above output, we can see that s2 is equal to s4 because the value of s2 is stored in a constant pool area, and since the value of s4 is equal to the value of s2 hence s4 will point to the same memory location as that of s2.

Methods of a String Class

1. String concat(String str)

The method is used to concat or join two strings. This method takes an argument as a String and returns a String. As this method belongs to the String class hence this method can be called using a String class object.

String s1 = "Java";
String s2 = "HandsOn";
String s3 = s1.concat(s2);

Output: JavaHandsOn

2. int length()

This method is used to find the length of the string or in other words, we can say it is used to find the number of characters in a string. This method does not take any argument but it returns an int value.

String s1 = "JavaHandsOn";
int length = s1.length();

Output: 11

3. String substring(int i)

This method is used to extract a substring from a string. The substring is a smaller part of a string. This method takes an int argument. This argument specifies the position or index of a character in the main string. This method returns a new string consisting of all the characters starting from position i till the end of the string.

String s1 = "JavaHandsOn";
String s2 = s1.substring(4);

Output: HandsOn

4. String substring(int i1, int i2)

This method is also used to extract a substring from a string. This method takes two arguments i1 and i2. i1 specifies the starting position of a character in the main string and i2 specifies the end position. This method returns a new string consisting of all the characters starting from position i1 till i2.

Note* The character at position i2 will be excluded.

String s1 = "JavaHandsOn";
String s2 = s1.substring(4, 10);

Output: HandsO

5. char charAt(int position)

This method returns a character at a specific position in the string.

String s1 = "JavaHandsOn";
char ch = s1.charAt(5);

Output: a
package com.java.handson.strings;

public class StringUtils {

    public static void main(String[] args) {

        String s1 = "Java";
        String s2 = "HandsOn";
        String s3 = s1.concat(s2);
        System.out.println("Concat : "+s3);

        s1 = "JavaHandsOn";
        int length = s1.length();
        System.out.println("Length : "+length);

        s1 = "JavaHandsOn";
        s2 = s1.substring(4);
        System.out.println("Substring : "+s2);

        s1 = "JavaHandsOn";
        s2 = s1.substring(4, 10);
        System.out.println("Substring : "+s2);

        s1 = "JavaHandsOn";
        char ch = s1.charAt(5);
        System.out.println("charAt : "+ch);
    }
}
Output:
Concat : JavaHandsOn
Length : 11
Substring : HandsOn
Substring : HandsO
charAt : a

6. int indexOf(String substring)

If a given string contains a substring then this method returns the first position of the occurrence of that substring. This method takes a substring as an argument and it returns an int value. This int value is the first position of the occurrence of that substring.

If no occurrence of the substring is found then this method returns some negative value.

String s1 = "Hello welcome to JavaHandsOn";
int position = s1.indexOf("welcome");

Output: 6

7. int lastIndexOf(String substring)

If a given string contains a substring then this method returns the last position of the occurrence of that substring. This method takes a substring as an argument and it returns an int value. This int value is the last position of the occurrence of that substring.

If no occurrence of the substring is found then this method returns some negative value.

String s1 = "Hello welcome to JavaHandsOn, welcome again!";
int position = s1.lastIndexOf("welcome");

Output: 30

8. String replace(char ch1, char ch2)

This method replaces all the occurrences of character ch1 with a new character ch2.

String s1 = "JavaHandsOn";
String s2 = s1.replace('a', 'x');
           
Output: JxvxHxndsOn

9. boolean startsWith(String substring)

If a given string starts with a substring that is present as an argument then the method returns true else it returns false.

String s1 = "Hello welcome to JavaHandsOn";
boolean bool = s1.startsWith("Hello");

Output: true

As the above string s1 starts with the substring “Hello” hence the result will be true.

10. boolean endsWith(String substring)

If a given string ends with a substring that is present as an argument then the method returns true else it returns false.

String s1 = "Hello welcome to JavaHandsOn";
boolean bool = s1.endsWith("HandsOn");

Output: true

As the above string s1 ends with the substring “HandsOn” hence the result will be true.

package com.java.handson.strings;

public class StringUtils {
    public static void main(String[] args) {

        String s1 = "Hello welcome to JavaHandsOn";
        int position = s1.indexOf("welcome");
        System.out.println("indexOf : "+position);

        s1 = "Hello welcome to JavaHandsOn, welcome again!";
        position = s1.lastIndexOf("welcome");
        System.out.println("lastIndexOf : "+position);

        s1 = "JavaHandsOn";
        String s2 = s1.replace('a', 'x');
        System.out.println("replace : "+s2);

        s1 = "Hello welcome to JavaHandsOn";
        boolean bool = s1.startsWith("Hello");
        System.out.println("startsWith : "+bool);

        s1 = "Hello welcome to JavaHandsOn";
        bool = s1.endsWith("HandsOn");
        System.out.println("endsWith : "+bool);
    }
}
Output:
indexOf : 6
lastIndexOf : 30
replace : JxvxHxndsOn
startsWith : true
endsWith : true

11. int compareTo(String s)

This method is used to compare two strings. If there are two strings s1 and s2 then this method tells if s1 is greater than s2 or s2 is greater than s1 or s1 is equal to s2.

  • If s1 is greater than s2 then it returns a positive number.
  • If s2 is greater than s1 then it returns a negative number.
  • If s1 is equal to s2 then it returns 0.
String s1 = "Learn";
String s2 = "Java";
int compare = s1.compareTo(s2);

Output: 2

strings will be compared according to the order of words or characters in a dictionary.

According to the order of words in a dictionary the word Learn (s1) will come after the word Java (s2) hence s1 is greater than s2 and the compareTo method will return a positive number.

If we do a opposite comparison then the compareTo method will return a negative number.

int compare = s2.compareTo(s1);

Output: -2

compareTo method is a case-sensitive method. Ex. string Java will not be equivalent to Java.

String s1 = "Java";
String s2 = "java";
int compare = s1.compareTo(s2);

Output: -32

12. int compareToIgnoreCase(String s)

This method is the same as the above compareTo method but the basic difference is the compareToIgnoreCase is a case non-sensitive method. Ex. string Java will be equivalent to Java.

String s1 = "Java";
String s2 = "java";
int compare = s1.compareToIgnoreCase(s2);

Output: 0

13. boolean equals(String s)

This method checks the content of two strings. If the content matches then the method returns true else false.

String s1 = "Learn";
String s2 = "Java";
boolean bool = s1.equals(s2);

Output: false

This method is a case-sensitive method. Ex. string “Java” will not be equivalent to “java”.

String s1 = "Java";
String s2 = "java";
boolean bool = s1.equals(s2);

Output: false

14. boolean equalsIgnoreCase(String s)

This method is the same as the above equals method but the basic difference is the equalsIgnoreCase is a case non-sensitive method. Ex. string Java will be equivalent to Java.

String s1 = "Java";
String s2 = "java";
boolean bool = s1.equalsIgnoreCase(s2);

Output: true
package com.java.handson.strings;

public class StringUtils {

    public static void main(String[] args) {

        String s1 = "Learn";
        String s2 = "Java";
        int compare = s1.compareTo(s2);
        System.out.println("compareTo : "+compare);

        compare = s2.compareTo(s1);
        System.out.println("compareTo : "+compare);

        s1 = "Java";
        s2 = "java";
        compare = s1.compareTo(s2);
        System.out.println("compareTo : "+compare);

        s1 = "Java";
        s2 = "java";
        compare = s1.compareToIgnoreCase(s2);
        System.out.println("compareToIgnoreCase : "+compare);

        s1 = "Learn";
        s2 = "Java";
        boolean bool = s1.equals(s2);
        System.out.println("equals : "+bool);

        s1 = "Java";
        s2 = "java";
        bool = s1.equals(s2);
        System.out.println("equals : "+bool);

        s1 = "Java";
        s2 = "java";
        bool = s1.equalsIgnoreCase(s2);
        System.out.println("equalsIgnoreCase : "+bool);
    }
}
Output:
compareTo : 2
compareTo : -2
compareTo : -32
compareTo : 0
equals : false
equals : false
equalsIgnoreCase : true

15. String toUpperCase()

This method converts all characters of a string into upper case and it returns an upper case string.

String s1 = "Java";
String s2 = s1.toUpperCase();

Output: JAVA

16. String toLowerCase()

This method converts all characters of a string into lowercase and it returns a lowercase string.

String s1 = "Java";
String s2 = s1.toLowerCase();

Output: java

17. String trim()

This method removes the spaces from the start and end of a string. It will not remove spaces from the middle of the string.

For Ex. If we use a trim method on the ” Learn Java ” string then the spaces will be removed from start and end and the resultant string will be “Learn Java”.

String s1 = " Learn Java   ";
String s2 = s1.trim();

Output: Learn Java

18. String [ ] split(String delimiter)

This method splits a single string into a string array using a delimiter. The delimiter can be a single character or a regex expression.

String str = "Hello@How@are@you";
String[] arr = str.split("@");

In the above example “@” is a delimiter to split the string hence str gets split into an array like below.

arr[0] = "Hello"
arr[1] = "How"
arr[2] = "are"
arr[3] = "you"

19. String [ ] split(String delimiter, int limit)

This method splits a single string into a string array using a delimiter. The limit parameter decides the number of times the pattern will be applied and it affects the length of the resulting array.

String str = "Hello@How@are@you";
String[] arr = str.split("@", 2);

Output: {"Hello", "How@are@you"}
The last resultant string will contain the entire input beyond the delimiter.
String str = "Hello@How@are@you";
String[] arr = str.split("@", 5);

Output: {"Hello", "How, "are", "you"}
Here the limit is 5 but since the delimiter is present only 3 times in the string hence array created will be of length 4.
package com.java.handson.strings;

import java.util.Arrays;

public class StringUtils {

    public static void main(String[] args) {

        String s1 = "Java";
        String s2 = s1.toUpperCase();
        System.out.println("toUpperCase : "+s2);

        s1 = "Java";
        s2 = s1.toLowerCase();
        System.out.println("toLowerCase : "+s2);

        s1 = " Learn Java   ";
        s2 = s1.trim();
        System.out.println("trim : "+s2);

        String str = "Hello@How@are@you";
        String[] arr = str.split("@");
        System.out.println("split : "+ Arrays.toString(arr));

        str = "Hello@How@are@you";
        arr = str.split("@", 2);
        System.out.println("split : "+ Arrays.toString(arr));

        str = "Hello@How@are@you";
        arr = str.split("@", 5);
        System.out.println("split : "+ Arrays.toString(arr));
    }
}
Output:
toUpperCase : JAVA
toLowerCase : java
trim : Learn Java
split : [Hello, How, are, you]
split : [Hello, How@are@you]
split : [Hello, How, are, you]

We have covered most of the String class methods that will be used often. There are a few more methods present as part of a String class that you can check here https://docs.oracle.com/javase/8/docs/api/java/lang/String.html

So this is all about String in Java with proper examples. If you have any questions on this topic please raise them in the comments section. If you liked this article then please share this post with your friends and colleagues so that they can learn Java and its frameworks in more depth.

Leave a Comment

Latest Posts For java strings