Packages and Import Statements in Java

Introduction

Imagine you're organizing a massive library with millions of books. Without a system, finding a specific book would be chaos! Packages and Import Statements in Java work exactly like that—they organize classes into logical folders and give you shortcuts to access them, making your codebase clean, manageable, and conflict-free.

Packages are like digital folders that group related classes together, while import statements are like bookmarks that help you quickly access classes from other packages without typing their full paths every time.


What are Packages and Import Statements?

Packages are namespaces that organize related classes and interfaces. Import statements bring those classes into your current file's scope so you can use them without fully qualified names.

Key Characteristics:

  • Organization: Logical grouping of related classes
  • Namespace management: Prevent naming conflicts
  • Access control: Package-private visibility
  • Reusability: Easy to share and distribute code
  • Import convenience: Shortcut to use classes from other packages

Package and Import Hierarchy

project/
├── com/
│   ├── company/
│   │   ├── app/
│   │   │   ├── Main.java
│   │   │   ├── models/
│   │   │   │   ├── User.java
│   │   │   │   └── Product.java
│   │   │   └── utils/
│   │   │       ├── Validator.java
│   │   │       └── Formatter.java
│   │   └── database/
│   │       ├── Database.java
│   │       └── Connection.java
└── org/
└── external/
└── library/
└── MathUtils.java

Code Explanation with Examples

Example 1: Basic Package Structure and Imports

Directory Structure:

src/
├── com/
│   └── company/
│       └── app/
│           ├── Main.java
│           ├── models/
│           │   ├── User.java
│           │   └── Product.java
│           └── utils/
│               ├── Validator.java
│               └── Formatter.java
// File: src/com/company/app/Main.java
package com.company.app;
// Import specific classes
import com.company.app.models.User;
import com.company.app.models.Product;
import com.company.app.utils.Validator;
import com.company.app.utils.Formatter;
// Import static members
import static java.lang.Math.PI;
import static java.lang.Math.pow;
import static java.lang.System.out;
// Wildcard import for related classes
import java.util.*; // imports List, ArrayList, Map, etc.
public class Main {
public static void main(String[] args) {
System.out.println("=== PACKAGES AND IMPORTS DEMO ===");
// Using imported classes
User user = new User("Alice", "[email protected]");
Product product = new Product("Laptop", 999.99);
Validator validator = new Validator();
Formatter formatter = new Formatter();
// Using static imports
out.println("PI value: " + PI);
out.println("2^8 = " + pow(2, 8));
// Using wildcard imports
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
out.println("Names: " + names);
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);
scores.put("Bob", 87);
out.println("Scores: " + scores);
// Using fully qualified names (without import)
java.time.LocalDateTime now = java.time.LocalDateTime.now();
out.println("Current time: " + now);
// Demonstrate package functionality
validator.validateUser(user);
formatter.formatProduct(product);
}
}
// File: src/com/company/app/models/User.java
package com.company.app.models;
// Import from same package is implicit
// Import from other packages needs explicit import
import com.company.app.utils.Validator;
public class User {
private String name;
private String email;
public User(String name, String email) {
this.name = name;
this.email = email;
}
// Getters and setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
@Override
public String toString() {
return String.format("User{name='%s', email='%s'}", name, email);
}
}
// File: src/com/company/app/models/Product.java
package com.company.app.models;
public class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
// Getters and setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
@Override
public String toString() {
return String.format("Product{name='%s', price=%.2f}", name, price);
}
}
// File: src/com/company/app/utils/Validator.java
package com.company.app.utils;
// Import from models package
import com.company.app.models.User;
public class Validator {
public void validateUser(User user) {
System.out.println("🔍 Validating user: " + user.getName());
if (user.getName() == null || user.getName().trim().isEmpty()) {
System.out.println("❌ Invalid user name");
} else if (user.getEmail() == null || !user.getEmail().contains("@")) {
System.out.println("❌ Invalid email address");
} else {
System.out.println("✅ User validation passed");
}
}
public static boolean isValidEmail(String email) {
return email != null && email.matches("^[\\w.%+-]+@[\\w.-]+\\.[A-Za-z]{2,}$");
}
}
// File: src/com/company/app/utils/Formatter.java
package com.company.app.utils;
import com.company.app.models.Product;
public class Formatter {
public void formatProduct(Product product) {
System.out.println("📦 Formatting product: " + product.getName());
System.out.printf("   Name: %s%n", product.getName());
System.out.printf("   Price: $%.2f%n", product.getPrice());
System.out.printf("   Price with tax: $%.2f%n", product.getPrice() * 1.08);
}
public static String formatCurrency(double amount) {
return String.format("$%.2f", amount);
}
}

