image
String Pool and == vs Equals
Start course
Difficulty
Beginner
Duration
1h 31m
Students
101
Ratings
4.6/5
Description

In this course, we'll learn Strings in Java. 

Learning Objectives

  • What is String?
  • Creating String Objectives
  • Useful Methods of String Class
  • Immutable String
  • StringBuffer Class
  • StringBuilder Class

Intended Audience

  • Anyone looking to get Oracle Java Certification
  • Those who want to learn the Java Programming language from scratch
  • Java developers who want to increase their knowledge
  • Beginners with no previous coding experience in Java programming
  • Those who want to learn tips and tricks in Oracle Certified Associate – Java SE 8 Programmer certification exams

Prerequisites

  • No prior knowledge is required about the Java programming language
  • Basic computer knowledge
Transcript

Hi there. In the previous video, we introduced the string subject and we made some practice with the strings. In this lesson, we'll look at some of the more detailed topics about string. As you know, there were two ways to create a string object. The first one was string literal. The string literal is the easiest and most recommended way to create strings in Java. In this way, simply we assign the characters in double quotes to the variable of the string class. So, we learned this in the previous video. But, how does it work? Each time when we create a string literal, the java virtual machine first checks the string Pool in the heap memory. 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. 

String literal provides memory efficiency, because if the object exists already in the string pool, no new objects are created. Now, let's try to understand how objects are created by using string literals and string objects. By looking at our examples in the slide, on the first line, string str1 = "hello". Here, the string object is created only in the string Pool, as you see in the diagram, and str1 object refers to it. On the second line, string str2 = "hello". Here a new string object with a string pool will not be created because the string pool contains the same object with string hello. So, the str1 object refers to the same string object in the string pool. On the 3rd line, String str3 = "Example." Here, a new string object with string 'example' is created in the string 'pool' because the string 'pool' does not contain the object with the string 'example'. This is the background event when creating a literal object. So, how does it work when we create a string object using the new keyword. Let's look at this now. As you know, in the previous video, the other way to create a string object is string object. 

We create a string object by using the new keyword. It creates two objects and one reference variable. This variable refers to the objects in the heap. As you see in the diagram in the last line, a new string object with string 'java' is created in heap. Also, the same string object is created in the string 'pool' because the string 'pool' does not contain the object with string 'Java'. However, str4 refers to only the string object in heap, not the string pool. Let's make some examples in the eclipse. In the string project, I will right click on the string example package and select 'new' and 'class'. I'll specify the class name as string 'equality' and select the checkbox to add the main method and click the finish button. First, I will create two string objects by using the new keyword. String str1 = new String and its value would be "Java programming". 

The other string object, string str2 = new String  and its value would be "Java programming" again. Now, I will create two string objects by using java string literal. String str3 = "Java programming." The other string, string str4 = " Java programming". And lastly, I'll create another string with concatenation. So, I write, string str5 = "Java" + " programming." Okay, the strings are ready. Now, let's compare these string objects by using the equality operator first. I'll create a title to separate the equality and equals from each other. Okay, if you remember, the equality operator matches the references of objects, the equality operator will return a Boolean value, that is true or false. So, the equality operator returns true if two references refer to the same object. Now, let's see whether these are the same object or not. In the first print method. 

I will print the result of str1 = str2 by using the equality operator. I'll copy this line and paste it below nine times. The second will be comparing the str1 and str3, and the third will be str1 = str4. The fourth will be str1 and str5. The fifth will be str2 and str3. The sixth will be str2 and str4. The seventh will be str2 and str5. The eighth will be str3 and str4. The ninth will be str3 and str5. And the last print method will be str4 and str5. Okay, before running the app, let's examine the equality of these strings. The first string was created using the new keyword. So, the str1 object is created in the heap. The second string was created using the new keyword again, and the str2 object is created in the heap again, but as a different object. The str3 is literal. 

So, it created in the string pool, not the heap. The str4 is also literal. So, at this stage java virtual machine checks the string pool, and since the string pool has the same value, it doesn't create another object in the pool and refers to the previous object, i.e., str3. The str5 is also literal, but it is created by concatenating two strings using the plus sign. And since these strings are literal, str5 refers to the same object in the pool, i.e., str3. So, the result will be like that. Str1 and str2 are not equal, this will be false because refers to a different object. Str1 and str3 are not equal, this will be false because refers to a different object. Str1 and str4 are not equal, this will be false because refers to a different object. 

