There are no items in your cart
Add More
Add More
Item Details | Price |
---|
Introduction of Java String and How to Create a Java String
Thu Dec 30, 2021
In Java, string is basically an object that represents sequence of char values.
String S="Java";
System.out.println(S);
An array of characters works same as Java string in the following way:
char[] ch={'J','a','v','a'};
System.out.println(ch);
This is the array of characters and Array Object, but
char[] ch={'J','a','v','a'};
String S=new String(ch);
System.out.println(ch);
This is the String Object
String is a class of The java.lang package i.e we can write The java.lang.String class
The java.lang.String class is used to create a string object.
Since arrays are immutable(cannot grow), Strings are immutable as well. Whenever a change to a String is made, an entirely new String is created.
There are two ways to create String object: ·
1) String Literal
Java String literal is created by using double quotes.
For Example:
String S="Java";
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:
String s1="Welcome";
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
The string can also be declared using new operator i.e. dynamically allocated. In case of String are dynamically allocated they are assigned a new memory location in heap. This string will not be added to String constant pool.
String s=new String("Welcome");
Example:
String S1="Ram"; //creating string by Java string literal
char[] ch={'J','a','v','a'};
String S2=new String(ch); //converting char array to string
String S3=new String("Hello"); //creating Java string by new keyword System.out.println(S1);
System.out.println(S2);
System.out.println(S3);
S P SHARMA CLASSES
S P SHARMA SIR