Lesson 1
Lesson 1
Lesson 1
1) String Literal
Java String literal is created by using double
quotes. For Example:
1.String s="welcome";
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 inst
ance
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.
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
1. String s=new String("Welcome");//creates two
objects and one reference variable
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).
No Method Description
.
o class Teststringcomparison1{
o public static void main(String args[]){
o String s1="Sachin";
o String s2="Sachin";
o String s3=new String("Sachin");
o String s4="Saurav";
o System.out.println(s1.equals(s2));//true
o System.out.println(s1.equals(s3));//true
o System.out.println(s1.equals(s4));//false
o }
o }
In the above code, two strings are compared
using equals() method of String class. And the
result is printed as boolean
values, true or false.
Teststringcomparison2.java
1. class Teststringcomparison2{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="SACHIN";
5.
6. System.out.println(s1.equals(s2));//false
7. System.out.println(s1.equalsIgnoreCase(s2
));//true
8. }
9. }
In the above program, the methods of String class
are used. The equals() method returns true if
String objects are matching and both strings are of
same case. equalsIgnoreCase() returns true
regardless of cases of strings.
2) By Using == operator
The == operator compares references not
values.
Teststringcomparison3.java
1.class Teststringcomparison3{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. System.out.println(s1==s2);//true (because both
refer to same instance)
7. System.out.println(s1==s3);//false(because s3 re
fers to instance created in nonpool)
8. }
9.}