In Java programming language, a string is nothing but a sequence of characters. It is the most widely used object. Java String class has many methods that are used for various manipulations. It is immutable, meaning, its value cannot be changed. A string is equivalent to an array of characters.
Table of Contents
Creating a string in Java
We can create a string using 2 different methods:
- Using string literal
- Using new keyword
Create a string using a string literal
This is the most direct way of creating a string in Java. We can create a string by enclosing the value in double-quotes. Here the variable “value” of type String holds the string named as “Java language”
String value = "Java language";
When we create a string literal, JVM first checks in the “string constant pool” if the string exists. If it does not exist, JVM creates a new string instance, else only a reference to the pooled instance will be returned. For example, in the below case, both string objects hold the same value. Hence only 1 object is created (i.e s1) and s2 will have the reference to s1. This means, irrespective of how many ever string variables we create with the same value, only 1 instance will be created in the string constant pool.
“String constant pool” is nothing but the special memory to hold the string objects.
String s1 = "Java language"; String s2 = "Java language";
Creating a string using the new keyword
When we want to have 2 different objects holding the same string value, then we create a string using the new keyword as described below. In this case, JVM creates 2 different string objects in a heap memory
String s1 = new String("Java"); String s2 = new String("Java");
String Methods Java
The java.lang.String class supports various methods which are used for different string manipulations as described below:
Method | 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 anotherstring) | Compares 2 strings based on the unicode value of the characters and returns negative value if it preceeds the argument string, else returns positive. The return value is 0 if both strings are equal | anotherstring - string to compare with the string object |
int compareToIgnoreCase(String anotherstring) | Similar to compareTo method except that it ignores the case. | anotherstring - string to compare with the string object |
String concat(String str) | Concatenates two string values | str - The string to concatenate with the string object value |
boolean contains(CharSequence c) | Checks if the string contains the specified character sequence and returns true if present | c - Character sequence to find in the string |
boolean contentEquals(CharSequence c) | Checks if the string contains the exact charactersequence and returns true if present | c - Character sequence to find in the string |
boolean contentEquals(StringBuffer sb) | Checks if the string contains the specified string buffer and returns true if present | sb - String buffer content |
boolean endsWith(String suffix) | Checks if the string ends with the specified suffix and returns true if present | suffix - the suffix to check in the string |
boolean equals(Object obj) | Checks the similarity of the string object with the object passed and returns true if equal | obj - The object to compare |
boolean equalsIgnoreCase(String str) | Compares two string irrespective by ignoring the case and returns true if both 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(String str) | 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 is the string is empty or contains only empty spaces | |
boolean isEmpty() | Returns true if the string is empty(i.e 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(String str) | Returns the index of the last occurrence of the specified substring in the string | str - the substring value present in the string |
int length() | Returns the length of the string | |
boolean matches(String regex) | Returns true if the string matches with the specified regular expression | regex - The regular expression to be checked |
String repeat(int count) | Concatenates the string based on the count | count - number of times to concatenate the input string |
String replace(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 be replaced |
String[] split(string regexp) | Splits the string based on the regular expression. It returns array | regexp - delimiter to split the string |
String[] split(String regexp, int limit) | Splits the string based on the regular expression and number of times it needs to be applied | regexp - delimiter to split the string limit - number of times the pattern has to be applied |
boolean startsWith(String prefix) | Checks if the given string starts with the specified prefix. Returns true if present | prefix - the prefix to check in the string |
boolean startsWith(String prefix, int tooffset) | Checks if the given string starts with the specified prefix based on the tooffset parameter.Returns true if present | prefix - the prefix to check in the string tooffset - the index from which needs to begin search |
String strip() | Returns a string with all whitespaces removed, both leading and trailing | |
String stripLeading() | Returns a substring of the string with all leading spaces removed | |
String stripTrailing() | Returns a substring of the string with all trailing spaces removed | |
CharSequence subSequence(int startIndex, int endIndex) | Returns a character sequence of the string based on start and end index | startIndex - the index from which the substring has to be retrieved endIndex - the index until which the substring has to be retrieved |
String subString(int startIndex) | Returns a substring of the string based on the start index | startIndex - the index from which the substring has 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 has to be retrieved endIndex - the index until which the substring has to be retrieved |
char[] to CharArray() | Converts the string to character array | |
String toLowerCase() | Converts all characters in the string to lowercase | |
String toLowerCase(Locale locale) | Converts all characters in the string to lowercase based on the locale rules | locale - the locale rules to be applied |
String toString() | Returns the string itself | |
String toUpperCase() | Converts all characters in the string to upper case | |
String toUpperCase(Locale locale) | Converts all characters in the string to upper case based on the locale rules | locale - the locale rules to be applied |
String trim() | Returns a string with all leading and trailing spaces removed | |
String formatString(String format, Object... args) | Returns a formatted string based on the format and arguments | format - format specifier args - arguments referenced by the format specifier |
String join(CharSequence delimiter, CharSequence... elements) | Joins the character sequence elements using the delimiter | delimiter - the delimiter to join elements - the string elements to join |
String valueOf(Boolean b) | Returns the string representation of the boolean argument. If true is passed, returns true | b - boolean value as true or false |
String valueOf(char c) | Returns string representation of the character argument | c - character |
String valueOf(char[] data) | Returns string representation of the character array argument | data - character array |
String valueOf(double d) | Returns string representation of the double argument | d - double value |
String valueOf(float f) | Returns string representation of the float argument | f - float value |
String valueOf(int i) | Returns string representation of the integer argument | i - integer value |
String valueIOf(long l) | Returns string representation of the long argument | l - long value |
String valueOf(Object obj) | Returns the string representation of the object argument | obj - object |
String valueOf(char[] data, int offset, int count) | Returns a string representation of the specific substring character array argument based on the offset and count | data - character array offset - start Index count - length of the substring |
Example: Java program to create a string from array characters
In the below example, we convert an array of characters to a string in Java using the new keyword.
public class StringDemo1 { public static void main(String[] args) { char[] c = {'j','a','v','a'}; String s = new String(c); System.out.println(s); } }
Output: java
Example: Using length(), charAt() and indexOf() methods
The below 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 : u The length of the input string is : 13 The index of letter 'v' is : 2
Example: Using compareTo(), contentEquals() and contains()
This example shows a comparison of 2 strings in Java
- compareTo() returns a positive integer here since the input string succeeds the argument string.
- compareToIgnoreCase() returns 0 since both strings are equal irrespective of the case.
- contains() returns true since the input string contains the argument string
- contentEquals() returns false since 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 : 7 Comparison of input string with argument ignoring case is : 0 Output of contains method: true Output of contentEquals method: false
Example: Using equals()
1st output is false since the case does not match even though the content is the same. 2nd output is true since content and case matches.
3rd output is false since both content 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: false true false
Example: Concatenation of strings
We can concatenate 2 strings in Java using concat() method of the Java String class. “+” is also used to concatenate 2 or more strings which are normally used in print statements. While concatenating 2 strings, space is not included in between the strings. In the below example, string s3 contains the concatenated value of s1 and s2 which is used along with a new string in the print statement.
We can also concatenate 2 strings in Java using the join() method. This will join the words passed in the argument with a delimiter specified.
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 today welcome,to,tutorialcup
Example: Java program to convert string between upper case and lower case
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 tutorialcup Convert to upper case: WELCOME TO TUTORIALCUP
Example: Using 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 tutorial ava tutor
Example: Using split and replace
Split is another most commonly used method of String in Java. In this example, we first split the input string using the delimiter ” “. Hence this prints each word separately. Next, we split based on the delimiter but specify limit as 2 which means it splits only into two string array values.
In the 1st example of replacing, we replace the individual character. In the next, we replace the character sequence.
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: Welcome to java programming Split output using delimiter and limit: Welcome to java programming Replace output with character: Welcome to Java programming Replace output with character sequence: Welcome to javascript programming
Example: Java Format string
We can format any type of data to a string using the format method. Here, we are using 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 Java Float value is 55.678900 Boolean value is true
Conclusion
In this tutorial, you have learned about String in Java, different ways of creating it, and different string methods along with examples.