11 May Strings in Java
A String is a chain of characters. String Class is provided by Java and it implements strings as object of class String. In this lesson we will learn about Strings in Java.
Create strings in Java using any of the following constructors,
The following creates an empty string,
1 2 3 |
String student = new String(); |
The following creates a string object. Initialized in the form of array of characters,
1 2 3 |
String message = new String(“Studyopedia provides free tutorials!”); |
The following is another usage of Strings,
1 2 3 |
String result = “New York tops the list of most expensive cities for Business”; |
Let us see an example of strings,
1 2 3 4 5 6 7 8 9 10 |
public class StudyopediaDemo { public static void main(String args[]) { String message = new String("Studyopedia provides free tutorials!"); System.out.println("Dear Learners, "+message); } } |
The following is the output,
Let us see how to concatenate two strings,
String Concatenation in Java
To concat a string in Java, use the String concat() method,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class StudyopediaDemo { public static void main(String args[]) { String str1 = new String("Studyopedia provides free tutorials "); String str2 = str1; str1 = str1.concat("for all"); System.out.println("Dear Learners, "+str1); } } |
The following is the output,
Let us now see why strings are mutable in Java,
Why Strings are Immutable?
Strings in Java cannot be changed, once created. Therefore, String objects are immutable. Remember that this does not apply to reference variables.
An example would make it easier to understand.
1 2 3 |
String str1 = “Example”; |
Now, referred to str2,
1 2 3 |
String str2 = str1; |
The following displays the text Example,
1 2 3 4 |
System.out.println(str1); System.out.println(str2); |
Now let us use the concat() method,
1 2 3 |
str1 = str1.concat(“Question”); |
Printing str1, displays, Example Question, i.e. concatenation,
1 2 3 |
System.out.println(str1); |
Printing str2, displays, Example,
1 2 3 |
System.out.println(str2); |
Since concatenation did not refer to string str2, therefore the concatenation result is not visible.
Let us now see the methods in String class that allows you to manipulate strings.
Methods
String class methods allow easier manipulation of strings in Java. Below the methods are explained with suitable examples.
- char charAt(int index)
Returns character at the specified index.
- int compareTo(Object o)
Compares the String to another Object.
- int compareTo(String anotherString)
Compares two strings lexicographically.
- int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences.
- String concat(String str)
Concatenates the specified string to the end of this string.
- static String copyValueOf(char[] data)
Returns a String representing the character sequence in the array specified.
- static String copyValueOf(char[] data, int offset, int count)
Returns a String representing the character sequence in the array specified.
- boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.
- boolean equals(Object anObject)
Compares this string to the specified object.
- boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
- byte getBytes()
Encodes this String into a sequence of bytes using the platform’s default charset, storing the result into a new byte array.
- byte[] getBytes(String charsetName)
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
- void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
- int hashCode()
Returns a hash code for this string.
- int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
- 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.
- int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
- int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
- String intern()
Returns a canonical representation for the string object.
- int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.
- int lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
- int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
- int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
- int length()
Returns the length of this string.
- boolean matches(String regex)
Tells whether or not this string matches the given regular expression.
- boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Tests if two string regions are equal, with an option to ignore case or not.
- boolean regionMatches(int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
- String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
- String replaceAll(String regex, String replacement
Replaces each substring of this string that matches the given regular expression with the given replacement.
- String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the given replacement.
- String[] split(String regex)
Splits this string around matches of the given regular expression.
- String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.
- boolean startsWith(String prefix)
Tests if this string starts with the specified prefix.
- boolean startsWith(String prefix, int toffset)
Tests if this string starts with the specified prefix beginning a specified index.
- CharSequence subSequence(int beginIndex, int endIndex)
Returns a new character sequence that is a subsequence of this sequence.
- String substring(int beginIndex)
Returns a new string that is a substring of this string.
- String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string.
- char[] toCharArray()
Converts this string to a new character array.
- String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.
- String toLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the given Locale.
- String toString()
This object (which is already a string!) is itself returned.
- String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
- String toUpperCase(Locale locale)
Converts all of the characters in this String to upper case using the rules of the given Locale.
- String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
Reference: Oracle Java String Class
In this lesson we learned how to work with Strings in Java.
No Comments