Strings in Java: A Comprehensive Guide
In the Java programming language, a string is nothing more than a sequence of characters. It is the most used object. The Java String class has many methods that are used for various manipulations. It is immutable, that is, its value cannot be changed. A string is equivalent to an array of characters.
Create a string in Java
We can create a string using 2 different methods:
- Using a literal string
- Use a new keyword
Create a string using a string literal
This is the most direct way to create a beautiful one in Java. We can create a string by enscasing the value in quotation marks. Here, the string “value” variable contains the string named “Java language”String value = “Java language”;
When we create a string literal, JVM first checks the “string constant pool” to see if the string exists. If it does not exist, the JVM creates a new string instance, otherwise only a reference to the pooled instance will be returned. For example, in the case below, both string objects have the same value. Therefore, only one object is created (that is, s1) and s1 will have the reference to s2. This means that no matter how many string variables we create with the same value, only one instance will be created in the string constant pool.
“String constant pool” is nothing but the special memory to hold string objects.https://57362150bd7f309b09b86e21f96387a8.safeframe.googlesyndication.com/safeframe/1-0-38/html/container.htmlString s1 = “Java language”; String s2 = “Java language”;
Create a string using the new keyword
When we want to have 2 different objects containing the same string value, we create a string using the Nine (ve) keyword as described below. In this case, JVM creates 2 different string objects in heap memoryString s1 = new String(“Java”);String s2 = new String(“Java”);
Java String Methods
The java.lang.String class supports various methods that are used for different string manipulations as described below:
delivery | description | parameters |
---|---|---|
char charAt (int index) | Returns the character at the specified index of the input string | index – the index value of the string |
int codePointAt (int index) | Returns the unicode value of the character at the specified index | index – the index value of the string |
int codePointBefore (int index) | Returns the unicode value of the character present before the specified index | index – the index value of the string |
int compareTo (string anothertring) | Compares 2 strings based on the unicode value of the characters and returns a negative value if it precedes the argument string, otherwise returns positive. The return value is 0 if the two strings are equal | anotherstring – string to compare with string object |
int compareToIgnoreCase (string anothertring) | Similar to the compareTo method except that it ignores case. | anotherstring – string to compare with string object |
Concat String (String String) | Concatenates two string values | str – The string to concatenate with the value of the string object |
boolean contains (CharSequence c) | Checks whether the string contains the specified character sequence and returns true if present | c – Sequence of characters to search for in the string |
boolean contentEquals (CharSequence c) | Checks whether the string contains the exact character sequence and returns true if present | c – Sequence of characters to search for in the string |
boolean contentEquals (StringBuffer sb) | Checks whether the string contains the specified string buffer and returns true if present | sb – String buffer contents |
boolean endsWith (string suffix) | Checks whether the string ends with the specified suffix and returns true if present | suffix – the suffix to save in the string |
Boolean is equal to (Object obj) | Checks the similarity of the string object with the object passed in and returns true if equal | obj – The object to compare |
boolean equalsIgnoreCase (string) | Compares two strings independently ignoring case and returns true if the two strings are equal | str – The string to compare |
int indexOf (int ch) | Returns the index of the first occurrence of the specified Unicode character in the string | ch – unicode value of the character |
int indexOf (str string) | Returns the index of the first occurrence of the specified substring in the string | str – the substring value present in the string |
Boolean isBlank () | Returns true if the string is empty or contains only blank spaces | |
Boolean isEmpty () | Returns true if the string is empty (that is, the length is 0) | |
int lastindexOf (int ch) | Returns the index of the last occurrence of the specified Unicode character in the string | ch – unicode value of the character |
int lastindexOf (str string) | Returns the index of the last occurrence of the specified substring in the string | str – the substring value present in the string |
length int () | Returns the length of the string | |
Boolean matches (String regex) | Returns true if the string matches the specified regular expression | regex – The regular expression to check |
String repetition (integer) | Concatenates the string based on the number | count – number of times to concatenate the input string |
Replace string (char oldchar, char newchar) | Returns the new string by replacing all occurrences of the character with the new character | oldchar – character to replace newchar – character to replace |
String [] split (string regular expression) | Divides the string based on the regular expression. It returns an array | regexp – delimiter to divide the string |
String [] split (string regular expression, int limit) | Divides the string based on the regular expression and the number of times it should be applied | regexp – delimiter to divide the limit string – number of times the pattern should be applied |
boolean startsWith (string prefix) | Checks whether the given string begins with the specified prefix. Returns true if present | prefix – the prefix to register in the string |
boolean startsWith (String prefix, int tooffset) | Checks whether the given string begins with the prefix specified based on the tooffset parameter. | prefix – the prefix to be saved in the tooffset string – the index from which to start the search |
Twine strip () | Returns a string with all spaces removed, both start and end | |
ChainLeading Band () | Returns a substring of the string with all leading spaces removed | |
Chain band | Returns a substring of the string with all trailing spaces removed | |
CharSequence subSequence (int startIndex, int endIndex) | Returns a sequence of characters in the string based on the start and end index | startIndex – the index from which the substring is to be retrieved endIndex – the index up to which the substring is to be retrieved |
String subString (int startIndex) | Returns a substring of the string based on the starting index | startIndex – the index from which the substring is to be retrieved |
String subString(int startIndex, int endIndex) | Returns a substring of the string based on the start and end index | startIndex – the index from which the substring is to be retrieved endIndex – the index up to which the substring is to be retrieved |
char [] to CharArray() | Converts the string to a character array | |
String toLowerCase() | Converts all characters in the string to lowercase | |
String toLowerCase (locale) | Converts all characters in the string to lowercase based on local rules | locale – the local rules to apply |
String toString () | Returns the string itself | |
ToUpperCase string () | Converts all characters in the string to uppercase | |
String toUpperCase (locale) | Converts all characters in the string to uppercase based on local rules | locale – the local rules to apply |
Chain cut () | Returns a string with all leading and trailing spaces removed | |
String formatString (string format, object … args) | Returns a formatted string based on format and arguments | format – format specifier args – arguments referenced by the format specifier |
Jointure de chaîne (délimiteur CharSequence, éléments CharSequence …) | Joint les éléments de la séquence de caractères à l’aide du délimiteur | delimiter – le délimiteur à joindre elements – les éléments de chaîne à joindre |
Chaîne valueOf (booléen b) | Renvoie la représentation sous forme de chaîne de l’argument booléen. Si true est passé, renvoie true | b – valeur booléenne vraie ou fausse |
Chaîne valueOf (char c) | Renvoie une représentation sous forme de chaîne de l’argument de caractère | c – caractère |
Chaîne valueOf (char [] data) | Renvoie une représentation sous forme de chaîne de l’argument du tableau de caractères | data – tableau de caractères |
Chaîne valueOf (double d) | Renvoie une représentation sous forme de chaîne de l’argument double | d – valeur double |
Chaîne valueOf (float f) | Renvoie une représentation sous forme de chaîne de l’argument float | f – valeur flottante |
Chaîne valueOf (int i) | Renvoie une représentation sous forme de chaîne de l’argument entier | i – valeur entière |
Valeur de chaîne IOf (long l) | Renvoie une représentation sous forme de chaîne de l’argument long | l – valeur longue |
Chaîne valueOf (Object obj) | Renvoie la représentation sous forme de chaîne de l’argument objet | obj – objet |
Chaîne valueOf (char [] data, int offset, int count) | Renvoie une représentation sous forme de chaîne de l’argument de tableau de caractères de sous-chaîne spécifique en fonction du décalage et du nombre | data – tableau de caractères offset – index de début count – longueur de la sous-chaîne |
Example: Using the length(), charAt(), and indexOf() methods
The following example shows you how to retrieve a character at a particular index, get the length of a string, and retrieve the index of a particular character.public class StringDemo2{ public static void main(String[] args){ String s1 = new String(“Java tutorial”);System. out. println(“The character at index 6 is : ” + s1. charAt(6));System. out. println(“The length of the input string is : ” + s1. length());System. out. println(“The index of letter ‘v’ is : ” + s1. indexOf(‘v’)); }}Output:The character at index 6 is : uThe length of the input string is : 13The index of letter ‘v’ is : 2
Example: Using compareTo(), contentEquals(), and contains()
This example shows a comparison of 2 strings in Java
- compareTo() here returns a positive integer since the input string succeeds the argument string.
- compareToIgnoreCase() returns 0 because the two strings are equal regardless of case.
- contains() returns true because the input string contains the argument string
- contentEquals() returns false because the input string does not contain the exact argument string.
public class StringDemo2{ public static void main(String[] args){ String s1 = new String(“Java tutorial”);System. out. println(“Comparison of input string with argument is : ” + s1. compareTo(“C++”));System. out. println(“Comparison of input string with argument ignoring case is : ” + s1. compareToIgnoreCase(“JAVA TUTORIAL”));System. out. println(“Output of contains method: ” + s1. contains(“tutorial”));System. out. println(“Output of contentEquals method: ” + s1. contentEquals(“Java”)); }}Output:Comparison of input string with argument is : 7Comparison of input string with argument ignoring case is : 0Output of contains method: trueOutput of contentEquals method: false
Example: Using equals ()
The first output is false because the case does not match even if the content is the same. The second output is true since the content and case match.
The third output is false because the two contents are different.public class StringDemo3{ public static void main(String[] args){ String s1 = “java tutorial”; String s2 = “Java Tutorial”; String s3 = “java tutorial”; String s4 = “Tutorial cup”;System. out. println(s1. equals(s2));System. out. println(s1. equals(s3));System. out. println(s1. equals(s4)); }}Output:falsetruefalse
Example: String Concatenation
One can concatenate 2 strings in Java using concat() method of the Java String Class. “+” Is also used to concatenate 2 or more strings that are normally used in print instructions. When concatenating 2 strings, space is not included between the strings. In the example below, the string s3 contains the concatenated value of s1 and s2 that is used with a new string in the print statement.
We can also concatenate 2 strings in Java using the join() method. This will join the passed words in the argument with a specified delimiter.public class StringConcat{ public static void main(String[] args){ String s1 = “Hello,”; String s2 = “how are you”; String s3 = s1. concat(s2);System. out. println(s3 + ” today”);System. out. println(s1. join(“,”, “welcome”,”to”,”tutorialcup”)); }}Output:Hello,how are you todaywelcome,to,tutorialcup
Feel free to get your Java homework done by someone who can provide expert help online.
Example: Java program to convert a string between uppercase and lowercase
public class StringCase{ public static void main(String[] args){ String s1 = “Welcome to tutorialcup”;System. out. println(“Convert to lower case: ” + s1. toLowerCase());System. out. println(“Convert to upper case: ” + s1. toUpperCase()); }}Output:Convert to lower case: welcome to tutorialcupConvert to upper case: WELCOME TO TUTORIALCUP
Example: Using a Substring in Java
We can retrieve part of the string in Java using the substring method. The index value starts at 0.public class StringDemo3{ public static void main(String[] args){ String s1 = “java tutorial”;System. out. println(s1. substring(3));System. out. println(s1. substring(1, 10)); }}Output:a tutorialava tutor
Example: Using Division and Replacement
Split is another method of String most commonly used in Java. In this example, we first split the input string using the “” delimiter. Therefore, this prints each word separately. Next, we divide according to the delimiter but specify the limit to 2, which means that it only divides into two string array values.
In the first replacement example, we replace the individual character. In the next one, we replace the sequence of characters.public class StringDemo4{ public static void main(String[] args){ String str1 = “Welcome to java programming”;System. out. println(“Split output using delimiter:”); Split using only delimiter String[] arrval = str1. split(” “); for(int i=0;i<arrval. length;i++){System. out. println(arrval[i]); }System. out. println(“\nSplit output using delimiter and limit:”); Split using delimiter and limit String[] arrval2 = str1. split(” “, 2); for(int i=0;i<arrval2. length;i++){System. out. println(arrval2[i]); } System. out. println(“\nReplace output with character:”); Replace character String str2 = str1. replace(‘j’, ‘J’);System. out. println(str2);System. out. println(“\nReplace output with character sequence:”); String str3 = str1. replace(“java”, “javascript”);System. out. println(str3); }}Output:Split output using delimiter:WelcometoJavaprogrammingSplit output using delimiter and limit:Welcometo java programmingReplace output with character:Welcome to Java programmingReplace output with character sequence:Welcome to javascript programming
Example: Java format string
We can format any data type to a string using the format method. Here we use string (“%s”), float (%f”), and boolean (“%b”) as examples.public class StringFormat{ public static void main(String[] args){ String str = “Java”; String formatstring1 = String. format(“Programming language is %s”,str); String formatstring2 = String. format(“Float value is %f”, 55.6789); String formatstring3 = String. format(“Boolean value is %b”, true);System. out. println(formatstring1);System. out. println(formatstring2);System. out. println(formatstring3); }}Output:Programming language is JavaFloat value is 55.678900Boolean value is true
conclusion
In this tutorial, you learned about String in Java, different ways to create it, and different string methods as well as example