0

Please explain what happening here:

class Test{
public static void main(String[] args){
    int a = 43%2;
    System.out.printf("The test remainder is %d %s",a,"hello");
 }
}

In the above code i want to know is it operator overloading of the % operator?

Vince
  • 14,470
  • 7
  • 39
  • 84
Avinash Kumar
  • 288
  • 6
  • 21
  • Are you asking about the `int a = 43 % 2;` or the use of `%` in the format string? – Jon Skeet Aug 06 '17 at 11:30
  • Java currently doesn't support operator overloading. The only built-in operator overload is for numeric and `String` values. – Vince Aug 06 '17 at 11:30
  • while i replacing or removing % from string, output not shown. if changing order of %d %s then exception thrown. why? – Avinash Kumar Aug 06 '17 at 11:36
  • Possible duplicate of [Operator overloading in Java](https://stackoverflow.com/questions/1686699/operator-overloading-in-java) – Sarah Aziziyan Aug 06 '17 at 11:37

2 Answers2

1

Looks like you're confused by the usage of % in a String.

Anything that is enclosed between "" in Java is not an operator. So when you have code like
43 % 2 the % is an operator but when you have a String like "asdf%asdf%++*adsf" the % + and * are not operators. Also Java doesn't have operator overloading.

The printf function uses % to mark the position where it will later put the variables you pass to it, it could've been any other symbol and has nothing to do with operator overloading.

Oleg
  • 6,124
  • 2
  • 23
  • 40
1

Nope. Java currently has very limited support for operator overloading, and this is not one of those cases.

The % in the string literal is handled by the implementation of java.util.Formatter. String#format and PrintWriter#printf delegate the formatting work to Formatter, which manually parses the string.

The only reason % has value there is due to how Formatter handles the string.

If you view the code, you'll find:

if (conversion == '%' || conversion == 'n')

followed by a switch statement which handles the different types.

Vince
  • 14,470
  • 7
  • 39
  • 84