Java Variables - Real Life Examples
Practical Variable Usage in Real Applications
Variables are the foundation of storing and working with data in Java. They represent information such as user details, prices, balances, or sensor readings. Real-world applications rely heavily on variables to handle state and process data.
In this section, we’ll explore variables in contexts such as user authentication, e-commerce systems, banking applications, and data processing to see how different variable types solve everyday problems.
User Authentication System
In authentication systems, variables hold user credentials, attempt counts, and status flags. Constants are also used to define rules like maximum attempts.
import java.util.Scanner;
public class AuthenticationSystem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
final String STORED_USERNAME = "admin";
final String STORED_PASSWORD_HASH = Integer.toHexString("password".hashCode());
final int MAX_ATTEMPTS = 3;
String enteredUsername;
String enteredPassword;
int attemptCount = 0;
boolean isAuthenticated = false;
while (attemptCount < MAX_ATTEMPTS && !isAuthenticated) {
System.out.print("Enter username: ");
enteredUsername = scanner.nextLine();
System.out.print("Enter password: ");
enteredPassword = scanner.nextLine();
String enteredHash = Integer.toHexString(enteredPassword.hashCode());
if (enteredUsername.equals(STORED_USERNAME) && enteredHash.equals(STORED_PASSWORD_HASH)) {
isAuthenticated = true;
System.out.println("Authentication successful! Welcome, " + enteredUsername + ".");
} else {
attemptCount++;
int remaining = MAX_ATTEMPTS - attemptCount;
System.out.println("Invalid credentials. Attempts remaining: " + remaining);
}
}
if (!isAuthenticated) {
System.out.println("Maximum attempts reached. Account locked.");
}
scanner.close();
}
}
Enter username: admin Enter password: password Authentication successful! Welcome, admin.
E-commerce Shopping Cart
In e-commerce systems, variables represent product information, cart contents, prices, and totals. They are updated dynamically as the user interacts with the cart.
import java.util.ArrayList;
import java.util.List;
public class ShoppingCart {
public static void main(String[] args) {
String[] productNames = {"Laptop", "Mouse", "Keyboard", "Monitor"};
double[] productPrices = {999.99, 25.50, 75.00, 299.99};
int[] productStock = {10, 50, 30, 15};
List<String> cartItems = new ArrayList<>();
List<Integer> cartQuantities = new ArrayList<>();
List<Double> cartPrices = new ArrayList<>();
addToCart(cartItems, cartQuantities, cartPrices, productNames, productPrices, productStock, 0, 1);
addToCart(cartItems, cartQuantities, cartPrices, productNames, productPrices, productStock, 1, 2);
addToCart(cartItems, cartQuantities, cartPrices, productNames, productPrices, productStock, 2, 1);
double subtotal = calculateSubtotal(cartQuantities, cartPrices);
double taxRate = 0.08;
double taxAmount = subtotal * taxRate;
double grandTotal = subtotal + taxAmount;
System.out.println("=== SHOPPING CART ===");
for (int i = 0; i < cartItems.size(); i++) {
System.out.printf("%-10s x%d @ $%.2f = $%.2f%n", cartItems.get(i), cartQuantities.get(i), cartPrices.get(i), cartQuantities.get(i) * cartPrices.get(i));
}
System.out.println("\n=== ORDER SUMMARY ===");
System.out.printf("Subtotal: $%.2f%n", subtotal);
System.out.printf("Tax (8%%): $%.2f%n", taxAmount);
System.out.printf("Total: $%.2f%n", grandTotal);
System.out.println("\n=== UPDATED STOCK ===");
for (int i = 0; i < productNames.length; i++) {
System.out.printf("%-10s: %d remaining%n", productNames[i], productStock[i]);
}
}
private static void addToCart(List<String> items, List<Integer> quantities, List<Double> prices, String[] names, double[] pricesArr, int[] stock, int index, int qty) {
if (stock[index] >= qty) {
items.add(names[index]);
quantities.add(qty);
prices.add(pricesArr[index]);
stock[index] -= qty;
} else {
System.out.println("Insufficient stock for " + names[index]);
}
}
private static double calculateSubtotal(List<Integer> quantities, List<Double> prices) {
double total = 0;
for (int i = 0; i < quantities.size(); i++) {
total += quantities.get(i) * prices.get(i);
}
return total;
}
}
=== SHOPPING CART === Laptop x1 @ $999.99 = $999.99 Mouse x2 @ $25.50 = $51.00 Keyboard x1 @ $75.00 = $75.00 === ORDER SUMMARY === Subtotal: $1125.99 Tax (8%): $90.08 Total: $1216.07 === UPDATED STOCK === Laptop : 9 remaining Mouse : 48 remaining Keyboard : 29 remaining Monitor : 15 remaining
Banking Application
Banking applications rely on variables to store account details, track balances, and record transactions. Constants define rules like overdraft limits.
import java.text.NumberFormat;
import java.util.Locale;
public class BankingApplication {
public static void main(String[] args) {
String accountNumber = "ACC-123456";
String accountHolder = "John Doe";
double accountBalance = 5000.00;
final double OVERDRAFT_LIMIT = -1000.00;
String[] transactionTypes = new String[10];
double[] transactionAmounts = new double[10];
double[] transactionBalances = new double[10];
int transactionCount = 0;
NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.US);
accountBalance = processTransaction("DEPOSIT", 1000.00, accountBalance, transactionTypes, transactionAmounts, transactionBalances, transactionCount++);
accountBalance = processTransaction("WITHDRAWAL", 250.50, accountBalance, transactionTypes, transactionAmounts, transactionBalances, transactionCount++);
accountBalance = processTransaction("WITHDRAWAL", 1500.00, accountBalance, transactionTypes, transactionAmounts, transactionBalances, transactionCount++);
accountBalance = processTransaction("TRANSFER", 2000.00, accountBalance, transactionTypes, transactionAmounts, transactionBalances, transactionCount++);
System.out.println("=== ACCOUNT SUMMARY ===");
System.out.println("Account: " + accountNumber);
System.out.println("Holder: " + accountHolder);
System.out.println("Balance: " + currency.format(accountBalance));
System.out.println("\n=== TRANSACTION HISTORY ===");
System.out.printf("%-12s %-12s %-12s%n", "Type", "Amount", "Balance");
for (int i = 0; i < transactionCount; i++) {
System.out.printf("%-12s %-12s %-12s%n", transactionTypes[i], currency.format(transactionAmounts[i]), currency.format(transactionBalances[i]));
}
double annualInterestRate = 0.025;
double monthlyInterest = accountBalance * (annualInterestRate / 12);
System.out.printf("\nProjected monthly interest: %s%n", currency.format(monthlyInterest));
}
private static double processTransaction(String type, double amount, double currentBalance, String[] types, double[] amounts, double[] balances, int index) {
double newBalance = currentBalance;
if (type.equals("DEPOSIT") || type.equals("TRANSFER_IN")) {
newBalance += amount;
} else if (type.equals("WITHDRAWAL") || type.equals("TRANSFER")) {
if (currentBalance - amount >= -1000.00) {
newBalance -= amount;
} else {
System.out.println("Transaction declined: Overdraft limit exceeded");
return currentBalance;
}
}
types[index] = type;
amounts[index] = (type.equals("WITHDRAWAL") || type.equals("TRANSFER")) ? -amount : amount;
balances[index] = newBalance;
return newBalance;
}
}
=== ACCOUNT SUMMARY === Account: ACC-123456 Holder: John Doe Balance: $3,250.00 === TRANSACTION HISTORY === Type Amount Balance DEPOSIT $1,000.00 $6,000.00 WITHDRAWAL ($250.50) $5,749.50 WITHDRAWAL ($1,500.00) $4,249.50 TRANSFER ($2,000.00) $2,249.50 Projected monthly interest: $4.69
Data Processing and Analysis
Variables are also central in analyzing datasets. They store metrics such as totals, averages, and counts. Here’s how variables help calculate statistics and categorize data.
public class DataAnalysis {
public static void main(String[] args) {
double[] temperatures = {72.5, 68.3, 75.1, 69.8, 71.2, 73.6, 70.4, 74.9, 67.5, 76.2};
double sum = 0;
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
int count = temperatures.length;
for (double temp : temperatures) {
sum += temp;
if (temp < min) min = temp;
if (temp > max) max = temp;
}
double mean = sum / count;
double varianceSum = 0;
for (double temp : temperatures) {
varianceSum += Math.pow(temp - mean, 2);
}
double variance = varianceSum / count;
double standardDeviation = Math.sqrt(variance);
System.out.println("=== TEMPERATURE ANALYSIS ===");
System.out.printf("Dataset size: %d readings%n", count);
System.out.printf("Mean temperature: %.2f°F%n", mean);
System.out.printf("Minimum temperature: %.2f°F%n", min);
System.out.printf("Maximum temperature: %.2f°F%n", max);
System.out.printf("Temperature range: %.2f°F%n", max - min);
System.out.printf("Variance: %.4f%n", variance);
System.out.printf("Standard Deviation: %.4f%n", standardDeviation);
int mild = 0, warm = 0, hot = 0;
for (double temp : temperatures) {
if (temp < 70) mild++;
else if (temp < 75) warm++;
else hot++;
}
System.out.println("\n=== TEMPERATURE CATEGORIES ===");
System.out.printf("Mild (<70°F): %d readings (%.1f%%)%n", mild, (mild * 100.0 / count));
System.out.printf("Warm (70-75°F): %d readings (%.1f%%)%n", warm, (warm * 100.0 / count));
System.out.printf("Hot (>75°F): %d readings (%.1f%%)%n", hot, (hot * 100.0 / count));
System.out.println("\n=== CELSIUS CONVERSION ===");
System.out.printf("%-10s %-10s%n", "Fahrenheit", "Celsius");
for (double f : temperatures) {
double c = (f - 32) * 5.0 / 9.0;
System.out.printf("%-10.1f %-10.1f%n", f, c);
}
}
}
=== TEMPERATURE ANALYSIS === Dataset size: 10 readings Mean temperature: 71.95°F Minimum temperature: 67.50°F Maximum temperature: 76.20°F Temperature range: 8.70°F Variance: 8.5285 Standard Deviation: 2.9204 === TEMPERATURE CATEGORIES === Mild (<70°F): 2 readings (20.0%) Warm (70-75°F): 5 readings (50.0%) Hot (>75°F): 3 readings (30.0%) === CELSIUS CONVERSION === Fahrenheit Celsius 72.5 22.5 68.3 20.2 75.1 23.9 69.8 21.0 71.2 21.8 73.6 23.1 70.4 21.3 74.9 23.8 67.5 19.7 76.2 24.6