Java String to lowercase() Method

Java String to lowercase() Method

As mentioned above, and as the name suggests, this method is going to get us the lowercase version of the string. Always remember that the strings are immutable. We have seen a program above for this method, but still, for getting a clearer picture, let’s again do it.

public class StringMethods {
public static void main(String[] args) {
String exampleString = “THIS IS IN ALL CAPITAL, BUT YOU WON’T SEE IT THAT WAY!”;
System.out.println(exampleString.toLowerCase());
System.out.println(exampleString);
}
}

So, we first get the output, in all lowercase, since we have invoked the method toLowerCase() for the example string. But just to mention that the original string has not changed, I tried printing the string variable again, and the output is the normal string like we have initialized, in all caps. So, from this, it is clear that for the new value, which is a lowercase version of that string, we had to have a separate object. Now, what if I do something like this? →

public class StringMethods {
public static void main(String[] args) {
String exampleString = “THIS IS IN ALL CAPITAL, BUT YOU WON’T SEE IT THAT WAY!”;
exampleString = exampleString.toLowerCase();
System.out.println(exampleString);
}
}

Now, if we try running this program, we can have a look that the example string variable now points to the lowercase version of the string. Now again you might say hey… how come now we were able to change the value of the string? Then again I want to remind you of the thing that the object which contains the string in all capital letters which was created before this, is still there.

When we invoked the method toLowerCase(), we created a new object with the lowercase version of the string. Now, we are reassigning the string variable which was earlier pointing to another object, and now making the string variable point to this newly created object. So, the value is not being changed, but a new object is being created and the string variable is being made to point to the newly created object.

Now if you are wondering what happened to the previous object then? Well, for that object, if there is no reference towards it, it will be eligible for something called garbage collection. Well, garbage collection is something that we are going to discuss a little ahead, but just to tell you that garbage collection is a process for memory management. Since the object wasn’t referred, it will be cleared for efficient memory management. In other words, the object was unused, and the unused objects are deleted by the garbage collector for efficient memory management.

So, I just wanted to mention these things so that we can avoid getting into any kind of problem. So, with this said, let’s now get ahead and implement several other methods related to strings.