Output:

=== PACKAGES AND IMPORTS DEMO ===
PI value: 3.141592653589793
2^8 = 256.0
Names: [Alice, Bob]
Scores: {Alice=95, Bob=87}
Current time: 2024-01-15T10:30:00.123
🔍 Validating user: Alice
✅ User validation passed
📦 Formatting product: Laptop
Name: Laptop
Price: $999.99
Price with tax: $1079.99

Example 2: Access Modifiers and Package Visibility

Directory Structure:

src/
├── com/
│   └── company/
│       ├── banking/
│       │   ├── Bank.java
│       │   ├── accounts/
│       │   │   ├── Account.java
│       │   │   ├── SavingsAccount.java
│       │   │   └── CheckingAccount.java
│       │   └── internal/
│       │       ├── AuditService.java
│       │       └── SecurityManager.java
│       └── client/
│           └── ClientApp.java
// File: src/com/company/banking/Bank.java
package com.company.banking;
import com.company.banking.accounts.*;
import com.company.banking.internal.AuditService;
import com.company.banking.internal.SecurityManager;
import java.util.ArrayList;
import java.util.List;
public class Bank {
private String name;
private List<Account> accounts;
private AuditService auditService;
private SecurityManager securityManager;
public Bank(String name) {
this.name = name;
this.accounts = new ArrayList<>();
this.auditService = new AuditService();
this.securityManager = new SecurityManager();
System.out.println("🏦 Bank created: " + name);
}
public void openAccount(Account account) {
accounts.add(account);
auditService.logAccountCreation(account.getAccountNumber());
System.out.println("✅ Account opened: " + account.getAccountNumber());
}
public void displayAllAccounts() {
System.out.println("\n=== ACCOUNTS IN " + name.toUpperCase() + " ===");
for (Account account : accounts) {
account.displayInfo();
}
}
// Package-private method - accessible within same package
void internalTransfer(String from, String to, double amount) {
System.out.println("🔄 Internal transfer: $" + amount + " from " + from + " to " + to);
auditService.logInternalTransfer(from, to, amount);
}
public String getName() { return name; }
}
// File: src/com/company/banking/accounts/Account.java
package com.company.banking.accounts;
// No import needed for classes in same package
// import com.company.banking.accounts.*; // Implicit
public abstract class Account {
protected String accountNumber;
protected double balance;
protected String accountHolder;
// Package-private constructor - only accessible within package
Account(String accountNumber, String accountHolder, double initialBalance) {
this.accountNumber = accountNumber;
this.accountHolder = accountHolder;
this.balance = initialBalance;
}
// Public methods - accessible from anywhere
public abstract void withdraw(double amount);
public abstract void deposit(double amount);
public void displayInfo() {
System.out.printf("Account: %s | Holder: %s | Balance: $%.2f%n", 
accountNumber, accountHolder, balance);
}
// Public getters
public String getAccountNumber() { return accountNumber; }
public double getBalance() { return balance; }
public String getAccountHolder() { return accountHolder; }
// Package-private setter - only within package
void setBalance(double balance) { this.balance = balance; }
}
// File: src/com/company/banking/accounts/SavingsAccount.java
package com.company.banking.accounts;
public class SavingsAccount extends Account {
private double interestRate;
public SavingsAccount(String accountNumber, String accountHolder, 
double initialBalance, double interestRate) {
super(accountNumber, accountHolder, initialBalance);
this.interestRate = interestRate;
}
@Override
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("💰 Withdrawn: $" + amount + " from " + accountNumber);
} else {
System.out.println("❌ Insufficient funds in " + accountNumber);
}
}
@Override
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("💰 Deposited: $" + amount + " to " + accountNumber);
}
}
public void applyInterest() {
double interest = balance * interestRate / 100;
balance += interest;
System.out.printf("📈 Interest applied: $%.2f to %s%n", interest, accountNumber);
}
@Override
public void displayInfo() {
System.out.printf("💵 Savings Account: %s | Holder: %s | Balance: $%.2f | Rate: %.1f%%%n", 
accountNumber, accountHolder, balance, interestRate);
}
}
// File: src/com/company/banking/accounts/CheckingAccount.java
package com.company.banking.accounts;
public class CheckingAccount extends Account {
private double overdraftLimit;
public CheckingAccount(String accountNumber, String accountHolder, 
double initialBalance, double overdraftLimit) {
super(accountNumber, accountHolder, initialBalance);
this.overdraftLimit = overdraftLimit;
}
@Override
public void withdraw(double amount) {
if (amount > 0 && (balance - amount) >= -overdraftLimit) {
balance -= amount;
System.out.println("💰 Withdrawn: $" + amount + " from " + accountNumber);
} else {
System.out.println("❌ Overdraft limit exceeded for " + accountNumber);
}
}
@Override
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("💰 Deposited: $" + amount + " to " + accountNumber);
}
}
@Override
public void displayInfo() {
System.out.printf("🏦 Checking Account: %s | Holder: %s | Balance: $%.2f | Overdraft: $%.2f%n", 
accountNumber, accountHolder, balance, overdraftLimit);
}
}
// File: src/com/company/banking/internal/AuditService.java
package com.company.banking.internal;
// Package-private class - only accessible within com.company.banking package
class AuditService {
void logAccountCreation(String accountNumber) {
System.out.println("📝 AUDIT: Account created - " + accountNumber);
}
void logInternalTransfer(String from, String to, double amount) {
System.out.printf("📝 AUDIT: Transfer $%.2f from %s to %s%n", amount, from, to);
}
void logSecurityEvent(String event) {
System.out.println("🚨 SECURITY AUDIT: " + event);
}
}
// File: src/com/company/banking/internal/SecurityManager.java
package com.company.banking.internal;
class SecurityManager {
void validateTransaction(String accountNumber, double amount) {
System.out.println("🔒 Security check for account: " + accountNumber);
if (amount > 10000) {
System.out.println("⚠️  Large transaction requires additional verification");
}
}
void logAccess(String user, String resource) {
System.out.println("🔐 Access log: " + user + " accessed " + resource);
}
}
// File: src/com/company/client/ClientApp.java
package com.company.client;
// Import public classes from banking package
import com.company.banking.Bank;
import com.company.banking.accounts.SavingsAccount;
import com.company.banking.accounts.CheckingAccount;
// import com.company.banking.internal.AuditService; // ❌ Cannot import - package-private class
// import com.company.banking.internal.SecurityManager; // ❌ Cannot import - package-private class
public class ClientApp {
public static void main(String[] args) {
System.out.println("=== BANKING CLIENT APPLICATION ===");
// Create bank and accounts
Bank bank = new Bank("Java Bank");
SavingsAccount savings = new SavingsAccount("SAV001", "Alice Johnson", 5000.0, 2.5);
CheckingAccount checking = new CheckingAccount("CHK001", "Bob Smith", 3000.0, 1000.0);
// Open accounts
bank.openAccount(savings);
bank.openAccount(checking);
// Perform transactions
System.out.println("\n=== TRANSACTIONS ===");
savings.deposit(1000.0);
savings.withdraw(500.0);
savings.applyInterest();
checking.deposit(2000.0);
checking.withdraw(4500.0); // Within overdraft limit
checking.withdraw(6000.0); // Exceeds overdraft limit
// Display all accounts
bank.displayAllAccounts();
// ❌ Client cannot access package-private members
// bank.internalTransfer("SAV001", "CHK001", 500.0); // Compilation error
// ❌ Client cannot access package-private classes
// AuditService audit = new AuditService(); // Compilation error
// SecurityManager security = new SecurityManager(); // Compilation error
System.out.println("\n✅ Client can only use public interface of the banking system");
}
}

