- What is a string?
- Why do we use Strings?
- How to create a String?
- String Length
- What is Concatenating Strings?
- Java String Methods
What is a string?
String manipulation is a sequence of characters. They are widely used in Java. In java, strings are used to create objects. It is not a primitive type and is used to create and store immutable things. Simply you can take it as constant because you can’t change it once created. In java, we do a lot of things with the help of strings. You can also think of a string as an array of characters. Let us discuss how can we represent a string of “GREEN”?
G | R | E | E | N |
Now, before diving deep into string manipulation in java, let’s have a quick talk over some basic things about the string that you need to know.
Why do we use Strings?
You don’t disagree that processing human language is one of the foremost functions of our modern computer science.
This is really important, as language symbols are important to meaning and decision making, and numbers are important to maths. But, more part of this isn’t visible to the user because all of these processing works going on in the background. Although the process is highly precise and accurate.
So in Java, we can consider String as our best friend and If you want to become a good java developer then you should keep it tight that string class is going to be your main tool for storing and processing language.
Also Read: Palindrome in JAVA
How to create a String?
We have mainly two ways to create strings in Java:-
● String Literal
● Using new keyword
i) By Using String literal
In Java, we can create strings by assigning a string literal to the String instance;
String str1 = “GreatLearning” ; |
String str2 = “GreatLearning” ; |
As you already know that String is an object in Java. But, above we’ve not created any string object using the new keyword. It is the compiler who does that task for us. It creates a string object having the string literal (which is provided by us called “ GreatLearning” ) and then assigns it to provided string instances.
However, it doesn’t create a new object if the object already exists in the memory. Moreover, it will assign the same object to new instances. So, it is clear that even if we have two string instances (str1 and str2) the compiler is only created on a string object ( value= “GreatLearning”) and it’ll assign the same to both instances. To make it more clear, let’s consider an example. Imagine there are 15 string instances having the same value, so you should know that there’s only one object having the value and all of the 15 string instances would be pointing to the same object.
So, the question is what if we want to have two different objects with the same string? Well for that we need to create strings
Also Read: Exception Handling in Java with Examples
ii) By Using New Keyword
When we try to assign the same string object to two different literals, compilers only create one and make both literals to point the same object. So by using this, we can easily get out of this problem.
String str1 = new String(“GreatLearning”) ; |
String str2 = new String(“GreatLearning”) ; |
Thus by using this, the compiler will create two different objects in memory having the same string.
Example of a simple Java String
public class Example{
public static void main(String args[]){
//creating a string by java string literal
String str = "ModernIndia ";
char arrch[]={'G','r','e','a','t','L','e','a','r','n','i','n','g'};
//converting the char array arrch[] to string str2
String str2 = new String(arrch);
//creating another java string ‘str3’ by using new keyword
String str3 = new String("String Example");
//Displaying all the three strings
System.out.println(str);
System.out.println(str2);
System.out.println(str3);
}
}
Output:
ModernIndia GreatLearning String Example |
String Length
The methods which are used to obtain information about an object are known as accessor methods. length()method is one of the accessor
method, you can use it with string. Here, the number of characters contained in the string object.
Example:
public class StringExample {
public static void main(String args[]) {
String s1= "Begin your learning journey today";
System.out.println( "The length of String is : " +s1.lenght); }
}
The output will be:
The length of String is : 29 |
What is Concatenating Strings?
Concatenating is nothing but a combination of two or more strings. Let’s clear it with the help of a simple example:
Consider we have two strings str1= “Green” and str2= ‘Tea”. If we combine these two strings, then we should have a result as str3= “GreenTea”.
Here, we have basically two methods to perform string concatenation. Check out the code to get a clear picture:
public class String_Example{
public static void main(String[] args){
//String Concatenation
String str1 = "Green";
String str2 = "Tea";
//Method 1 : Using concat
String str3 = str1.concat(str2);
System.out.println(str3);
//Method 2 : Using "+" operator
String str4 = str1 + str2;
System.out.println(str4);
}
}
Java String Methods
char charAt(int index): It always returns the character at the specified index. Specified index value always should be between 0 to length() -1 both inclusive.
Also, it throws IndexOutOfBoundsException if index<0||>= length of String.
int compareTo(String string): It helps to compare the two strings based on the Unicode value of each character in the strings.
boolean startsWith(String prefix): It’ll test whether the string is having specified prefix, if yes then it returns true else false.
boolean equals(Object obj): It compares the string with the specified string and returns true if both matches else it’ll print false.
int compareToIgnoreCase(String string): This is same as CompareTo method although it ignores the case during comparison.
boolean startsWith(String prefix, int offset): It always checks whether the substring (which is starting from the specified offset index) is having the specified prefix or not.
int hashCode(): It always returns the hash code of the string.
boolean equalsIgnoreCase(String string): It’s not much different than the equal method. It works the same as equals method but it doesn’t consider the case while comparing the strings. Also, it does a case insensitive comparison.
int indexOf(String str): It returns the index of first occurrence of specified substring str.
boolean endsWith(String suffix): It checks whether the string ends with the specified suffix or not.
int indexOf(int ch): It returns the index of the first occurrence of the specified character ch in the string.
int lastIndexOf(int ch): It always returns the last occurrence of the character ch in the string.
int lastIndexOf(int ch, int fromIndex): This is the same as lastIndexOf(int ch) method, and it starts searching from fromIndex.
int lastindexOf(String str): It returns the index of last occurrence of string str.
String substring(int beginIndex): This method helps to return the substring of the string. Also this substring starts with the character at the specified index.
int indexOf(int ch, int fromIndex): This is the same as indexOf method however as you know it starts searching in the string from the specified fromIndex.
String concat(String str): It always Concatenates the specified string “str” at the end of the string like we explained above with an example.
String substring(int beginIndex, int endIndex): It always returns the substring. Moreover, the substring starts with a character at beginIndex and ends with the character at endIndex.
boolean contains(CharSequences): This will check whether the string contains the specified sequence of char values or not. And if yes then it returns true else false. It throws NullPointerException of ‘s’ is null.
String toUpperCase(): This is equivalent to the
toUpperCase(Locale.getDefault()).
String replace(char oldChar, char newChar): This method helps to return the new updated string after changing all the occurrences of oldChar with the newChar.
public String intern(): It searches the specified string in the memory pool and if it is found then it returns the reference of it, else it’ll allocate the memory space to the specified string by assigning reference to it.
String toUpperCase(Locale locale): This method helps to convert the string to upper case string with the help of the rules defined by specified locale.
String replaceAll(String regex, String replacement): This string method replaces all the occurrences of substrings which are fit to the regular expression regex with the replacement string.
public static String join(): It helps in joining the given strings using the specified delimiter and it returns the concatenated Java String.
String[] split(String regex): It is almost the same as split(String regex, int limit) method although it does not have any threshold limit.
public boolean isEmpty(): It returns true if the given string has 0 length. And if the length of the specified Java String is non-zero then it’ll return false.
String toLowerCase(): This string method is equivalent to toLowerCase(Locale. getDefault()).
String replaceFirst(String regex, String replacement): This method replaces the first occurrence of a substring which is fit to the given regular expression “regex” with the specified replacement string.
String toLowerCase(Locale locale): This string method converts the string to lowercase string using the rules defined by the given locale.
public static String format(): It helps in returning a formatted java String.
String[] split(String regex, int limit): This string method splits the string and returns the array of substrings that matches the given regular expression. Also, limit is a result threshold here.
static String copyValueOf(char[] data, int offset, int count): This string method isn’t very different from the above method. Moreover, it comes up with two extra arguments called length of subarray and initial offset of subarray.
String trim(): This string method always returns the substring after omitting leading and trailing white spaces from the original string.
static String copyValueOf(char[] data): This string method returns a string that contains the characters of the specified character array.
char[] toCharArray(): It converts the string to a character array.
static String valueOf(): It returns a string representation of passed arguments such as int, long, float, double, char and char array.
boolean contentEquals(StringBuffer sb): This string method compares the string to the specified string buffer.
boolean regionMatches(int srcoffset, String dest, int destoffset, int len): This string method compares the substring of the input to the substring of specified string.
void getChars(int srcBegin, int srcEnd, char[] dest, int destBegin): This string method always copies the characters of the src array to the dest array. Only the specified range is being copied(srcBegin to srcEnd) to dest subarray(starting fromdestBegin).
boolean regionMatches(boolean ignoreCase, int srcoffset, String dest, int destoffset, int len): This method is one asnother variation of regionMatches method with the extra boolean argument to specify whether the comparison is case insensitive or case sensitive.
byte[] getBytes(String charsetName): This method simply converts the String into sequence of bytes using the specified charset encoding and returns the array of resulted bytes.
byte[] getBytes(): It is very similar to the above method but it just uses the default charset encoding for converting the string into sequence of bytes.
int length(): This string method is used to return the length of a String.
int codePointAt(int index): This method is similar to the charAt method however it returns the Unicode code point value of the specified index rather than the character itself.
boolean matches(String regex): It is used to check whether the String is matching with the specified regular expression regex or not.
We hope now you might have got some basic idea about String manipulation in Java and you can now move forward to learn more. Get your hands on free Java Certificates today!
Engaging in the study of Java programming suggests a keen interest in the realm of software development. For those embarking upon this journey with aspirations towards a career in this field, it is recommended to explore the following pages in order to acquire a comprehensive understanding of the development career path: