Introduction To Java String Handling
Introduction To Java String Handling
System.out.println(s1);
Hello Java
System.out.println(s1);
Hello Java
Each time we create a String literal, the JVM checks the string pool first. If the string literal
already exists in the pool, a reference to the pool instance is returned. If string does not
exist in the pool, a new string object is created, and is placed in the pool. String objects are
stored in a special memory area known as string constant pool inside the heap memory.
And, when we create another object with same string, then a reference of the string literal
already present in string pool is returned.
String str2 = str;
But if we change the new string, its reference gets modified.
str2=str2.concat("world");
Concatenating String
There are 2 methods to concatenate two or more string.
String s = "Hello";
System.out.println(str1);
HelloJava
2) Using + operator
Java uses "+" operator to concatenate two string objects into single one. It can also
concatenate numeric value with string object. See the below example.
public class Demo{
String s = "Hello";
System.out.println(str1);
System.out.println(str2);
HelloJava
Java11
String Comparison
To compare string objects, Java provides methods and operators both. So we can
compare string in following three ways.
Example
It compares the content of the strings. It will return true if string matches, else
returns false.
public class Demo{
String s = "Hell";
String s1 = "Hello";
String s2 = "Hello";
System.out.println(b);
b = s.equals(s1) ; //false
System.out.println(b);
true
false
Using == operator
The double equal (==) operator compares two object references to check whether they
refer to same instance. This also, will return true on successful match else returns false.
public class Demo{
String s1 = "Java";
String s2 = "Java";
System.out.println(b);
System.out.println(b);
true
false
Explanation
We are creating a new object using new operator, and thus it gets created in a non-pool
memory area of the heap. s1 is pointing to the String in string pool while s3 is pointing to
the String in heap and hence, when we compare s1 and s3, the answer is false.
The following image will explain it more clearly.
By compareTo() method
String compareTo() method compares values and returns an integer value which tells if
the string compared is less than, equal to or greater than the other string. It compares the
String based on natural ordering i.e alphabetically. Its general syntax is.
Syntax:
int compareTo(String str)
Example:
public class HelloWorld{
String s1 = "Abhi";
String s2 = "Viraaj";
String s3 = "Abhi";
System.out.println(a);
System.out.println(a);
System.out.println(a);
-21
21
THANK YOU