Bird
0
0

What will be the output of this Java code?

medium📝 Predict Output Q5 of 15
Java - Object-Oriented Programming Concepts
What will be the output of this Java code?
class Product {
  String name;
  double price;
  void display() {
    System.out.println(name + ": $" + price);
  }
}
public class Shop {
  public static void main(String[] args) {
    Product p = new Product();
    p.name = "Pen";
    p.price = 1.5;
    p.display();
  }
}
APen: $1.5
BPen: $1,5
Cnull: $0.0
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Assign values to object fields

    The Product object has name "Pen" and price 1.5 assigned.
  2. Step 2: Output format in display method

    Display prints name, colon, dollar sign, and price as a decimal number.
  3. Final Answer:

    Pen: $1.5 -> Option A
  4. Quick Check:

    Field values printed correctly = Pen: $1.5 [OK]
Quick Trick: Use dot to separate decimals in Java numbers [OK]
Common Mistakes:
  • Using comma instead of dot
  • Not assigning fields
  • Expecting different output format

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes