Updates
  • Starting New Weekday Batch for Java Full Stack Developer on 24th June 2024 @ 02:00 PM to 04:00 PM
  • Starting New Weekend Batch for Java Full Stack Developer on 06th July 2024 @ 11:00 AM to 02:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 08th July 2024 @ 04:00 PM to 06:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 29th July 2024 @ 10:00 AM to 12:00 PM
Join Course

java.lang.String class

• String is not a primitive data type in Java.
• Java.lang.String is a built-in class which is available inside Java.lang package.
• String is a final class which cannot be extended by some other class.
• String objects are immutable in nature in which changes cannot be made.
• Whenever you concatenate any string with an existing object of String class a new object is created.
• String class object uses special memory location, i.e., String-Constant-Pool which is available in Heap for the reusability of String objects.
• String object can be created in two different ways:

1. Using String Literals.
2. Using new operator.

Now we will discuss how JVM creates an object internally of String class using String Literals:

In Java Programming Language when we create an object of String class using String literals like- String s1 = “Hello”-then first the program will access SCP and check for any existing object of String class in SCP having “Hello” String literals. If String class object is not available in SCP then a new object of String class is created in SCP and the corresponding reference variable linked to that newly created object. If String class object is already existing in SCP then new object is not created and corresponding reference variable refers to that same existing object in SCP.

            
class JTC{
	public static void main(String arg[]){
		String s1 = "Hello";
		String s2 = "Hello";
		String s3 = "hello";
		
		System.out.println("s1 == s2 :- "+(s1==s2)); // true
		System.out.println("s1 == s3 :- "+(s1==s3)); // false
		System.out.println("s2 == s3 :- "+(s2==s3)); // false
	}
}
    s1 == s2 :- true
    s1 == s3 :- false
    s2 == s3 :- false
            

In the above example we have class JTC and inside the JTC class main() method first we are creating an object of String s1 = “Hello”, so as we discussed the it accesses SCP and checks for existing object of String class configured with “Hello” String literals. As you can see that this is the first object, i.e. the object did not exist and hence was created. The program creates a new object of String class with “Hello” and s1 reference variable refers to that object.

In the next line again, we have String s2 = “Hello”; however, now already we have an object of String class with “Hello” String literals in SCP so it does not create a new object here and s2 reference variable gets linked to the existing object.

In the next line again, we are creating an object of String class using “hello” String literals String s3 = “hello”, and because we do not have any object of String class with “hello” String literals in SCP so it creates a new object in SCP and s3 is the reference variable for that newly created object.

In the last section of the above example, we are comparing String class object for checking and in the output we can see that s1 == s2 result is true. This shows that s1 and s2 reference variables refer to the same object of String class. Also s1 == s3 and s2 == s3 results are false which shows that s1, s3 and s2, s3 are referring to different objects.

Here we will discuss how JVM works when we create an object of String class using new operator:

In Java when we create an object of String with new operator then first the program checks inside the SCP that whether that string class object is available with specific String literal or not. If it is not available inside SCP, one new object in SCP will be created and thereafter the programs comes out of the SCP and creates one new object inside the Heap and reference variable gets linked with the object in Heap. If the String object is available inside SCP (String-Constant-Pool), then it will not create any new object inside SCP; it comes out of the SCP and creates a String object inside the Heap and gets linked to that object in the Heap.

            
class A{
	public static void main(String arg[]){
		
		String s1 = new String("Hello");
		String s2 = new String("Hello");
		String s3 = "Hello";
		
		System.out.println("s1 == s2 :- "+(s1 == s2));
		System.out.println("s1 == s3 :- "+(s1 == s3));
		System.out.println("s2 == s3 :- "+(s2 == s3));
	}
}
    s1 == s2 :- false
    s1 == s3 :- false
    s2 == s3 :- false
            

In this example we can see that we are creating an object of String class using new operator String s1 = new String (“Hello”); so, the program sends its prompt inside the SCP to check for existing object of String class configured with “Hello” String literals. This is the first instance where we can see an object with “Hello” String literals, this means that the program has created this new object- which is the first object that we can see- in SCP and thereafter program has been sent into the Heap area by the program to create a new object in Heap as well. With the creation of this first object we get two objects of String class with “Hello” String literals- one is in Heap and one is in SCP- and finally s1 reference variable gets linked with the newly created object in the Heap area.

In the next line again, we have an object of String class- String s2 = new String (“Hello”)- with same String literals which is “Hello”. Hence as we discussed the program does not create any new object in SCP but in Heap a new object with “Hello” String literals is created and reference variable s2 refers to this new object created in Heap.

Further, again in the next line, we are creating an object of String class using String literals which is “Hello”. As we have discussed, the program goes to the SCP and searches for existing object of String class with “Hello” String literals. However, now we already have an object of String class with “Hello” String literals inside SCP and s3 reference variable refers to that same object.

