11 May Strings in Java
A String is a chain of characters. String Class is provided by Java, and it implements strings as objects of the class String. In this lesson, we will learn about Strings in Java.
Let us see how to create strings in Java with examples.
Ways to Create a String in Java
There are multiple ways to create a string in Java:
Way 1: The following creates an empty string using the new:
String student = new String();
Way 2: Or, use the following to create an empty string:
String student;
Ways to Create a String and Initialize in Java
We can also create a string and initialize it in a single line:
Way 1: The following creates a string and also initializes it:
String message = "Amit";
Way 2: Or, use the following to create and initialize a string using the new:
String message = new String("Amit");
String – Other Examples
The following creates a string object. Initialized in the form of an array of characters,
String message = new String("Studyopedia provides free tutorials!"");
The following is another usage of Strings,
String result = "New York tops the list of most expensive cities for Business";
Coding example to create a string in Java
Let us see an example to create strings in Java:
// Create a String in Java
class Demo53 {
public static void main(String[] args) {
String message = "Hi";
// String message = new String ("Hi");
System.out.println(message);
}
}
The following is the output,
Hi
String Concatenation in Java
Let us see how to concatenate two strings. To concat a string in Java, use the String concat() method,
// String Concatenation in Java
class Demo54 {
public static void main(String[] args) {
String message1 = "Hi";
System.out.println(message1);
String message2 = ", Amit";
System.out.println(message2);
System.out.println("After concatenation = " + message1.concat(message2));
}
}
Output
Hi , Amit After concatenation = Hi, Amit
Why are Strings 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.
String str1 = “Example”;
Now, referred to str2,
String str2 = str1;
The following displays the text Example,
System.out.println(str1); System.out.println(str2);
Now let us use the concat() method,
str1 = str1.concat(“Question”);
Printing str1 displays, Example Question, i.e., concatenation,
System.out.println(str1);
Printing str2, displays, Example,
System.out.println(str2);
Since concatenation did not refer to string str2, the concatenation result is not visible.
Let us now see the methods in the String class that allow you to manipulate strings.
Built-in String Methods
String class methods allow easier manipulation of strings in Java. Below, the methods are explained with suitable examples.
- char charAt(int index)
Returns the 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 at the 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 lowercase 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