Output:

=== BANKING CLIENT APPLICATION ===
🏦 Bank created: Java Bank
📝 AUDIT: Account created - SAV001
✅ Account opened: SAV001
📝 AUDIT: Account created - CHK001
✅ Account opened: CHK001
=== TRANSACTIONS ===
💰 Deposited: $1000.0 to SAV001
💰 Withdrawn: $500.0 from SAV001
📈 Interest applied: $137.50 to SAV001
💰 Deposited: $2000.0 to CHK001
💰 Withdrawn: $4500.0 from CHK001
❌ Overdraft limit exceeded for CHK001
=== ACCOUNTS IN JAVA BANK ===
💵 Savings Account: SAV001 | Holder: Alice Johnson | Balance: $5637.50 | Rate: 2.5%
🏦 Checking Account: CHK001 | Holder: Bob Smith | Balance: $500.00 | Overdraft: $1000.00
✅ Client can only use public interface of the banking system

Example 3: Real-World Package Organization

Directory Structure:

ecommerce/
├── com/
│   └── company/
│       └── ecommerce/
│           ├── Main.java
│           ├── config/
│           │   ├── AppConfig.java
│           │   └── DatabaseConfig.java
│           ├── models/
│           │   ├── User.java
│           │   ├── Product.java
│           │   ├── Order.java
│           │   └── Cart.java
│           ├── services/
│           │   ├── UserService.java
│           │   ├── ProductService.java
│           │   ├── OrderService.java
│           │   └── PaymentService.java
│           ├── utils/
│           │   ├── Validator.java
│           │   ├── Formatter.java
│           │   └── Logger.java
│           └── exceptions/
│               ├── ValidationException.java
│               ├── PaymentException.java
│               └── OrderException.java
// File: com/company/ecommerce/Main.java
package com.company.ecommerce;
// Import from same project packages
import com.company.ecommerce.config.AppConfig;
import com.company.ecommerce.models.*;
import com.company.ecommerce.services.*;
import com.company.ecommerce.utils.Formatter;
import com.company.ecommerce.utils.Logger;
import com.company.ecommerce.exceptions.ValidationException;
// Import Java standard library packages
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
System.out.println("=== E-COMMERCE SYSTEM ===");
// Initialize services
UserService userService = new UserService();
ProductService productService = new ProductService();
OrderService orderService = new OrderService();
PaymentService paymentService = new PaymentService();
Logger.log("System initialized");
try {
// Create users
User alice = userService.registerUser("Alice", "[email protected]", "secure123");
User bob = userService.registerUser("Bob", "[email protected]", "password456");
// Add products
Product laptop = productService.addProduct("Laptop", 999.99, 10);
Product phone = productService.addProduct("Smartphone", 499.99, 25);
Product headphones = productService.addProduct("Headphones", 149.99, 50);
// User operations
Cart aliceCart = new Cart(alice);
aliceCart.addProduct(laptop, 1);
aliceCart.addProduct(headphones, 2);
System.out.println("\n" + alice.getName() + "'s Cart:");
aliceCart.displayCart();
// Place order
Order order = orderService.createOrder(aliceCart);
paymentService.processPayment(order, "credit_card");
// Display order summary
System.out.println("\n=== ORDER SUMMARY ===");
Formatter.formatOrder(order);
} catch (ValidationException e) {
System.err.println("Validation error: " + e.getMessage());
} catch (Exception e) {
System.err.println("Unexpected error: " + e.getMessage());
}
Logger.log("System shutdown");
}
}
// File: com/company/ecommerce/models/User.java
package com.company.ecommerce.models;
import com.company.ecommerce.utils.Validator;
public class User {
private static int nextId = 1;
private final int id;
private String name;
private String email;
private String passwordHash;
public User(String name, String email, String passwordHash) {
this.id = nextId++;
this.name = name;
this.email = email;
this.passwordHash = passwordHash;
}
// Getters
public int getId() { return id; }
public String getName() { return name; }
public String getEmail() { return email; }
// Setters with validation
public void setName(String name) {
if (Validator.isValidName(name)) {
this.name = name;
}
}
public void setEmail(String email) {
if (Validator.isValidEmail(email)) {
this.email = email;
}
}
@Override
public String toString() {
return String.format("User{id=%d, name='%s', email='%s'}", id, name, email);
}
}
// File: com/company/ecommerce/models/Product.java
package com.company.ecommerce.models;
public class Product {
private static int nextId = 1;
private final int id;
private String name;
private double price;
private int stockQuantity;
public Product(String name, double price, int stockQuantity) {
this.id = nextId++;
this.name = name;
this.price = price;
this.stockQuantity = stockQuantity;
}
// Getters
public int getId() { return id; }
public String getName() { return name; }
public double getPrice() { return price; }
public int getStockQuantity() { return stockQuantity; }
// Business methods
public void reduceStock(int quantity) {
if (quantity <= stockQuantity) {
stockQuantity -= quantity;
}
}
public void increaseStock(int quantity) {
stockQuantity += quantity;
}
@Override
public String toString() {
return String.format("Product{id=%d, name='%s', price=%.2f, stock=%d}", 
id, name, price, stockQuantity);
}
}
// File: com/company/ecommerce/models/Order.java
package com.company.ecommerce.models;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
public class Order {
private static int nextId = 1;
private final int id;
private final User user;
private final Map<Product, Integer> items;
private final double totalAmount;
private final LocalDateTime orderDate;
private String status;
public Order(User user, Map<Product, Integer> items) {
this.id = nextId++;
this.user = user;
this.items = new HashMap<>(items);
this.totalAmount = calculateTotalAmount();
this.orderDate = LocalDateTime.now();
this.status = "PENDING";
}
private double calculateTotalAmount() {
return items.entrySet().stream()
.mapToDouble(entry -> entry.getKey().getPrice() * entry.getValue())
.sum();
}
// Getters
public int getId() { return id; }
public User getUser() { return user; }
public Map<Product, Integer> getItems() { return new HashMap<>(items); }
public double getTotalAmount() { return totalAmount; }
public LocalDateTime getOrderDate() { return orderDate; }
public String getStatus() { return status; }
public void setStatus(String status) {
this.status = status;
}
@Override
public String toString() {
return String.format("Order{id=%d, user=%s, total=%.2f, status='%s'}", 
id, user.getName(), totalAmount, status);
}
}
// File: com/company/ecommerce/models/Cart.java
package com.company.ecommerce.models;
import java.util.HashMap;
import java.util.Map;
public class Cart {
private final User user;
private final Map<Product, Integer> items;
public Cart(User user) {
this.user = user;
this.items = new HashMap<>();
}
public void addProduct(Product product, int quantity) {
items.put(product, items.getOrDefault(product, 0) + quantity);
System.out.printf("➕ Added %d x %s to cart%n", quantity, product.getName());
}
public void removeProduct(Product product, int quantity) {
int currentQuantity = items.getOrDefault(product, 0);
if (currentQuantity <= quantity) {
items.remove(product);
} else {
items.put(product, currentQuantity - quantity);
}
System.out.printf("➖ Removed %d x %s from cart%n", quantity, product.getName());
}
public void clear() {
items.clear();
System.out.println("🗑️ Cart cleared");
}
public double getTotal() {
return items.entrySet().stream()
.mapToDouble(entry -> entry.getKey().getPrice() * entry.getValue())
.sum();
}
public void displayCart() {
if (items.isEmpty()) {
System.out.println("🛒 Cart is empty");
return;
}
System.out.println("🛒 Shopping Cart for " + user.getName() + ":");
items.forEach((product, quantity) -> {
double itemTotal = product.getPrice() * quantity;
System.out.printf("   %d x %s = $%.2f%n", quantity, product.getName(), itemTotal);
});
System.out.printf("   Total: $%.2f%n", getTotal());
}
public Map<Product, Integer> getItems() {
return new HashMap<>(items);
}
public User getUser() {
return user;
}
}
// File: com/company/ecommerce/services/UserService.java
package com.company.ecommerce.services;
import com.company.ecommerce.models.User;
import com.company.ecommerce.utils.Validator;
import com.company.ecommerce.exceptions.ValidationException;
public class UserService {
public User registerUser(String name, String email, String password) 
throws ValidationException {
// Validate input
if (!Validator.isValidName(name)) {
throw new ValidationException("Invalid name: " + name);
}
if (!Validator.isValidEmail(email)) {
throw new ValidationException("Invalid email: " + email);
}
if (!Validator.isValidPassword(password)) {
throw new ValidationException("Invalid password");
}
// Create user (in real app, hash the password)
String passwordHash = "hashed_" + password; // Simplified
User user = new User(name, email, passwordHash);
System.out.println("✅ User registered: " + user);
return user;
}
public boolean login(String email, String password) {
System.out.println("🔐 Login attempt for: " + email);
// Simplified login logic
return email != null && password != null;
}
}
// File: com/company/ecommerce/services/ProductService.java
package com.company.ecommerce.services;
import com.company.ecommerce.models.Product;
import com.company.ecommerce.utils.Validator;
import com.company.ecommerce.exceptions.ValidationException;
public class ProductService {
public Product addProduct(String name, double price, int stockQuantity) 
throws ValidationException {
if (!Validator.isValidProductName(name)) {
throw new ValidationException("Invalid product name: " + name);
}
if (price <= 0) {
throw new ValidationException("Price must be positive: " + price);
}
if (stockQuantity < 0) {
throw new ValidationException("Stock quantity cannot be negative: " + stockQuantity);
}
Product product = new Product(name, price, stockQuantity);
System.out.println("✅ Product added: " + product);
return product;
}
public void updateStock(Product product, int newQuantity) {
if (newQuantity >= 0) {
// In real app, we'd have a method to update stock
System.out.printf("📦 Stock updated: %s -> %d units%n", 
product.getName(), newQuantity);
}
}
}
// File: com/company/ecommerce/services/OrderService.java
package com.company.ecommerce.services;
import com.company.ecommerce.models.*;
import com.company.ecommerce.exceptions.OrderException;
public class OrderService {
public Order createOrder(Cart cart) throws OrderException {
if (cart.getItems().isEmpty()) {
throw new OrderException("Cannot create order from empty cart");
}
// Check stock availability
for (var entry : cart.getItems().entrySet()) {
Product product = entry.getKey();
int quantity = entry.getValue();
if (product.getStockQuantity() < quantity) {
throw new OrderException("Insufficient stock for: " + product.getName());
}
}
// Create order
Order order = new Order(cart.getUser(), cart.getItems());
// Update stock
for (var entry : cart.getItems().entrySet()) {
Product product = entry.getKey();
int quantity = entry.getValue();
product.reduceStock(quantity);
}
System.out.println("✅ Order created: " + order);
return order;
}
}
// File: com/company/ecommerce/services/PaymentService.java
package com.company.ecommerce.services;
import com.company.ecommerce.models.Order;
import com.company.ecommerce.exceptions.PaymentException;
public class PaymentService {
public void processPayment(Order order, String paymentMethod) throws PaymentException {
if (order.getTotalAmount() <= 0) {
throw new PaymentException("Invalid order amount: " + order.getTotalAmount());
}
System.out.printf("💳 Processing %s payment of $%.2f for order #%d%n", 
paymentMethod, order.getTotalAmount(), order.getId());
// Simulate payment processing
boolean paymentSuccess = Math.random() > 0.1; // 90% success rate
if (paymentSuccess) {
order.setStatus("PAID");
System.out.println("✅ Payment successful for order #" + order.getId());
} else {
order.setStatus("PAYMENT_FAILED");
throw new PaymentException("Payment failed for order #" + order.getId());
}
}
}
// File: com/company/ecommerce/utils/Validator.java
package com.company.ecommerce.utils;
public class Validator {
public static boolean isValidEmail(String email) {
return email != null && email.matches("^[\\w.%+-]+@[\\w.-]+\\.[A-Za-z]{2,}$");
}
public static boolean isValidName(String name) {
return name != null && name.length() >= 2 && name.length() <= 50;
}
public static boolean isValidPassword(String password) {
return password != null && password.length() >= 6;
}
public static boolean isValidProductName(String name) {
return name != null && !name.trim().isEmpty() && name.length() <= 100;
}
public static boolean isValidPrice(double price) {
return price >= 0;
}
}
// File: com/company/ecommerce/utils/Formatter.java
package com.company.ecommerce.utils;
import com.company.ecommerce.models.Order;
import com.company.ecommerce.models.Product;
import java.util.Map;
public class Formatter {
public static void formatOrder(Order order) {
System.out.println("📋 Order #" + order.getId());
System.out.println("   Customer: " + order.getUser().getName());
System.out.println("   Date: " + order.getOrderDate());
System.out.println("   Status: " + order.getStatus());
System.out.println("   Items:");
for (Map.Entry<Product, Integer> entry : order.getItems().entrySet()) {
Product product = entry.getKey();
int quantity = entry.getValue();
double itemTotal = product.getPrice() * quantity;
System.out.printf("     %d x %s = $%.2f%n", quantity, product.getName(), itemTotal);
}
System.out.printf("   Total Amount: $%.2f%n", order.getTotalAmount());
}
public static String formatCurrency(double amount) {
return String.format("$%.2f", amount);
}
}
// File: com/company/ecommerce/utils/Logger.java
package com.company.ecommerce.utils;
public class Logger {
public static void log(String message) {
System.out.println("[LOG] " + java.time.LocalDateTime.now() + " - " + message);
}
public static void error(String message) {
System.err.println("[ERROR] " + java.time.LocalDateTime.now() + " - " + message);
}
public static void warn(String message) {
System.out.println("[WARN] " + java.time.LocalDateTime.now() + " - " + message);
}
}
// File: com/company/ecommerce/exceptions/ValidationException.java
package com.company.ecommerce.exceptions;
public class ValidationException extends Exception {
public ValidationException(String message) {
super(message);
}
public ValidationException(String message, Throwable cause) {
super(message, cause);
}
}
// File: com/company/ecommerce/exceptions/PaymentException.java
package com.company.ecommerce.exceptions;
public class PaymentException extends Exception {
public PaymentException(String message) {
super(message);
}
public PaymentException(String message, Throwable cause) {
super(message, cause);
}
}
// File: com/company/ecommerce/exceptions/OrderException.java
package com.company.ecommerce.exceptions;
public class OrderException extends Exception {
public OrderException(String message) {
super(message);
}
public OrderException(String message, Throwable cause) {
super(message, cause);
}
}