It means all the reference variables- s1, s2 and s3- are referring to three different objects and that is the reason we are getting false for s1 == s2, s1 == s3 and s2 == s3 in output.

Previously we have seen how we can create an object of java.lang.String class. We can recap here that all the existing objects of String class are Immutable. In Immutable objects we cannot perform any changes. If we try to perform any changes in immutable objects, like concatenation, then JVM will create a new object of String class again and again along with the resultant String literal.

            
            class A{
	public static void main(String arg[]){
		
		String s1 = "Hello";
		String s2 = "JTC";
		String s3 = s1 + s2;
		String s4 = "HelloJTC";
		
		System.out.println("s1 == s3 :- "+(s1 == s3)); // false
		System.out.println("s1 == s2 :- "+(s1 == s2)); // false
		System.out.println("s3 == s4 :- "+(s3 == s4)); // false
		
		System.out.println("s1 :- "+s1); // Hello
		System.out.println("s2 :- "+s2); // JTC
		System.out.println("s3 :- "+s3); // HelloJTC
		System.out.println("s4 :- "+s4); // HelloJTC
	}
}
    s1 == s3 :- false
    s1 == s2 :- false
    s3 == s4 :- false
    s1 :- Hello
    s2 :- JTC
    s3 :- HelloJTC
    s4 :- HelloJTC
            

In this example we will understand what happens internally when we perform concatenation operation along with an existing object of String class.
As we can see in the above example we have two different objects of String class that have been created using String literals “Hello” and “JTC”, so here we get two new objects of String class in SCP that are referred by s1 and s2 respectively.

Thereafter in the next line we are concatenating s1 and s2 and storing their result in s3 String s3 = s1 + s2; so as per our discussion, one new object gets created along with resultant String literals which is “HelloJTC” and in this example that object is created in Heap area.

Finally we are creating an object of String class using “HelloJTC” string literals String s4 = “HelloJTC”; so here we get a new object in SCP and s4 reference variable refers to that newly created object.

We can see that in the output s1 and s2, s1 and s3 and s3 and s4 have been compared and the return for all the three comparisons is false. This proves that the entire String class object is immutable.

            
class A{
	public static void main(String arg[]){
		final String s1 = "Hello";
		final String s2 = "JTC";
		String s3 = s1 + s2;
		String s4 = "HelloJTC";
		
		System.out.println("s3 == s4 :- "+(s3 == s4));
	}
}
    s3 == s4 :- true
            

In the above example we can see that in class A we have two different objects of String class String s1 = “Hello” and String s2 = “JTC” and s1 and s2 both are the final type reference variable.

In the next line we are concatenating s1 and s2 and trying to store their reference result in s3. As we know that String class object is an immutable object so here we will get a new object. The new object will be created inside the SCP since its final content and reference variable s3 refers newly created in SCP.

In the next line we have String s4 = “HelloJTC” which refers to the same object as s3. That is the reason when we are comparing s3 and s4 we are getting the return as true.

• String class important methods: -

1. public int hashCode();

As we know hashCode() method is available in java.lang.Object class but in java.lang.String class it is overridden. In String class when we apply the method, we get return as the hash code of String class object on the basis of their content UNICODE.

It means in String class we can get same hash code for two different objects while having same string literals.

            
class JTC{
	public static void main(String arg[]){

		String s1 = new String("abc");
		String s2 = new String("abc");
		
		System.out.println("s1 == s2 :- "+(s1 == s2)); // false
		
		System.out.println("s1.hashCode :- "+s1.hashCode()); // 96354
		System.out.println("s2.hashCode :- "+s2.hashCode()); // 96354
	}
}
    s1 == s2 :- false
    s1.hashCode :- 96354
    s2.hashCode :- 96354
            

In the above example we are creating two different objects of String class using new operators- String s1 = new String (“abc”) and String s2 = new String(“abc”). As we discussed, these are two different objects of String class created in Heap area and that is the reason when we compare s1 == s2 we get false. However, we are getting same hash codes for both objects because both objects are having the same String literals.

2. equals(): -

In Java Programming Language equals () method is also available in java.lang.Object class which compares on the basis of references. However, in java.lang.String class equals () method has been overridden and it compares on the basis of content..

            
class JTC{
	public static void main(String arg[]){

		String s1 = new String("abc");
		String s2 = new String("abc");
		
		System.out.println("s1 == s2 :- "+(s1 == s2)); // false
		System.out.println("s1.equals(s2) :- "+(s1.equals(s2))); // true
	}
}
    s1 == s2 :- false
    s1.equals(s2) :- true
            

In the above example we are creating two objects of String class using new operator, so here we will get two different objects of String class in Heap. That is the reason when we are comparing s1 == s2 we are getting false as the result. We can see that in the next line we are comparing s1 and s2 using equals(). The method equals() of java.lang.String class compares on the basis of content, so here we get true as return.

3. public int compareTo(java.lang.Object);

