Introduction to String in Java
A string is basically a sequence of character, but in java, they are treated as objects, and they are immutable in nature; java provides java.lang.String package with different methods available to perform an operation on a string, but we can also create a mutable string in java.
How to Define String in Java?
We can define it by using the string literal and new keywords. But the difference is literal will not be going to create the new object unless and until it is not available in the string pool, but the new keyword will always create the new object irrespective of the string constant pool because it creates a string in the heap area.
- Mutable string
- Immutable string
How to Create String in Java?
In java, we can define string by using two ways which are as follows:
- By using a string literal
- By using a new keyword
1. String literal
The string which we create by using literal directly goes to the string constant pool. This means if the requested string already present in the string pool, then the existing string will be returned if the requested string does not exist, then only a new instance of string would be created and place in the pool for future reference. The JVM performs all these things.
Syntax:
String s="abc";
String s1 = "abc" ;
In the above scenario, only one object would be created in the string pool because JVM will not be able to find the requested object, so it will create it and place it into the pool, and s1 will point to that reference only for further use. So string literal also save memory by not creating the same instance again. Hence they make our code memory efficient.
2. new keyword
In java, we use the new keyword to create a new object. Whenever we use a new keyword, it will create a new object for us. Also, object which are created by using new keyword place into the heap memory area.
Syntax:
String s = new Stirng("abc");
In the above example, this object will be placed into the heap memory area, not into the string pool, because we are creating it by using the new keyword.
Example:
public class Main {
public static void main(String[] args) {
String s = "abc";
String s1 = "abc";
String ss = new String("abc");
System.out.println("Output will be :: " + s + " "+ s1 +" "+ ss);
}
}
Output:
Rules and Regulations for String in Java
It is immutable, which means we cannot change its value once it is assigned. So for creating a mutable string, we need to use a String buffer for this.
Few points need to remember:
- While defining string, make sure it is always quoted with double-quotes.
- They are immutable, i.e. value cannot be changed once assigned.
- We can use the ‘+’ operator to concatenate two or more string.
- We can directly assign the string to a variable without calling its constructor.
Methods of String Class in Java
Various methods available are as follows:
- trim()
- toUpperCase
- toLowerCase
- valueOf(int value)
- toLowerCase(Locale l)
- intern()
- indexOf(int ch)
- indexOf(String substring, int fromIndex)
- indexOf(String substring)
- split(String regex, int limit)
- concat(String str)
- indexOf(int ch, int fromIndex)
- length()
- equals(Object another)
- join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
- isEmpty()
- replace(char old, char new)
- equalsIgnoreCase(String another)
- split(String regex)
- toUpperCase(Locale l)
- contains(CharSequence s)
- charAt(int index)
- replace(CharSequence old, CharSequence new)
- join(CharSequence delimiter, CharSequence… elements)
- substring(int beginIndex)
- ubstring(int beginIndex, int endIndex)
- String class in java implement different interfac named
- Serializable
- Comparable
- CharSequence
Also, the string class implement one more interface, i.e. CharSequence interface; StringBuilder and String Buffer also implement this interface. StringBuffer and StringBuilder are used to create the mutable string in java.
Example – Using StringBuffer
Code:
public class Demo{
public static void main(String[] args) {
StringBuffer sb=new StringBuffer("creating string ");
sb.append("executed");//original string will get chnage
System.out.println("Result is " +sb);//it will print creating string executed
}
}
Output :
Example – Using StringBuilder
Code:
public class Main{
public static void main(String[] args) {
StringBuilder sb=new StringBuilder("Creating string");
sb.append(" using string Builder");//original will get change
System.out.println("Result is "+sb);
}
}
Output:
Examples
Below are the examples :
Example #1
Code:
public class Main{
public static void main(String[] args) {
String s1="demoforsting";
System.out.println("String is " +s1.substring(2,4));
System.out.println( "with one parameter " +s1.substring(2));
}
}
Output:
Example #2
Code:
public class Demo{
public static void main(String[] args) {
String s1="abc";
String s2="abc";
String s3="ABC";
String s4="java";
System.out.println("Result is " +s1.equals(s2));//true
System.out.println("Result is " +s1.equals(s3));//false
System.out.println("Result is " +s1.equals(s4));//false
}
}
Output:
Example #3
Code:
public class Demo{
public static void main(String[] args) {
String s1="convert it into uppercase";
String upper=s1.toUpperCase();
System.out.println("result is "+upper);
}
}
Output:
Example #4
Code:
public class Demo{
public static void main(String[] args) {
String s1="CONVERT IT INTO LOWER CASE";
String s1upper=s1.toLowerCase();
System.out.println("result is "+s1upper);
}
}
Output:
Example #5
Code:
public class Main{
public static void main(String[] args) {
String name="Demo to check contains method";
System.out.println("Result for conatins mehtod is " +name.contains("check"));
System.out.println("Result for conatins mehtod is " +name.contains("method"));
System.out.println("Result for conatins mehtod is " +name.contains("move"));
}
}
Output:
Example #6
Code:
public class Main{
public static void main(String[] args) {
String str1 = "Demo for";
String str2 = "Concat";
String str3 = "Method";
// doing for string one
String str4 = str1.concat(str2);
System.out.println("Result is "+str4);
// for multiple string
String str5 = str1.concat(str2).concat(str3);
System.out.println("Result is "+str5);
}
}
Output:
Example #7
Code:
public class Main {
public static void main(String[] args) {
String s1 =" Provide space to see use of trim method in java ";
System.out.println(s1.length());
System.out.println("without trim output is "+s1); //Not using trim here
String tr = s1.trim();
System.out.println(tr.length());
System.out.println("with trim output is "+tr); //using trim here
}
}
Output:
Conclusion
So java string is an object which is immutable in nature to provide security in various aspects like URL reading, database username and password, port, and so many other things. But if we want to create a mutable string, we should use string buffer and builder.
Recommended Articles
This has been a guide to String in Java. Here we discuss the introduction, methods, examples, and how to create String in Java? You may also have a look at the following articles to learn more –