Avinash Kumar
Avinash Kumar

Reputation: 318

Is the use of % in printf operator overloading? If not, what is it?

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?

Upvotes: 0

Views: 138

Answers (2)

Vince
Vince

Reputation: 15156

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.

Upvotes: 1

Oleg
Oleg

Reputation: 6314

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.

Upvotes: 1

Related Questions