In the previous section we learned about loops in java and what are the 3 types of loops, Now in this section we are going to learn most usable topic in entire java programming language "Java Strings". String is a widely used topic in Java programming, Strings are a sequence of characters. In Java, strings are treated as objects. The Java platform provides the String class to create and manipulate strings
We have different ways to create a string in java, the most common way to create a String is
String helloString = "Hello world"; |
We can also create a String with "new" keyword
String helloString = new String("Hello world"); |
So what is the difference between create String with new keyword and double quotes ("")
new String("
Hello world"); which
explicitly creates a new distinct instance of a String
object;
where as
String helloString = "Hello world"; it may reuse an instance from the string constant pool if one is available.
Note: The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters, then you should use String Buffer & String Builder Classes
We will learn about String buffer and String builder in coming sections.
This unit will cover even more methods for working with strings.
length()
trim()
concat()
toLowerCase()
toUpperCase()
startsWith()
endsWith()
replace()
Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object
Syntax
str.length() |
Example
public class StringDemo { public static void main(String args[]) { String javaString = "welcome to Java String"; int len = javaString.length(); System.out.println( "String Length is : " + len ); } } |
Output
String Length is : 22
The String class contains a method called concat to add different strings, int and other primitive types values...
Syntax:
string1.concat(string2); |
The above returns a new string that is string1 with string2 added to it at the end. We can also use the concat() method with string literals, as in −
"Java String ".concat("Methods");
Strings are more commonly concatenated with the + operator, as in −
"Hello," + " world" + "!"
This will returns
"Hello, world!"
The trim() method removes all the leading(starting) and trailing(ending) spaces of the given string and returns a new string.
Syntax
class Main { public static void main(String[] args) { String mobile = " 9876543210 "; String trimmed = mobile.trim(); // trim method called and returned a new string System.out.println(mobile); // old string System.out.println(trimmed); // new string
} } |
9876543210
9876543210
In the above code, we can see that the trimmed variable contains a new string returned by trim() after removing all the leading and trailing spaces.
The toLowerCase() method converts each character of the given string to lowercase and returns a new string.
class Main { public static void main(String[] args) { String name = "HEllO, How ARE yOu?"; String lowercaseStr = name.toLowerCase(); System.out.println(name); // old string System.out.println(lowercaseStr); // new string } } |
HEllO, How ARE yOu?
hello, how are you?
In the above code, we can see that the lowercaseStr variable contains a new string returned by toLowerCase() with all the characters of the given string converted to lowercase.
The toUpperCase() method converts each character of the given string to uppercase and returns a new string.
Syntax
class Main { public static void main(String[] args) { String name = "helLO, How aRe yoU?"; String uppercaseStr = name.toUpperCase(); System.out.println(name); // old string System.out.println(uppercaseStr); // new string } } |
helLO, How aRe yoU?
HELLO, HOW ARE YOU?
In the above code, we can see that the uppercaseStr variable contains a new string returned by toUpperCase() with all the characters of the given string converted to uppercase.
The startswith() method returns true if the given string starts with the specified value. Otherwise, false is returned.
Syntax
The value provided to startswith() should be a string.
class Main { public static void main(String[] args) { String url = "https://www.google.com/"; boolean isSecureUrl = url.startsWith("https://");
System.out.println(isSecureUrl); } } |
true
In the above code, the url starts with https://. Hence true is returned and printed to the console.
The endsWith() method returns true if the given string ends with the specified value. Otherwise, false is returned.
Syntax
The value provided to endsWith() should be a string.
class Main { public static void main(String[] args) { String gmailId = "rahul123@gmail.com"; boolean isGmail = gmailId.endsWith("@gmail.com");
System.out.println(isGmail); } } |
true
In the above code, the gmailId ends with @gmail.com. Hence true is returned and printed to the console.
The replace() method in Java works similar to that in Python. It replaces all the occurrences of the old character/substring with the latest character/substring and returns a new string.
str.replace(old, latest); |
The old and latest can be either characters (char) or strings.
Note: Both old and latest should be of the same data type.
Example
class Main { public static void main(String[] args) { String programmingLanguage = "Java"; String latest = programmingLanguage.replace('a', 'e'); System.out.println(latest); } } |
Jeve
In the above code, we can see that replace() returns a new string replacing all the occurrences of a with e.
Example 2:
class Main { public static void main(String[] args) { String sentence = "teh cat and teh dog"; String newSentence = sentence.replace("teh", "the"); System.out.println(newSentence); } } |
the cat and the dog
The replaceFirst() method returns a new string after replacing the first occurrence of the old substring with the latest substring.
Syntax
str.replaceFirst(old, latest); |
Example
class Main { public static void main(String[] args) { String sentence = "teh cat and teh dog"; String newSentence = sentence.replaceFirst("teh", "the"); System.out.println(newSentence); } } |
the cat and teh dog
In the above code, we can see that the replaceFirst() method returns a new string replacing only the first occurrence of teh to the
What if a character is to be replaced using replaceFirst()? The replaceFirst() method accepts strings but not characters (i.e, char data type).
class Main { public static void main(String[] args) { String word = "Java"; String newWord = word.replaceFirst('a', 'i'); System.out.println(newWord); } } |
file.java:4: error: incompatible types: char cannot be converted to String String newWord = word.replaceFirst('a', 'i'); ^ 1 error |
The error occurs because we cannot pass a char data type to replaceFirst(). To meet the requirement, we can provide double quotes (") around characters to pass the characters as strings.
class Main { public static void main(String[] args) { String word = "Java"; String newWord = word.replaceFirst("a", "i"); System.out.println(newWord); } } |
Java
Related Queries:
Java Concatenate string and int
Java String concatenate best practices
Java String concate vs +
String append Java
serial number | method | describe |
---|---|---|
1 | char charAt (int index) | Returns the character at the specified index. |
2 | int compareTo (Object o) | Compares this String object with another object. |
3 | int compareTo (String anotherString) | Compares two strings lexicographically. |
4 | int compareToIgnoreCase (String str) | Compares two strings lexicographically, but case insensitively. |
5 | String concat (String str) | Concatenates the specified string to the end of this string. |
6 | boolean contentEquals (StringBuffer sb) | Returns if and only if String the string represented by this is the StringBuffer same sequence of characters as specified true . |
7 | static String copyValueOf (char[] data) | String Returns the form of an object representing the sequence of characters in the specified array . |
8 | static String copyValueOf (char[] data, int offset, int count) | String Returns the form of an object representing the sequence of characters in the specified array . |
9 | boolean endsWith (String suffix) | Determines whether this string ends with the specified character as a suffix. |
10 | boolean equals (Object anObject) | Compares this string with the specified object. |
11 | boolean equalsIgnoreCase (String anotherString) | Compare this String to another String , ignoring case. |
12 | byte getBytes() | Encode this as a sequence of bytes using the platform's default charset String , storing the result into a new byte array. |
13 | byte[] getBytes (String charsetName) | Encodes this String into a sequence of bytes using the specified charset, storing the result into a new byte array. |
14 | void getChars (int srcBegin, int srcEnd, char[] dst, int dstBegin) | Copies the characters in this string into the destination character array. |
15 | int hashCode() | Returns the hash code for this string. |
16 | int indexOf (int ch) | Returns the index of the first occurrence of the specified character in this string. |
17 | int indexOf (int ch, int fromIndex) | Returns the index of the first occurrence of the specified character in this string, starting the search at the specified index. |
18 | int indexOf(String str) | Returns the index of the first occurrence of the specified substring within this string. |
19 | int indexOf (String str, int fromIndex) | Returns the index of the first occurrence of the specified substring within this string, starting at the specified index. |
20 | String intern() | Returns the canonical representation of a string object. |
twenty one | int lastIndexOf(int ch) | Returns the index of the last occurrence of the specified character in this string. |
twenty two | int lastIndexOf (int ch, int fromIndex) | Returns the index of the last occurrence of the specified character in this string, searching backwards from the specified index. |
twenty three | int lastIndexOf (String str) | Returns the index of the last occurrence of the specified substring in these strings. |
twenty four | int lastIndexOf (String str, int fromIndex) | Returns the index of the last occurrence of the specified substring in this string, searching backwards from the specified index. |
25 | int length() | Returns the length of this string. |
26 | boolean matches (String regex) | Determines whether this string matches the given regular expression. |
27 | boolean regionMatches (boolean ignoreCase, int toffset, String other, int ooffset, int len) | Determines whether two string regions are equal. |
28 | boolean regionMatches (int toffset, String other, int ooffset, int len) | Determines whether two string regions are equal. |
29 | String replace(char oldChar, char newChar) | Returns a new string newChar with all occurrences of this string replaced oldChar . |
30 | String replaceAll(String regex, String replacement) | will replace every substring in this string that matches the given regular expression. |
31 | String replaceFirst(String regex, String replacement) | Will replace the first substring in this string that matches the given regular expression. |
32 | String[] split(String regex) | Splits this string into matches of the given regular expression. |
33 | String[] split(String regex, int limit) | Splits this string into matches of the given regular expression. |
34 | boolean startsWith(String prefix) | Determines whether this string starts with the specified string prefix. |
35 | boolean startsWith(String prefix, int toffset) | Determines whether this string starts with the specified prefix at the specified index. |
36 | CharSequence subSequence(int beginIndex, int endIndex) | Returns a new sequence of characters that is a subsequence of this sequence. |
37 | String substring(int beginIndex) | Returns a new string that is a substring of this string. |
38 | String substring(int beginIndex, int endIndex) | Returns a new string that is a substring of this string. |
39 | char[] toCharArray() | Convert this string to a new character array. |
40 | String to LowerCase() | String Convert all characters in this to lowercase using the rules of the default locale . |
41 | String toLowerCase(Locale locale) | Converts all characters in this to lowercase using the given Locale rules .String |
42 | String to String() | Return this object (already a string) itself. |
43 | String toUpperCase() | String Convert all characters in this to uppercase using the rules of the default locale . |
44 | String toUpperCase(Locale locale) | Converts all characters in this to uppercase using the given Locale rules .String |
45 | String trim() | Return a copy of the string with leading and trailing spaces removed. |
46 | static String valueOf(primitive data type x) | Returns a string representation of the passed datatype parameter. |