Table of contents
Chief Concept
One of the central features of Java is that it does not support the function of operator overloading. Now, the term 'operator overloading' in simple definition is so, when an operator tends to perform different operator functions on different types of datatypes. For example, the + operator can work on both integers as well as strings performing addition and string concatenation respectively.
Main Read
While studying the data structure "String" and using Java as the high-level language for it, the cardinal concept of the arithmetic operation '+' and its value in strings come into the picture.
The exception arises in the string datatype, here Java allows the operator to overload.
Even when the basic output command of
The command println() uses a method ToString() to first convert the given datatype to String and then only the '+' operator could be used. If we want the addition of an integer, then first the "int" would be converted to a Wrapper class (This gives us more flexibility in storing, converting and manipulating an "int" datatype), then println class the method ToString(), and after all this happens we hence get the output.
The '+' operator works under only two conditions:
If it's used between primitives
Used in complex situations, under a single condition that one of the datatypes should always include String. Hence, the output also will be of type string.
All, this is done to ensure smooth learning and programming in Java. It eliminates any dubiety of any sort as the programmers can't have multiple meanings for the same operator.
Shortcomings
But, this causes hindrance in the String performance if a memory load code is there. For example
If the dry run the above code, it would go something like this:
"" + "a" = "a"
"a" + "b" = "ab"
"ab" + "c" = "abc"
"abc" + "d" = "abcd"
This would go till we reach the end of the alphabetical series, the iterations would go like this
a, ab , abc , abcd , abcde , .................................. , abcdefghijklmopqrstuvwxyz
So, each time a new object is being created, so much extra memory is getting used up in doing so and being passed on after each iteration, also to add all of the above objects won't have a reference variable, hence all the space wastage occurs just for the 'series' pointer to point towards the last string that is abcdefghijklmnopqrstuvwxyz.
Here, the role of String Builder comes into play, which I will talk about in some other article as that opens the door to raw Java methods and classes such as String Buffer, the library of java.lang.Object etc.
Hope, you liked this article and learned something new, and I will see you in the next post.
Keep Creating, Keep Exploring
---> Shrey Kothari