Java Data Types - Real Life Example
Practical Application of Data Types
Understanding how different data types work together in real-world applications is crucial for effective Java programming. This example demonstrates a user registration system that utilizes various Java data types.
It handles user registration, validation, and data storage, showing how primitive and non-primitive data types interact in practice.
User Registration System
A complete user registration system using appropriate data types:
Example
import java.time.LocalDate;
import java.util.Scanner;
public class UserRegistrationSystem {
private static int totalRegistrations = 0; // Registration counter
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// User information
String username;
String email;
String password;
byte age;
short yearOfBirth;
int userId;
long phoneNumber;
float height; // meters
double weight; // kilograms
char gender;
boolean isActive;
LocalDate registrationDate;
System.out.println("=== USER REGISTRATION SYSTEM ===");
// Get user input
System.out.print("Enter username: ");
username = scanner.nextLine();
System.out.print("Enter email: ");
email = scanner.nextLine();
System.out.print("Enter password: ");
password = scanner.nextLine();
System.out.print("Enter age: ");
age = scanner.nextByte();
System.out.print("Enter year of birth: ");
yearOfBirth = scanner.nextShort();
System.out.print("Enter phone number: ");
phoneNumber = scanner.nextLong();
System.out.print("Enter height (m): ");
height = scanner.nextFloat();
System.out.print("Enter weight (kg): ");
weight = scanner.nextDouble();
System.out.print("Enter gender (M/F): ");
gender = scanner.next().charAt(0);
System.out.print("Activate account? (true/false): ");
isActive = scanner.nextBoolean();
scanner.nextLine(); // Consume newline
// Generate user ID and registration date
userId = ++totalRegistrations;
registrationDate = LocalDate.now();
// Validate input
boolean isValid = validateUserInput(username, email, password, age,
yearOfBirth, phoneNumber, height,
weight, gender);
if (isValid) {
double bmi = calculateBMI(weight, height);
String bmiCategory = getBMICategory(bmi);
displayUserSummary(username, email, age, yearOfBirth, phoneNumber,
height, weight, gender, isActive, registrationDate,
userId, bmi, bmiCategory);
System.out.println("\nRegistration successful!");
} else {
System.out.println("Registration failed. Please check your input.");
}
scanner.close();
}
private static boolean validateUserInput(String username, String email, String password,
byte age, short yearOfBirth, long phoneNumber,
float height, double weight, char gender) {
if (username == null || username.trim().isEmpty()) return false;
if (!email.contains("@") || !email.contains(".")) return false;
if (password.length() < 8) return false;
if (age < 13 || age > 120) return false;
if (yearOfBirth < 1900 || yearOfBirth > LocalDate.now().getYear()) return false;
if (String.valueOf(phoneNumber).length() < 10) return false;
if (height < 0.5 || height > 2.5) return false;
if (weight < 2.0 || weight > 500.0) return false;
if (gender != 'M' && gender != 'F' && gender != 'm' && gender != 'f') return false;
return true;
}
private static double calculateBMI(double weight, float height) {
return weight / (height * height);
}
private static String getBMICategory(double bmi) {
if (bmi < 18.5) return "Underweight";
else if (bmi < 25) return "Normal weight";
else if (bmi < 30) return "Overweight";
else return "Obese";
}
private static void displayUserSummary(String username, String email, byte age,
short yearOfBirth, long phoneNumber,
float height, double weight, char gender,
boolean isActive, LocalDate registrationDate,
int userId, double bmi, String bmiCategory) {
System.out.println("\n=== REGISTRATION SUMMARY ===");
System.out.println("User ID: " + userId);
System.out.println("Username: " + username);
System.out.println("Email: " + email);
System.out.println("Age: " + age);
System.out.println("Year of Birth: " + yearOfBirth);
System.out.println("Phone: " + phoneNumber);
System.out.printf("Height: %.2fm\n", height);
System.out.printf("Weight: %.1fkg\n", weight);
System.out.println("Gender: " + (Character.toUpperCase(gender) == 'M' ? "Male" : "Female"));
System.out.println("Account Active: " + isActive);
System.out.println("Registration Date: " + registrationDate);
System.out.printf("BMI: %.1f (%s)\n", bmi, bmiCategory);
}
}
Output
=== USER REGISTRATION SYSTEM === Enter username: john_doe Enter email: john@example.com Enter password: securepass123 Enter age: 25 Enter year of birth: 1998 Enter phone number: 1234567890 Enter height (m): 1.75 Enter weight (kg): 68.5 Enter gender (M/F): M Activate account? (true/false): true === REGISTRATION SUMMARY === User ID: 1 Username: john_doe Email: john@example.com Age: 25 Year of Birth: 1998 Phone: 1234567890 Height: 1.75m Weight: 68.5kg Gender: Male Account Active: true Registration Date: 2024-01-15 BMI: 22.4 (Normal weight) Registration successful!
Data Type Selection Rationale
Each variable uses the most suitable data type for efficiency and accuracy:
Variable | Data Type | Rationale |
---|---|---|
username | String | Text data of variable length |
String | Text with symbols like @ and . | |
password | String | Text, typically encrypted in real systems |
age | byte | Small range (0–127), saves memory |
yearOfBirth | short | Sufficient for years between 1900–2100 |
userId | int | Handles large numbers of users |
phoneNumber | long | Stores 10+ digit numbers |
height | float | Decimal values with moderate precision |
weight | double | Decimal values with higher precision |
gender | char | Single character (M/F) |
isActive | boolean | Represents a true/false state |
registrationDate | LocalDate | Specialized type for dates |
Error Handling and Edge Cases
The system validates input and handles incorrect or edge case values gracefully.
Example
import java.time.LocalDate;
public class ErrorHandlingExample {
public static void main(String[] args) {
// Invalid input example
testValidation("", "invalid", "short", (byte)200, (short)1800,
123456789L, 0.3f, 1.0, 'X');
// Valid input example
testValidation("validuser", "valid@email.com", "longpassword",
(byte)25, (short)1998, 1234567890L, 1.75f, 68.5, 'M');
}
private static void testValidation(String username, String email, String password,
byte age, short yearOfBirth, long phoneNumber,
float height, double weight, char gender) {
System.out.println("\nTesting validation for: " + username);
boolean isValid = validateUserInput(username, email, password, age,
yearOfBirth, phoneNumber, height,
weight, gender);
System.out.println("Validation result: " + (isValid ? "PASS" : "FAIL"));
}
private static boolean validateUserInput(String username, String email, String password,
byte age, short yearOfBirth, long phoneNumber,
float height, double weight, char gender) {
if (username == null || username.trim().isEmpty()) return false;
if (!email.contains("@") || !email.contains(".")) return false;
if (password.length() < 8) return false;
if (age < 13 || age > 120) return false;
if (yearOfBirth < 1900 || yearOfBirth > LocalDate.now().getYear()) return false;
if (String.valueOf(phoneNumber).length() < 10) return false;
if (height < 0.5 || height > 2.5) return false;
if (weight < 2.0 || weight > 500.0) return false;
if (gender != 'M' && gender != 'F' && gender != 'm' && gender != 'f') return false;
return true;
}
}
Output
Testing validation for: Validation result: FAIL Testing validation for: validuser Validation result: PASS