In: Computer Science
What is the output of the following piece of Java code?
int id = 4; double grossPay = 81.475; String jobType = "Intern"; System.out.printf("Id: %d, Type: %s, Amount:%.2f", id,grossPay,jobType);
Select one:
Error
Id: 4, Type: Intern, Amount: $81.475
Id: 4, Type: $81.475, Amount: Intern
Id: 4, Type: $81.48, Amount:Intern
Id: 4, Type: Intern, Amount: $81.48
Output: Error
There is a Runtime error in the code, not a compile-time error.
Runtime Error :
Exception in thread "main" java.util.IllegalFormatConversionException: f != java.lang.String.
System.out.printf("Id: %d, Type: %s, Amount:%.2f", id,grossPay,jobType);
In this statement, for grossPay, %s is used as the format specifier, but grossPay is double so it has to be %f .
Correction:
System.out.printf("Id: %d, Type: %.2f, Amount:%s", id,grossPay,jobType);
Program:
class Output
{
public static void main(String args[])
{
int id = 4;
double grossPay = 81.475;
String jobType = "Intern";
System.out.printf("Id: %d, Type: %.2f, Amount:%s",
id,grossPay,jobType);
}
}
Output: