In this tutorial, we will learn about Java strings, how to create them, and the various methods of the String class.
A string in Java is a sequence of characters. For example, “Java” is a string made up of the characters ‘J’, ‘a’, ‘v’, ‘a’.
In Java, we use double quotes to represent a string. As an example:
// create a string String Sample = “Developers Dome”; |
In this case, we’ve created a string variable called Sample. “Developers Dome” is used to initialize the variable.
Example: In Java, create a String.
class Main { public static void main(String[] args) { // create strings String sample = "Kotlin"; String sample1 = "Ruby"; String sample2 = "Java"; // print strings System.out.println(sample); System.out.println(sample1); System.out.println(sample2); } }
Output:
Kotlin Ruby Java |
In the preceding example, we created three strings marked sample, sample1, and sample2. In this case, we are directly creating strings as primitive types.
Strings are not primitive types in Java (like int, char, etc). On the other hand, all the strings are objects of a predefined class called String. |
Contents
How to create a string object?
String objects can be created in two ways:
- As a string literal
- By using a new keyword
1: String Literal
Double quotes are used to create a Java String literal.
Example:
String sample=”Developers Dome”; |
When you create a string literal, the JVM first checks the “string constant pool.” If the string is already in the pool, a pointer to the pooled instance is returned. If the string does not already exist in the pool, a new string instance is created and added to it.
String literals are used in Java to improve Java’s memory efficiency |
2: By new keyword
The literal “DevelopersDome” will be placed in the string constant pool, and JVM will create a new string object in normal (non-pool) heap memory. The variable will be used to refer to a heap object (non-pool).
String sample =new String(“Welcome”); |
Example: Java String Example
public class Sample{ public static void main(String args[]){ String x="java";//creating string by Java string literal char ch[]={'s','t','r','i','n','g'}; String y=new String(ch); String z=new String("DevelopersDome");//Java string by new keyword System.out.println(x); System.out.println(y); System.out.println(z); }}
Output:
Java String DevelopersDome |
Methods of Java String
Aside from the methods mentioned above, Java includes a number of string methods. Here are a few examples of these methods:
Methods | Description |
---|---|
contains() | determines whether or not the string contains a substring |
substring() | returns the string’s substring |
replace() | substitutes the specified new character for the specified old character |
replaceAll() | all substrings that match the regex pattern are replaced |
replaceFirst() | replace the first substring that matches |
charAt() | returns the character that can be found in the specified location |
getBytes() | converts the string to a bytes array |
indexOf() | The position of the specified character in the string is returned. |
compareTo() | compares two strings in the order of their appearance in the dictionary |
compareToIgnoreCase() | compares two strings while disregarding case differences |
trim() | removes any whitespace at the beginning and end of a sentence |
format() | returns a formatted string |
split() | divides a string into an array of strings |
toLowerCase() | converts the string’s case to lowercase |
toUpperCase() | converts the string’s case to uppercase |
valueOf() | The string representation of the specified argument is returned. |
toCharArray() | transforms a string into a char array |
matches() | determines if the string matches the regex |
startsWith() | determines if the string starts with the specified string |
endsWith() | determines if the string ends with the given string. |
isEmpty() | determines if a string is empty or not |
intern() | returns the string’s canonical representation |
contentEquals() | determines if the string is equal to the charSequence |
hashCode() | returns the string’s hash code |
Strings in Java: immutable
String objects are immutable in Java. Immutable simply means that it cannot be changed or modified. The data or state of a String object can’t be changed once it’s been created, instead, a new String object is created.
- Consider the following scenario to gain a better understanding:
// Create String String sample = “DevelopersDome”; |
We’ve created a string variable called example in this case. The string ” DevelopersDome” is stored in the variable.
Let’s say we want to modify the string.
// add another string “Hello” to the previous string example sample = sample .concat(” Hello”); |
- The concat() method is being used to add another string Hello to the previous string.
- It appears that we have the ability to change the previous string’s value. This, however, is not the case. Let’s take a look at what’s going on here.
- JVM takes the first string “DevelopesDome” and adds “Hello” to it to make a new string. It then assigns the new string “DevelopersDome Hello” to the sample variable, leaving the first string “DevelopersDome” unchanged.
Escape character: Java Strings
What is escape character?
When a character in Java is preceded by a backslash (), it is referred to as a Java escape sequence or escape characters. It could contain letters, numerals, punctuation marks, and so on. These characters are interpreted by the Java compiler as a single character that gives the compiler a specific meaning.
Let’s say we need to use double quotes within a string.
// include double quote String sample = “It is a “Hello” class”; |
- Because double quotes are used to represent strings, the compiler will treat “It is a” as a string. As a result, the code above will result in an error.
- In Java, we use the escape character to solve this problem. As an example:
// using the escape character String sample = “It is a \”Hello\” class.”; |
Java String Operations
Java String has a number of methods for performing various operations on strings. We’ll take a look at some of the most common string operations.
1: Join Two Java Strings
The concat() method in Java can be used to join two strings. As an example:
class Main { public static void main(String[] args) { // first string String demo1 = "Developers"; System.out.println("First String: " + demo1); // second string String demo2 = "Dome"; System.out.println("Second String: " + demo2); // join two strings String add = demo1.concat(demo2); System.out.println("Add String: " + add); } }
Output:
First String: Developers Second String: Dome Add String: DevelopersDome |
2. Get length of a String
The length() method of the String is used to determine the length of a string. As an example:
class Main { public static void main(String[] args) { // create string String sample = "Hello World"; System.out.println("String: " + sample); // length of sample int length = sample.length(); System.out.println("Length is: " + length); } }
Output:
String: Hello World Length: 11 |
3: Reverse a String
reverse a string in java,reverse a string in java,reverse a string in java,reverse a string in java,reverse a string in java,reverse a string in java,reverse a string in java, java string length,
In this example, we will reverse a string in java:
public class ReverseString { public static String reverseString(String str){ char ch[]=str.toCharArray(); String rev=""; for(int i=ch.length-1;i>=0;i--){ rev+=ch[i]; } return rev; } } public class sample { public static void main(String[] args) { System.out.println(ReverseString.reverseString("DevelopersDome")); System.out.println(ReverseString.reverseString("Hello EveryOne")); } }
Output:
emoDsrepoleveD enOyrevE olleh |
You might like:
Java Object and Java Class with Example
We hope that this article will assist you in understanding all about Java String. We have concentrated on making a basic, meaningful, and easy-to-learn guide to the concepts. Still, if you have any problems regarding this, please post them in the comment section, and we will be glad to assist you.