Output:

=== E-COMMERCE SYSTEM ===
[LOG] 2024-01-15T10:30:00.123 - System initialized
✅ User registered: User{id=1, name='Alice', email='[email protected]'}
✅ User registered: User{id=2, name='Bob', email='[email protected]'}
✅ Product added: Product{id=1, name='Laptop', price=999.99, stock=10}
✅ Product added: Product{id=2, name='Smartphone', price=499.99, stock=25}
✅ Product added: Product{id=3, name='Headphones', price=149.99, stock=50}
➕ Added 1 x Laptop to cart
➕ Added 2 x Headphones to cart
Alice's Cart:
🛒 Shopping Cart for Alice:
1 x Laptop = $999.99
2 x Headphones = $299.98
Total: $1299.97
✅ Order created: Order{id=1, user=Alice, total=1299.97, status='PENDING'}
💳 Processing credit_card payment of $1299.97 for order #1
✅ Payment successful for order #1
=== ORDER SUMMARY ===
📋 Order #1
Customer: Alice
Date: 2024-01-15T10:30:00.124
Status: PAID
Items:
1 x Laptop = $999.99
2 x Headphones = $299.98
Total Amount: $1299.97
[LOG] 2024-01-15T10:30:00.125 - System shutdown

Example 4: Common Pitfalls and Best Practices

```java
// File: com/company/demo/PackagePit

Leave a Reply

Your email address will not be published. Required fields are marked *


Macro Nepal Helper