Java Introduction
Getting Started
Java Syntax
Java Output – Printing Text
Java Output: Printing Numbers
Java Comments
Java Variables
Java Print Variables
Java: Declare Multiple Variables
Java Identifiers
Real-Life Examples
Java Type Casting
Java Data Types
Java Numbers
Java Boolean
Java Characters and Strings
Real-Life Example
Advanced Billing Example
….
🛒 Real-Life Example – Calculating Total Order Cost
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
- Mixing Data Types:
We usedint
for the number of items,float
for cost per item, andchar
for the currency symbol. - Automatic Type Conversion:
When multiplyingint
andfloat
, Java automatically promotes the result to afloat
. - Readability:
Proper variable names likeitems
,costPerItem
, andtotalCost
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