Str1 and str5 are not equal, this will be false because refers to a different object. Str2 and str3 are not equal, this will be false because refers to a different object. Str2 and str4 are not equal, this will be false because refers to a different object. Str2 and str5 are not equal, this will be false because refers to a different object. But str3 and str4 are equal. This will be true because they refer to the same object. Str3 and str5 are equal again because this will be true. Because they refer to the same object. And lastly, str4 and str5 are equal, this will be true because they refer to the same object. So, the last three equations will be true and the others will be false. Let's run the code and observe. 

You see the results in the console. The first seven equations are false and the last three equations are true. Because when you create a new object using the new keyword, this object is created in the heap  and a different ID is given to this object. But, if you create it literally, this time it looks at the string pool instead of the heap, and if the pool doesn't have an object with the same value, it creates a new object in the pool. If you want, we can also access the identification numbers defined for the objects here. If you want, let's take a look at it and understand it better. For this, we'll use the method of the system class called identity hash code. System.out.println("ID of str1: "  + System.identityHashCode(str1)). It's enough to write the object whose ID we want to learn in parenthesis. I'm typing str1. Now, let's copy this line and paste it four times, the second will be str2. This will be str3. This will be str4 and this will be str5. Now, let's run our code once again and observe the ID numbers of the objects. And as you can see, str1 and str2 are different because they are created with the new keyword and represent different objects. But, str3, str4, and str5 are the same because they reference the same object in the pool. 

Finally, I would like to point out that, as we mentioned earlier, Java is a case sensitive language. If you write the first letter of the word, programming in lower case, these strings will no longer be equal with str3 and str4, because Java sees it as a separate value and creates a new object in the pool for it. Another usage is as follows: For example, let's create a new string, string str6 and let's pass the str1 object to the string. Currently, str1 and str6 are the same objects. More precisely str1 and str6 are the same as they point to the same object. If we want to print this to the console as well, we will still get the result True. You can test this yourself. As a result if two string objects are matched using the equality operator, you need to see if they are created with the new keyword or literal. Now let's look at the comparison of these strings with the equals method. The equals method matches the values or contents of the objects. 

The equals method returns a boolean value, that is true or false. Equals method returns true, if two string objects contain the same content or values. So, I will copy these two print methods and paste them here. First, the title will be equals. And now let's change the equality operator to the equals method. This will be str1.equals str2 and I'll copy this method and paste it nine times. The second will be comparing the str1 and str3 and the third will be str1 is equal to str4. The fourth will be str1 and str5. The fifth will be str2 and str3. The sixth will be str2 and str4. The seventh will be str2 and str5. The eighth will be str3 and str4. The ninth will be str3 and str5 and the last print method will be str4 and str5. If we run the application like this, all comparisons including str2 will be false because if you notice the first word of Java is lower case and the str2 variable, in other variables, the first letter of java is capitalized. This content is different from the others because java is a case sensitive language. 

If you want let's run the application and test it. As you can see the 1st, 5th, 6th and 7th results are false. Notice that these are comparisons with str2. If we fix that then all will be true. Let's fix it now. Yes all results will now be true. Let's run it again now. As you can see, all results are true. The equals method doesn't look at the identity, it looks at the value or content. Now, I will show you another thing, first I will convert these codes to the comment line. Now let's create a string, String s1 = "Java Programming"  and another string, string s2 = " Programming" and another string, String  s3 = "Java" + s2. So, let's look at the equality of these strings. The s1 is literal, so it is created in the string pool, not the heap and its value is Java programming. 

The s2 is literal again. So, it's created in the string pool, not the heap and its value is a space programming. So, the last string i.e., s3 is created by concatenating two strings, but the first string is literal and the other one is an object. So, this time JVM creates another object. For this reason, if we compare these strings with the equality operator, all results will be false, but we compare these with the equals method. Since the 1st and 3rd strings are the same the result will be true. Let's print them on the console. System.out.println(S1=S2);  System.out.println(s2=s3); System.out.println (s2=s3). Now, let's run it and see, as you can see all results are false. Now, let's compare them with the equals method. System.out.println(s1.equals s2);  System.out.println ( s1. equals s3); System.out.println ( s2. equals s3). Now, let's run it and see as you can see the 1st and 3rd results are false but the second result i.e., s1.equals s3 is true because they have the same content. 

