Java Support Operator Overloading – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Mon, 04 Jul 2022 05:41:53 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg Java Support Operator Overloading – Programmerbay https://programmerbay.com 32 32 Does Java Support Operator Overloading? https://programmerbay.com/does-java-support-operator-overloading/ https://programmerbay.com/does-java-support-operator-overloading/#respond Sat, 18 Jun 2022 07:38:01 +0000 https://programmerbay.com/?p=8638 Operator overloading can be defined as the ability to achieve different behaviour from an operator, other than expected behaviour, based on the arguments.

It comes under static polymorphism.

C++ allows operator overloading which enables a user to redefine the operator behaviour. To overload an operator, the operator keyword is used. Similar to function, it can have arguments and return type. It can also be used with user-defined types.

Syntax in C++:

returnType operator operatorSymbol( argument );

void operator ++ () {

// logic here

}


Unlike C++ or Kotlin, Java doesn’t provide support for operator overloading. The only operator that is overloaded + operator, which can be used for concatenation of two strings and arithmetic addition. However, a programmer is not allowed to overload an operator in Java.

To not have operator overloading is the design decision of Java language creators. Operator overloading allows redefining the meaning of an operator which can increase the complexity. Like, an arithmetic operator should operate in arithmetic operations rather than working for other purposes. To avoid confusion and complexity in this language, Java designers decide to keep it simple and transparent.

Below are some reasons why operator overloading may not part of the Java feature.

Ease: Operator overloading empowers an operator to have multiple operational meanings which might slow down the JVM at the time of identifying the respective behaviour of that very operator, preventing it from simplicity and transparency. This can increase the design complexity and reduces the JVM efficiency.

Multiple Definitions: Operator overloading enables a developer to develop user-defined functionality of an operator that can lead to difficulty for others to figure out the actual functionality of that operator. It becomes more error-prone in a program which might increase development and delivery time.

Method overloading: Method overloading is a more sophisticated and clean way to achieve the same functionality than Operator overloading, as a result, it doesn’t make sense in the first place to have such a feature. Operator overloading increases the JVM’s design complexity which might turn its speed slower.

]]>
https://programmerbay.com/does-java-support-operator-overloading/feed/ 0