Creating a Practical Application
Now that we've explored various techniques for handling null values in string concatenation, let's apply what we've learned to build a small practical application. This will help solidify our understanding and show how to use these techniques in a real-world scenario.
In this step, we'll create a program that formats user profile information, handling potential null values in various fields.
-
Create a new Java file named UserProfileFormatter.java
in the /home/labex/project
directory.
-
Add the following code to the file:
import java.util.StringJoiner;
import java.util.Objects;
public class UserProfileFormatter {
public static void main(String[] args) {
// Complete user with all fields
formatUserProfile("John", "Doe", "john.doe@example.com", "Software Developer", "New York");
// User with some null fields
formatUserProfile("Alice", "Smith", null, "Data Scientist", null);
// User with only name
formatUserProfile("Bob", "Johnson", null, null, null);
// User with minimal information
formatUserProfile(null, "Williams", "robert@example.com", null, null);
// Let's use our utility method
User user1 = new User("Sarah", "Connor", "sarah@skynet.com", "Freedom Fighter", "Los Angeles");
System.out.println("\nFormatted user1 profile:");
System.out.println(formatUserInfo(user1));
User user2 = new User("James", null, null, "Student", "Boston");
System.out.println("\nFormatted user2 profile:");
System.out.println(formatUserInfo(user2));
}
public static void formatUserProfile(String firstName, String lastName,
String email, String occupation, String city) {
System.out.println("\n------ User Profile ------");
// Format full name using StringJoiner
StringJoiner nameJoiner = new StringJoiner(" ");
if (firstName != null) nameJoiner.add(firstName);
if (lastName != null) nameJoiner.add(lastName);
String fullName = nameJoiner.toString();
System.out.println("Name: " + (fullName.isEmpty() ? "Not provided" : fullName));
// Email with null check using ternary operator
System.out.println("Email: " + (email != null ? email : "Not provided"));
// Occupation with Objects.toString()
System.out.println("Occupation: " + Objects.toString(occupation, "Not provided"));
// City with null check using if-else
String cityInfo;
if (city != null) {
cityInfo = city;
} else {
cityInfo = "Not provided";
}
System.out.println("City: " + cityInfo);
System.out.println("---------------------------");
}
// A more comprehensive utility method to format user information
public static String formatUserInfo(User user) {
if (user == null) {
return "No user information available";
}
StringBuilder builder = new StringBuilder();
builder.append("------ User Profile ------\n");
// Handle name
StringJoiner nameJoiner = new StringJoiner(" ");
if (user.getFirstName() != null) nameJoiner.add(user.getFirstName());
if (user.getLastName() != null) nameJoiner.add(user.getLastName());
String fullName = nameJoiner.toString();
builder.append("Name: ").append(fullName.isEmpty() ? "Not provided" : fullName).append("\n");
// Handle email
builder.append("Email: ").append(user.getEmail() != null ? user.getEmail() : "Not provided").append("\n");
// Handle occupation
builder.append("Occupation: ").append(Objects.toString(user.getOccupation(), "Not provided")).append("\n");
// Handle city
builder.append("City: ").append(Objects.toString(user.getCity(), "Not provided")).append("\n");
builder.append("---------------------------");
return builder.toString();
}
// User class to represent a user
static class User {
private final String firstName;
private final String lastName;
private final String email;
private final String occupation;
private final String city;
public User(String firstName, String lastName, String email, String occupation, String city) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.occupation = occupation;
this.city = city;
}
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
public String getEmail() { return email; }
public String getOccupation() { return occupation; }
public String getCity() { return city; }
}
}
-
Save the file by pressing Ctrl+S or by selecting File > Save from the menu.
-
Compile and run the Java program:
cd ~/project
javac UserProfileFormatter.java
java UserProfileFormatter
You should see output similar to the following:
------ User Profile ------
Name: John Doe
Email: john.doe@example.com
Occupation: Software Developer
City: New York
---------------------------
------ User Profile ------
Name: Alice Smith
Email: Not provided
Occupation: Data Scientist
City: Not provided
---------------------------
------ User Profile ------
Name: Bob Johnson
Email: Not provided
Occupation: Not provided
City: Not provided
---------------------------
------ User Profile ------
Name: Williams
Email: robert@example.com
Occupation: Not provided
City: Not provided
---------------------------
Formatted user1 profile:
------ User Profile ------
Name: Sarah Connor
Email: sarah@skynet.com
Occupation: Freedom Fighter
City: Los Angeles
---------------------------
Formatted user2 profile:
------ User Profile ------
Name: James
Email: Not provided
Occupation: Student
City: Boston
---------------------------
In this example, we've created a real-world application that formats user profile information, which often contains null or missing values. Let's break down what's happening:
-
We used different null-handling techniques in the formatUserProfile
method:
- StringJoiner for combining name parts
- Ternary operator for email
- Objects.toString() for occupation
- If-else statement for city
-
We created a more comprehensive formatUserInfo
method that takes a User object and handles potential nulls in all fields.
-
The User class demonstrates a common scenario where data might be missing for some fields.
This practical example shows how the techniques we've learned can be applied to real-world scenarios. The code is robust and handles null values gracefully, providing default text ("Not provided") when information is missing.