Operator overloading

Question: Why java does not support operator overloading?
Answer: Operator overloading means to use the same operator for different data types. A programmer can provide his or her own operator to a class by overloading the built-in operator to perform some specific computation when the operator is used on objects of that class. Below are the reasons why java does not support operator overloading.
  • Operator overloading can be exceedingly confusing. Keeping the human tendency in mind that some operators have specific meaning and if changed then programmers tend to make errors.
  • By not supporting operator overloading, the code would be simple and clear which was one of the primary goals of java designers. And the same thing can be achieved by method overloading.
  • Operator overloading also makes the task of JVM complex. What this means that JVM takes more time to execute programs.
The only overloaded operator in Java is the arithmetic "+" operator. When "+" is used with integers it adds them. When the same "+" is used with strings it concatenates them. This can be explained with a simple example as shown below.
 package com.ram;

public class OperatorOverloading {
 public static void main(String[] args) {
  int a = 10;
  int b = 20;
  int c;
  String firstName = "Ram";
  String lastName = "Akunuru";
  String name;
  
  c = a + b; //Here "+" is used to add two integers.
  System.out.println("c = "+c);
  
  name = firstName + lastName; //Here "+" is used to concatenate the strings
  System.out.println("Name = "+name);
 }
}
 
 
Output:
c = 30
Name = RamAkunuru

No comments:

Post a Comment