I think the equality of strings is understood. Now, let's take a look at the equality of the primitive and wrapper classes, but first I will convert these lines to the comment line. For example, let's create an integer object, integer num1 = new integer (5). As you can see new integer statement is crossed out. This means that this is deprecated. If you remember we talked about auto boxing and auto unboxing concepts in our previous lessons. Since, these operations are done automatically in Java five and later such usage is no longer in question. That's why I'm deleting this. I just write five after equals. Now, let's create an int variable, int num2 = 5. Let's compare num1 and num2. System.out.println (num1 = num 2), System.out.println(num1. equals (num2). Let's review the code before testing it. Notice that creating an integer object using the new keyword is not allowed. So, num1 and num2 are literally created. So, in this case both results will be true. 

Now, let's run it and observe the result. As you can see the result is true for both. You can try this yourself for double and other wrapper classes. I just wanted to show you this difference. Finally let's look at the equality in arrays. I will convert these lines to the comment line. I'll create four string arrays, String [] cars1 = {"Ferrari" "Mercedes" "BMW"}. Now, let's create the second array String [] Cars2 = new string []. The length of this array will be three. And the elements of this array will be the same as the cars1 array, so I'll copy these elements and paste them here. Okay, now let's create the third array. String [] cars3 = new String [3]. Now, let's specify the elements of this array. Cars3 [0]. 

So, the zero represents the zero with index of this array i.e., the first element. The first element will be Ferrari, second element will be Mercedes, and the last element will be BMW. Okay, now let's create the last array String [] cars4 = cars2. Okay, now the arrays are ready. Now, let's print the equality of these arrays with the 'is equal to' operator S out cars1 = cars2. I'll copy this line and paste it five times. This will be cars1 and cars3. This will be cars1 and cars4. This will be cars2 and cars3. This will be cars2 and cars4. This will be cars3 and cars4. Before testing, let's examine. In arrays, when you create a new array, you actually create a different object for each array. So, since the 'is equal to' operator compares the objects, the first three arrays will be different from each other. 

But the cars4 array will be the same as the cars2 array, because theirs is the same object, only the reference will change, but the object is the same. So, the fifth print method will print the true and others will print false. So, now let's run and see. As you can see, only the fifth result is true, the others are false. Now, let's compare the equality of these arrays using the equals method. I'll create a title to separate the equality and equals from each other. So, the title can be equals. Okay, now I'll copy this method and paste it here. So this will be cars1. = cars2. And I will copy this line and paste it below five times. This will be cars1. = cars3, and this will be cars1. and cars4. This will be cars2. and cars3. This will be cars2. and cars4. And lastly, this will be cars3. and cars4. Okay, before testing, let's examine this. 

The equals method works differently in arrays according to the strings. Remember, the equals compares the content of the strings. So, if the content is the same, it returns true, else it returns false. But in the array, the equals method works as the 'is equal to' operator, so it compares the object again, not the content. If you press the control key on the keyboard, and click the equals method here, it will open the equals method in the object class. And as you can see, it checks with the 'is equal to' operator. So, for this reason the result will be the same as 'is equal to.' So, the fifth will be true and the others will be false again. Let's run and see. As you can see, the result is the same. This is the difference between the usage of the equals method in array and strings, but if we want to compare the elements of the arrays, this time we can use the equals method of the arrays, not the object class. Let's look at that. I will copy these two lines and paste them here. 

The title can be Arrays.equals and this will be Arrays.equals  (cars1, cars2). So, this will match each element of the arrays respectively. In the first element of the cars1 array with the first element of the cars2. The second with the second, and the third with the third. If it is the same, it returns true, else, returns false. Now, let's match the other arrays. I will copy this line and paste it five times. The second will be cars1 and cars3. The third will be cars1 and cars4. The forth will be cars2 and cars3. The fifth will be cars2 and cars4. The last will be cars3 and cars4. Okay, all these methods will print true because all elements of these arrays are the same. Let's run and see. As you can see, the result is true for all cases. Okay, I think the difference between the 'is equal to' operator and the equals method is understood. Let's take a short break here. See you in the next video.

 

About the Author
Students
3925
Courses
64
Learning Paths
5

OAK Academy is made up of tech experts who have been in the sector for years and years and are deeply rooted in the tech world. They specialize in critical areas like cybersecurity, coding, IT, game development, app monetization, and mobile development.

Covered Topics