In Java, you often use multiple data types together to solve real-world problems. Here’s an example where we calculate the total cost of a purchase using integers, floats, and characters.


🧾 Example: Shopping Cart Calculation

public class ShoppingCart {
    public static void main(String[] args) {
        // Number of items purchased
        int items = 50;

        // Cost of each item
        float costPerItem = 9.99f;

        // Currency symbol
        char currency = '$';

        // Calculate total cost
        float totalCost = items * costPerItem;

        // Print purchase details
        System.out.println("Number of items: " + items);
        System.out.println("Cost per item: " + costPerItem + currency);
        System.out.println("Total cost = " + totalCost + currency);
    }
}

✅ Output:

Number of items: 50
Cost per item: 9.99$
Total cost = 499.5$

💡 Key Points to Note

  1. Mixing Data Types:
    We used int for the number of items, float for cost per item, and char for the currency symbol.
  2. Automatic Type Conversion:
    When multiplying int and float, Java automatically promotes the result to a float.
  3. Readability:
    Proper variable names like items, costPerItem, and totalCost make the program easier to understand and maintain.

🏪 Real-World Scenarios

This approach can be applied to:

  • E-commerce apps (price calculation and discounts)
  • Inventory management systems
  • Billing and invoice generation
  • Restaurant POS (Point of Sale) software

🔥 GoNimbus Pro Challenge

Want to level up?
Modify the program to:

  • Add discount percentage
  • Include tax rate
  • Print the final payable amount

Scroll to Top