Access Modifier: - public
Return Type: - int
Method Name: - compareTo()
Parameter: - java.lang.Object
Functionality: - compareTo() method compares 2 String class object on the basis of their UNICODE.

            
class A{
	public static void main(String arg[]){
		String s1 = "ABC";
		String s2 = "ABC";
		
		System.out.println("s1.compareTo(s2) :- "+(s1.compareTo(s2))); // 0

		String s3 = "ACC";
		
		System.out.println("s1.compareTo(s3) :- "+(s1.compareTo(s3))); // -1

		String s4 = "ABCJTC";
		
		System.out.println("s1.compareTo(s4) :- "+(s1.compareTo(s4))); // -3

		System.out.println("s3.compareTo(s4) :- "+(s3.compareTo(s4))); // 1
	}
}
    s1.compareTo(s2) :- 0
    s1.compareTo(s3) :- -1
    s1.compareTo(s4) :- -3
    s3.compareTo(s4) :- 1
            

In the above program we can see that we have four objects of String class String s1 = “ABC”, String s2 = “ABC”, String s3 = “ACC” and String s4 = “ABCJTC”.

When we are comparing s1 and s2 (s1.compareTo(s2)) :-

Explanation: -

String s1 = “ABC”: - A – 65 | B – 66 | C – 67 String s2 = “ABC”: - A – 65 | B – 66 | C – 67 s1.compareTo(s2) :- A – A = 65 – 65 = 0 (ok) -> B – B = 66 – 66 = 0 (ok) -> C – C = 67 – 67 = 0

In this section we can see that how the compareTo() method compares two String class objects. The method is based on subtraction of UNICODE of characters and if the result is 0 then control moves ahead to check next character. When a non-zero value is obtained as result then control does not move ahead to check the next character and returns the same non-zero value to the caller. In this section because we are not getting any non-zero value till end so the method returns 0 to the caller.

When we compare s1 and s3 (s1.compareTo(s3)): -

Explanation: -

String s1 = “ABC”: - A – 65 | B – 66 | C – 67 String s3 = “ACC”: - A – 65 | C – 67 | C – 67 s1.compareTo(s2) :- A – A = 65 – 65 = 0 (ok) -> B – B = 66 – 67 = -1 (not ok) -> so it returns -1 to the caller

In this section we are comparing s1 = “ABC” and s2 = “ACC” using compareTo() method and because B-C = 66 – 67 = -1 which is a non-zero value so control is not moving ahead to check remaining characters and is returning -1 to caller.

When we compare s1 and s4 (s1.compareTo(s4)): -

Explanation: -

String s1 = “ABC”: - A – 65 | B – 66 | C – 67 String s4 = “ABCJTC”: - A – 65 | B – 66 | C – 67 s1.compareTo (s4): - A – A = 65 – 65 = 0 (ok) -> B – B = 66 – 66 = 0 (ok) -> C - C = 67 – 67 = 0

In this section we are comparing s1 = “ABC” and s2 = “ABCJTC” using compareTo(). We can see that in s1 = “ABC” and s2 = “ABCJTC” up to character C all the characters are same . After C,The method works on the basis of String length and returns the difference between lengths of the two strings, i.e., s1.length – s2.length => 3 – 6 = -3 and we get return as -3.

When we compare s3 and s4: -

Explanation: -

String s3 = “ACC”: - A – 65 | C – 67 | C – 67 String s4 = “ABCJTC”: - A – 65 | B – 66 | C – 67 S3.compareTo (s4): - A – A = 65 – 65 = 0 (ok) -> C – B = 67 – 66 = 1 (not ok) -> so the return is 1.

In this section we are comparing s3 = “ACC” and s4 = “ABCJTC” using compareTo(),as we can see in s3 = “ACC” and s4 = “ABCJTC” second character is not matched, that is C – B = 67 – 66 = 1. The result is a non –zero value so we get return as 1.

4. public java.lang.String[] split(java.lang.String);

Access Modifier: - public
Return Type: - java.lang.String[]
Method Name: - split()
Parameter: - java.lang.String
Functionality: - split() method of java.lang.String class splits the String literals on the basis of specified string literals.

            
class JTC{
	public static void main(String arg[]){
		
		String s1 = "Hello Welcome to the JTC Tutorial";
		String ar1[] = s1.split(" ");
	
		for(int i = 0; i <= ar1.length-1; i++){
			System.out.println("Index :- "+i+" Value :- "+ar1[i]);
		}
	}
}
    Index :- 0 Value :- Hello
    Index :- 1 Value :- Welcome
    Index :- 2 Value :- to
    Index :- 3 Value :- the
    Index :- 4 Value :- JTC
    Index :- 5 Value :- Tutorial
            

In the above example we have a String class object having String literals “Hello Welcome to the JTC Tutorial” and in the next line we are invoking split() and we are passing “ ” (one space) as argument, so the split method will split the String literals on the basis of “ “.

Finally we are printing the elements of ar1 using forloop.