Strings
Strings
Strings
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
1. By string literal
2. By new keyword
1) String Literal
Each time you create a string literal, the JVM checks the "string constant
pool" first. If the string already exists in the pool, a reference to the pooled
instance is returned. If the string doesn't exist in the pool, a new string
instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will not
find any string object with the value "Welcome" in string constant pool that
is why it will create a new object. After that it will find the string with the
value "Welcome" in the pool, it will not create a new object but will return
the reference to the same instance.
Note: String objects are stored in a special memory area known as the
"string constant pool".
Why Java uses the concept of String literal?
To make Java more memory efficient (because no new objects are created if
it exists already in the string constant pool).
2) By new keyword
In such case, JVM will create a new string object in normal (non-pool) heap
memory, and the literal "Welcome" will be placed in the string constant
pool. The variable s will refer to the object in a heap (non-pool).
StringExample.java
import java.lang.String;
class stringdemo {
public static void main(String arg[])
int result=s1.compareTo(s2);
System.out.println("After compareTo()");
String s3=s1.substring(4,12);
} } *****************
The string s1 is : gpt gulbarga
The String in Upper Case : GPT GULBARGA Dept.MCA, Mr.Rakesh Kumar 9 JAVA PROGRAMMING LAB
Dec-2017 The String in Lower Case : gpt gulbarga s1 equals to s2 : false s1 equals ignore case to s2 : true
After compareTo() gpt gulbarga is greather than to GPT GULBARGA Character at an index of 6 is :l
Extracted substring is :gulbarga After Replacing g with a in s1 : apt aulbaraa The string s4 is : This is a
book After trim() :This is a book