English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, we will learn about Java String through examples, how to create it and its various methods.
In Java, a string is a sequence of characters. For example, "hello" is a string that contains the character sequence "h", "e", "l", "l", and "o".
Unlike other programming languages, strings in Java are not primitive types (such as int, char, etc.). Instead, all strings are objects of a predefined class named String. For example,
//Create a string String type = "java programming";
Here, we create a string named type. Here, we initialize the string with "java programming". In Java, we useEscape characters tell the compiler to escapeRepresents a string.
This string is an instance of the String class.
Note:All string variables are instances of the String class.
Java String provides various methods that allow us to perform different string operations. The following are some commonly used string methods.
Method | Description |
---|---|
concat() | Concatenates two strings together |
equals() | Compares the values of two strings |
charAt() | Returns the character at the specified position |
getBytes() | Converts the string to a byte array |
indexOf() | Returns the position of the specified character in the string |
length() | Returns the size of the specified string |
replace() | Replaces the specified old character with the specified new character |
substring() | Returns the substring of the string |
split() | Splits the string into a string array |
toLowerCase() | Convert the string to lowercase |
toUpperCase() | Convert the string to uppercase |
valueOf() | Returns the string representation of the specified data |
Let's take a few examples.
class Main { public static void main(String[] args) { //Creating a string String greet = "Hello! World"; + 第42段 //checks the string length System.out.println("The length of a string: " + greet.length()); } }
Output result
The string is: Hello! World The length of a string: 12
In the above example, we created a string named greet. Here, we used the length() method to get the size of the string.
class Main { public static void main(String[] args) { //Creating a string String greet = "Hello! "; System.out.println("The first string: ") + 第42段 String name = "World"; System.out.println("The second string: ") + name); //Concatenate two strings String joinedString = greet.concat(name); System.out.println("The concatenated string: ") + joinedString); } }
Output result
The first string: Hello! The second string: World The concatenated string: Hello! World
In the above example, we created2strings named greet and name.
Here, we used the concat() method to concatenate strings. Therefore, we get a new string named joinedString.
In Java, we can also use + operator to concatenate two strings.
class Main { public static void main(String[] args) { //Creating a string String greet = "Hello! "; System.out.println("The first string: ") + 第42段 String name = "World"; System.out.println("The second string: ") + name); //Concatenate two strings String joinedString = greet + name; System.out.println("The concatenated string: ") + joinedString); } }
Output result
The first string: Hello! The second string: World The concatenated string: Hello! World
Here, we use+operator to concatenate two strings.
class Main { public static void main(String[] args) { //Create string s String first = "java programming"; String second = "java programming"; String third = "python programming"; //Compare the first string with the second string boolean result1 = first.equals(second); System.out.println("The first and second strings are equal: ") + result1); //Compare the first and third strings boolean result2 = first.equals(third); System.out.println("The first and third strings are equal: ") + result2); } }
Output result
The first and second strings are equal: true The first and third strings are not equal: false
In the above example, we used the equals() method to compare the values of two strings.
If the two strings are the same, this method returns true; otherwise, it returns false.
NoteWe can also use the == operator and the compareTo() method to compare strings.2a string.
class Main { public static void main(String[] args) { //Create a string using the string literal String greet = "Hello! World"; + 第42段 //returns position3at position System.out.println("Position3at position: " + greet.charAt(3)); //returns position7at position System.out.println("Position7at position: " + greet.charAt(7)); } }
Output result
The string is: Hello! World Position3at position: l Position7at position: W
In the above example, we used the charAt() method to access the character at a specified position.
class Main { public static void main(String[] args) { //Create a string using the new keyword String example = new String("Hello! World"); //Return the substring 'World' System.out.println("Using subString(): "); + example.substring(7)); //Convert the string to lowercase System.out.println("Using toLowerCase(): "); + example.toLowerCase()); //Convert the string to uppercase System.out.println("Using toUpperCase(): "); + example.toUpperCase()); //Replace character '!' with 'o' System.out.println("Using replace(): "); + example.replace('!', 'o')); } }
Output result
Using subString(): World Using toLowerCase(): hello! world Using toUpperCase(): HELLO! WORLD Using replace(): Helloo World
In the above example, we created a string named 'example' using the new keyword.
Here,
The substring() method returns the string 'World'
The toLowerCase() method converts a string to lowercase
The toUpperCase() method converts a string to uppercase
replace() method replaces the character '!' with 'o'.
Strings in Java useEscape characters tell the compiler to escapeFor example,
//Creating a string represent.
String example = "This\"is\"a\"string";Escape characters tell the compiler to escapeNow, if we want to include
//. For example, a string containing double quotes
String example = "This\"is\"the\"String"\"class";Escape characters tell the compiler to escapeThis will cause an error. This is because using
to represent strings. Therefore, the compiler treats "This is the " as a string.Escape characters tell the compiler to escapeTo solve this problem, escape characters (\) are used in Java. Now we can include
//, as shown below: Using escape characters
String example = "This\"is\"the\"String\"class.";Escape characters tell the compiler to escapeDouble quotes
Java strings are immutableIn Java, creating a string means creating an object of the string class.That's why strings are calledImmutableReason.
To understand it more deeply, let's look at an example:
//Creating a string String example = "Hello!";
Here, we create a string object "Hello!". After creation, we cannot change it.
Now let's assume we want to change the string.
//Adding another string to this string example = example.concat(" World");
Here, we try to add a new string to the previous string.
Since strings areImmutable, it should cause an error. But it's fine.
It now seems that we can change the string. However, that is not the case. Let's see what actually happens here.
We have a string "Hello!" referenced by a variable named example. Now, when executing the above code,
The JVM accepts the string "Hello!"
Appending the string "World" to it
This will create a new string "Hello! World"
The variable example now points to the new string
The previous string "Hello!" remains unchanged
Note: Each time a new string is created and referenced by a variable.
So far, we have created strings similar to basic types in Java. However, since strings in Java are objects, we can also create them using the new keyword. For example,
//Creating a string using the new keyword String name = new String("java string");
In the above example, we used the new keyword and the constructor String() to create a string.
The String class provides various other constructors to create strings.
Now, let's see how the process of creating a string is different from the previous process.
Now that we know how to create strings using string literals and the new keyword, let's see what the main differences between them are.
In Java, the JVM maintains a string pool to store all strings in memory. The string pool helps to reuse strings.
When creating a string using string literals, the value of the string is provided directly. Therefore, the compiler first checks the string pool to see if the string already exists.
if the string already existsthen no new string is created. Instead, the new reference points to the existing string.
if the string does not existthen a new string is created.
However, when using the new keyword to create a string, the value of the string is not provided directly. Therefore, a new string is always created.