Search⌘ K
AI Features

Solution: The Product SKU Generator

Explore how to build a product SKU generator by manipulating strings in Java. Understand using substring for dynamic prefixes and suffixes, and employ StringBuilder to efficiently construct the SKU without unnecessary string objects.

We'll cover the following...
Java 25
public class SKUGenerator {
public static String generateSKU(String productName, int id) {
// Extract prefix (first 3 chars)
String prefix = productName.substring(0, 3).toUpperCase();
// Extract suffix (last 2 chars)
String suffix = productName.substring(productName.length() - 2).toUpperCase();
// Build string efficiently
StringBuilder sb = new StringBuilder();
sb.append(prefix);
sb.append("-");
sb.append(id);
sb.append("-");
sb.append(suffix);
return sb.toString();
}
public static void main(String[] args) {
String item = "Gaming Laptop";
int id = 5510;
String result = generateSKU(item, id);
System.out.println("Input: " + item);
System.out.println("Generated SKU: " + result);
// Expected: GAM-5510-OP
}
}
...