• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Format

 
Balaji Bang
Ranch Hand
Posts: 182
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Output is 1

I thought it will expect a String parameter and gives Runtime Exception.

But for gives error.
 
Sagar Rohankar
Ranch Hand
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Banu Chowdary wrote:

Output is 1

I thought it will expect a String parameter and gives Runtime Exception.


Have you looked at format() methods signature, it takes var arg type of Object., So 1 is autoboxed in Integer type. No Exception !

Banu Chowdary wrote:
But for gives error.


It doesn't give error, because it syntactically correct, but throws RuntimeException , stating "IllegalFormatConversionException: d != java.lang.String" , it means, you passed string and format specifier expect a Integer object or int.
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Banu remember Object class has toString() method and Integer class overrides this method.

so it will be converted to

As format method takes var-args. And Integer.toString() will be used to print String.


will be converted to

It will not run Object class does not have any method to convert String to Integer.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic