Last Updated: 26 June, 2022
A String is an immutable and final class in Java. It was introduced in the JDK 1.0 version and defined in the java.lang package.
Java String is an object that allows us to store a sequence of characters. A string object may contain any type of data, such as alphanumeric, special characters, blank spaces, etc., values enclosed in double quotes.
For example, "Core Java" is a string containing a sequence of characters 'C', 'o', 'r', 'e', 'J', 'a', 'v' and 'a'.
Strings are immutable in Java which means their values cannot be changed once they are created; if we modify the string, the JVM will create a new object.
String Class Description
public final class String
extends Object
implements Serializable, Comparable<String>, CharSequence
A Java String literal is created by using double quotes.
For example:
String str = “Hello Java”;
The "new" keyword is used to create a Java String.
For example:
String str = new String(“Hello Java”);
Output
str1 value: Hello
str2 value: Hello Java
str3 value: Hello
s1 value: Java World
s2 value: Hello Java
When we create a String by literal, the object is always created inside the String pool, whereas if we create a string object using the 'new' keyword, it will be created inside the heap memory area.
A Java String constant pool is a special memory area that is created inside the heap memory. This constant pool is specially designed to store a collection of unique string objects. When a user creates a String using literals, JVM first checks the String pool to see if another String with the same value already exists. If found, it just returns the reference to that String object; otherwise, it creates a new String object with the given value and stores it in the String pool.
When a string is created with the "new" keyword, the JVM creates both the string object in heap memory and the literal, which is placed in the string constant pool.
The idea behind the string pool is to make Java more memory efficient.
Let's understand the above concept through the pictorial representation:
public String() : Initializes a newly created String object.
public String(String original) : Initializes a newly created String object so that it represents the same sequence of characters as the argument.
public String(char[] value) : Allocates a new String so that it represents the sequence of characters currently contained in the character array argument.
public String(char[] value, int offset, int count) : Allocates a new String that contains characters from a subarray of the character array argument. The offset argument is the index of the first character of the subarray and the count argument specifies the length of the subarray.
public String(int[] codePoints, int offset, int count) : Allocates a new String that contains characters from a subarray of the Unicode code point array argument. The offset argument is the index of the first code point of the subarray and the count argument specifies the length of the subarray.
public String(byte[] bytes, int offset, int length, String charsetName) : Constructs a new String by decoding the specified subarray of bytes using the specified charset. The length of the new String is a function of the charset, and hence may not be equal to the length of the subarray.
public String(byte[] bytes, int offset, int length, Charset charset) : Constructs a new String by decoding the specified subarray of bytes using the specified charset. The length of the new String is a function of the charset, and hence may not be equal to the length of the subarray.
public String(byte[] bytes, String charsetName) : Constructs a new String by decoding the specified array of bytes using the specified charset. The length of the new String is a function of the charset, and hence may not be equal to the length of the byte array.
public String(byte[] bytes, Charset charset) : Constructs a new String by decoding the specified array of bytes using the specified charset. The length of the new String is a function of the charset, and hence may not be equal to the length of the byte array.
public String(byte[] bytes, int offset, int length) : Constructs a new String by decoding the specified subarray of bytes using the platform's default charset. The length of the new String is a function of the charset, and hence may not be equal to the length of the subarray.
public String(byte[] bytes) : Constructs a new String by decoding the specified array of bytes.
public String(StringBuffer buffer) : Allocates a new string from string buffer.
public String(StringBuilder builder) : Allocates a new string from string builder.
char charAt(int index) :
Returns the char value at the specified index. An index ranges from 0 to length() - 1.
public int length() :
Returns the length of this string.
public boolean isEmpty() :
Returns true if length() is 0, otherwise false.
public int codePointAt(int index) :
Returns the character (Unicode code point) at the specified index. The index refers to char values (Unicode code units) and ranges from 0 to length() - 1.
public int codePointBefore(int index) :
Returns the character (Unicode code point) before the specified index. The index refers to char values (Unicode code units) and ranges from 1 to length.
public int codePointCount(int beginIndex, int endIndex) :
Returns the number of Unicode code points in the specified text range of this String. The text range begins at the specified beginIndex and extends to the char at index endIndex - 1.
public int offsetByCodePoints(int index, int codePointOffset) :
Returns the index within this String that is offset from the given index by codePointOffset code points. Unpaired surrogates within the text range given by index and codePointOffset count as one code point each.
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) :
Copies characters from this string into the destination character array.
public byte[] getBytes(String charsetName) :
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
public byte[] getBytes(Charset charset) :
Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.
public byte[] getBytes() :
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
public boolean equals(Object anObject) :
Returns true if the given object represents a String equivalent to this string, false otherwise.
public boolean contentEquals(StringBuffer sb) :
Returns true if this String represents the same sequence of characters as the specified StringBuffer, false otherwise.
public boolean contentEquals(CharSequence cs) :
Returns true if this String represents the same sequence of char values as the specified sequence, false otherwise.
public boolean equalsIgnoreCase(String anotherString) :
Returns true if the argument is not null and it represents an equivalent String ignoring case; false otherwise.
public int compareTo(String anotherString) :
Returns the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.
public int compareToIgnoreCase(String str) :
Returns a negative integer, zero, or a positive integer as the specified String is greater than, equal to, or less than this String, ignoring case considerations.
public boolean regionMatches(int toffset, String other, int ooffset, int len) :
Returns true if the specified subregion of this string exactly matches the specified subregion of the string argument; false otherwise.
public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) :
Returns true if the specified subregion of this string matches the specified subregion of the string argument; false otherwise. Whether the matching is exact or case insensitive depends on the ignoreCase argument.
public boolean startsWith(String prefix, int toffset) :
Returns true if the character sequence represented by the argument is a prefix of the substring of this object starting at index toffset; false otherwise.
public boolean startsWith(String prefix) :
Returns true if the character sequence represented by the argument is a prefix of the character sequence represented by this string; false otherwise.
public boolean endsWith(String suffix) :
Returns true if the character sequence represented by the argument is a suffix of the character sequence represented by this object; false otherwise.
public int hashCode() :
Returns a integer hash code value for the string.
public int indexOf(int ch) :
Returns the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.
public int indexOf(int ch, int fromIndex) :
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
public int lastIndexOf(int ch) :
Returns the index of the last occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.
public int lastIndexOf(int ch, int fromIndex) :
Returns the index of the last occurrence of the character in the character sequence represented by this object that is less than or equal to fromIndex, or -1 if the character does not occur before that point.
public int indexOf(String str) :
Returns the index of the first occurrence of the specified substring, or -1 if there is no such occurrence.
public int indexOf(String str, int fromIndex) :
Returns the index of the first occurrence of the specified substring, starting at the specified index, or -1 if there is no such occurrence.
public int lastIndexOf(String str) :
Returns the index of the last occurrence of the specified substring, or -1 if there is no such occurrence.
public int lastIndexOf(String str, int fromIndex) :
Returns the index of the last occurrence of the specified substring, searching backward from the specified index, or -1 if there is no such occurrence.
public String substring(int beginIndex) :
Returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.
public String substring(int beginIndex, int endIndex) :
Returns a string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
public CharSequence subSequence(int beginIndex, int endIndex) :
Returns a character sequence that is a subsequence of this sequence.
public String concat(String str) :
Returns a string that represents the concatenation of this object's characters followed by the string argument's characters.
public String replace(char oldChar, char newChar) :
Returns a string resulting from replacing all occurrences of oldChar in this string with newChar.
public boolean matches(String regex) :
Returns true if, and only if, this string matches the given regular expression.
public boolean contains(CharSequence s) :
Returns true if and only if this string contains the specified sequence of char values.
public String replaceFirst(String regex, String replacement) :
Replaces the first substring of this string that matches the given regular expression with the given replacement.
public String replaceAll(String regex, String replacement) :
Replaces each substring of this string that matches the given regular expression with the given replacement.
public String replace(CharSequence target, CharSequence replacement) :
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. The replacement proceeds from the beginning of the string to the end.
public String[] split(String regex, int limit) :
Splits this string around matches of the given regular expression.
public String[] split(String regex) :
Splits this string around matches of the given regular expression.
public static String join(CharSequence delimiter, CharSequence... elements) :
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) :
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
public String toLowerCase(Locale locale) :
Converts all of the characters in this String to lower case using the rules of the given Locale.
public String toLowerCase() :
Converts all of the characters in this String to lower case using the rules of the default locale.
public String toUpperCase(Locale locale) :
Converts all of the characters in this String to upper case using the rules of the given Locale.
public String toUpperCase() :
Converts all of the characters in this String to upper case using the rules of the default locale.
public String trim() :
Returns a string whose value is this string, with all leading and trailing space removed, or this string if it has no leading or trailing space.
public String strip() :
Returns a string whose value is this string, with all leading and trailing white space removed
public String stripLeading() :
Returns a string whose value is this string, with all leading white space removed.
public String stripTrailing() :
Returns a string whose value is this string, with all trailing white space removed.
public boolean isBlank() :
Returns true if the string is empty or contains only white space codepoints, otherwise false.
public Stream
Returns a stream of lines extracted from this string, separated by line terminators.
public String toString() :
This object (which is already a string!) is itself returned.
public IntStream chars() :
Returns an IntStream of char values from this sequence.
public IntStream codePoints() :
Returns an IntStream of Unicode code points from this sequence.
public char[] toCharArray() :
Converts this string to a new character array.
public static String format(String format, Object... args) :
Returns a formatted string using the specified format string and arguments.
public static String format(Locale l,String format,Object... args):
Returns a formatted string using the specified locale, format string, and arguments.
public static String valueOf(Object obj) :
Returns the string representation of the Object argument.
public static String valueOf(char[] data) :
Returns a String that contains the characters of the character array.
public static String valueOf(char[] data, int offset, int count) :
Returns the string representation of a specific subarray of the char array argument.
public static String copyValueOf(char[] data,int offset,int count):
Returns a String that contains the characters of the specified subarray of the character array.
public static String copyValueOf(char[] data) :
Equivalent to valueOf(char[]). Returns a String that contains the characters of the character array.
public static String valueOf(boolean b) :
Returns the string representation of the boolean argument.
public static String valueOf(char c) :
Returns the string representation of the char argument.
public static String valueOf(int i) :
Returns the string representation of the int argument.
public static String valueOf(long l) :
Returns the string representation of the long argument.
public static String valueOf(float f) :
Returns the string representation of the float argument.
public static String valueOf(double d) :
Returns the string representation of the double argument.
public String intern() :
Returns a canonical representation for the string object.
public String repeat(int count) :
Returns a string whose value is the concatenation of this string repeated count times.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com
Is String a primitive or derived type in Java?
In Java, String is derived data types.
What is Mutable and Immutable in Java?
Ans. In Java, objects are either mutable or immutable, it depends on how the class has been implemented.
Mutable: A mutable object's state can be changed once created that means an object's values can be changed after initialization. When we make a change to an existing mutable object, the JVM will not create any new objects.
Mutable classes are StringBuffer, StringBuilder, ArrayList, Date, etc.
Immutable: An object is considered immutable if its state cannot change once it is created. When we make a change to existing immutable objects, a new object will be created by the JVM every time. Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state.
Immutable classes are String, all wrapper classes, BigInteger, BigDecimal, etc.
How to Create an immutable class in Java?
Ans. These are the following steps we need to follow while writing the immutable class:
What is the difference between String and StringBuffer in Java?
Ans. String and StringBuffer are final classes of the java.lang package and are used to store a sequence of characters. There are many differences between them. Let's look at the given table:
String | StringBuffer |
---|---|
A string is an immutable class, which means its values cannot be changed once created. If we modify the string, the JVM will create another object. | A StringBuffer is a mutable class. An object can be changed once it is created. |
Strings can be created in two ways: 1. by string literal 2. by using a new keyword | StringBuffer can be created only one way: by a new keyword. |
In concatenation operations, String is slow and consumes more memory because it creates a new instance every time. | whereas StringBuffer is fast and consumes less memory. |
String uses a String Constant Pool and Heap Memory for storing the string object. | The StringBuffer only uses the heap memory. |
There is no capacity concept in strings. | StringBuffer has a default capacity of 16. |
How to convert a String into StringBuffer and vice versa?
Ans.
public class StringToStringBufferAndViceVersa { public static void main(String[] args) { StringBuffer sb = new StringBuffer(); String str1 = new String("String is an object in Java."); String str2 = "String is a sequance of characters"; // Converting String into StringBuffer sb.append(str1); sb.append(str2); // Converting StringBuffer into String String str = sb.toString(); System.out.println("String value: " + str); System.out.println("StringBuffer value: " + sb); } }
Output
String value: String is an object in Java.String is a sequance of characters
StringBuilder value: String is an object in Java.String is a sequance of characters
How to convert a String into StringBuilder and vice versa?
Ans.
public class StringToStringBuilderAndViceVersa { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); String str1 = new String("String is an object in Java."); String str2 = "String is a sequance of characters"; // Converting String into StringBuilder sb.append(str1); sb.append(str2); // Converting StringBuilder into String String str = sb.toString(); System.out.println("String value: " + str); System.out.println("StringBuilder value: " + sb); } }
Output
String value: String is an object in Java.String is a sequance of characters
StringBuilder value: String is an object in Java.String is a sequance of characters
Why is char 2 bytes in Java?
Ans. ASCII code covers 255 characters so, to store a character only 1 byte is needed. Java uses Unicode covering 65536 characters - so 2 bytes needed.
In Java, a character is encoded in UTF-16 which uses 2 bytes, which requires a minimum of 16-bits of storage for each character.
How many ways we can compare two Strings in Java?
Ans. In Java, there are couple of ways for comparing two strings. Let's see one by one:
String str1 = "Java String"; String str2 = "String in Java"; String str3 = "JAVA String"; String str4 = "Java String"; str1.equals(str2); // Output: false str1.equals(str3); // Output: false str1.equals(str4); // Output: true
String str1 = "Java String"; String str2 = "String in Java"; String str3 = "JAVA String"; str1.equals(str2); // Output: false str1.equals(str3); // Output: true
String str1 = "Java String"; String str2 = "String in Java"; String str3 = "JAVA String"; String str4 = "Java String"; Objects.equals(str1, str2); // Output: false Objects.equals(str1, str4); // Output: true Objects.equals(str1, null); // Output: false Objects.equals(null, null); // Output: true
String str1 = "Java String"; String str2 = "String in Java"; String str3 = "JAVA String"; String str4 = "Java String"; str1.compareTo(str2); // Output: -9 str1.compareTo(str3); // Output: 32 str1.compareTo(str4); // Output: 0
Does String is thread-safe in Java?
Yes, Strings are thread-safe. Since a String is immutable, it can be safely shared between many threads. We don't need to synchronise string operations externally.