Java Data Types Example: Calculating Total Cost of Items
Discover a practical example showcasing the use of various data types in Java to calculate and display the total cost of multiple items. This guide illustrates how to effectively utilize different data types, such as int
for quantities, double
for prices, and String
for item names, to create a simple yet functional program. Enhance your understanding of data types in Java through this real-world application.
Java Data Types Example
Real-Life Example
Here's a real-life example demonstrating the use of different data types in Java to calculate and output the total cost of a number of items:
Example
// Create variables of different data types
int items = 50;
float costPerItem = 9.99f;
float totalCost = items * costPerItem;
char currency = '$';
// Print variables
System.out.println("Number of items: " + items);
System.out.println("Cost per item: " + costPerItem + currency);
System.out.println("Total cost = " + totalCost + currency);
In this example:
items
is anint
storing the number of items.costPerItem
is afloat
storing the cost per item.totalCost
is afloat
storing the calculated total cost.currency
is achar
storing the currency symbol ('$' in this case).
The System.out.println
statements display these variables along with descriptive text.