How to Pad a String in Java

Padding strings with spaces or a specific character is a common text output requirement. This is required when you want to generate a fixed format output even when the size of the data displayed  are different. However there are no built-in Java functions for String padding. Using a third party library just for string padding is overkill!

The following Java program contains custom functions for right padding and left padding a string with a specific character. Run the program to see padding in action!

Code Example: How to Pad a String in Java

// Demo: How to right pad or left pad Strings in Java
public class PaddingDemo {

    public static void main(String[] args) {
        String input1 = "Hello World!";
        String input2 = "Hi There!";

        String output1 = padRight(input1,20,'*');
        String output2 = padRight(input2,20,'*');
        
        System.out.println(output1);
        System.out.println(output2);

        output1 = padLeft(input1,20,'*');
        output2 = padLeft(input2,20,'*');
        
        System.out.println(output1);
        System.out.println(output2);
    }
    
    // Right pad a string with the specified character
    public static String padRight(String s, int size,char pad) {
        StringBuilder builder = new StringBuilder(s);
        while(builder.length()<size) {
            builder.append(pad);
        }
        return builder.toString();
    }
    
    // Left pad a string with the specified character
    public static String padLeft(String s, int size,char pad) {
        StringBuilder builder = new StringBuilder(s);
        builder = builder.reverse(); // reverse initial string
        while(builder.length()<size) {
            builder.append(pad); // append at end
        }
        return builder.reverse().toString(); // reverse again!
    }
}

The output generated is,

Hello World!********
Hi There!***********
********Hello World!
***********Hi There!

How to Load Properties File in Java

Properties file is text file commonly used to store configuration data in Java programs. Each line in the properties file represents a property with name and value separated by an equal sign. Usually properties files are saved with the extension .properties.  We will creating and loading the sample properties file given below. It contains sample configuration for an email server,

#email server configuration
#Mon Feb 27 16:08:12 IST 2017
port=465
password=testpassword
host=smtp.mail.yahoo.com
username=testuser

The above properties file is created using the following Java program. The first comment in the file is inserted by our Java program. The second comment is a timestamp and it indicates when the file was created. This timestamp comment is automatically added by the Properties class. It cannot be suppressed.

Following are the main functions in the sample program,

  • createEmailProperties - This creates a new properties file named email.properties in the folder where PropertiesDemo class is located.
  • loadEmailProperties - Reads the email.properties and loads the properties into a HashMap.
  • printPropertiesInConsole - Prints the key value pairs loaded from the email.properties in the console.

Java Example: Reading and Writing Properties File

import java.io.FileReader;
import java.io.FileWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

// Java program to read and write properties file
public class PropertiesDemo {
    public static void main(String[] args) throws Exception{
        createEmailProperties();
        Map<String,String> props = loadEmailProperties();
        printPropertiesInConsole(props);
    }

    // Write a new properties file in Java
    private static void createEmailProperties() throws Exception {
        Properties p = new Properties();
        p.setProperty("host", "smtp.mail.yahoo.com");
        p.setProperty("port", "465");
        p.setProperty("username","testuser");
        p.setProperty("password", "testpassword");
        
        FileWriter writer = new FileWriter("email.properties");
        p.store(writer, "email server configuration");
        writer.close();
    }
    
    // Read a properties file in Java
    private static Map<String,String> loadEmailProperties() throws Exception {
        Map<String,String> propertyMap = new HashMap();
        
        FileReader reader = new FileReader("email.properties");
        Properties p = new Properties();
        p.load(reader);
                
        Enumeration keys = p.propertyNames();
        while(keys.hasMoreElements()) {
            String key = (String)keys.nextElement();
            propertyMap.put(key,p.getProperty(key));
        }
        
        reader.close();
        return propertyMap;
    }
    
    // Print all properties to the console
    private static void printPropertiesInConsole(Map<String,String> props) {
        for(String key:props.keySet()) {
            System.out.println(key+":"+props.get(key));
        }
    }
}

 

How to Read Properties File from Classpath

If you want to read properties file from the classpath, use the following function. This requirement is common in web applications.

private static Map loadFromClasspath() throws Exception {
    Map<String, String> propertyMap = new HashMap();
    InputStream stream = PropertiesDemo.class.getResourceAsStream("email.properties");
    Properties p = new Properties();
    p.load(stream);

    Enumeration keys = p.propertyNames();
    while (keys.hasMoreElements()) {
        String key = (String) keys.nextElement();
        propertyMap.put(key, p.getProperty(key));
    }

    stream.close();
    return propertyMap;
}

How to Convert Miles to Kilometers in Java

Miles and Kilometers are different units used for distance measurement. Miles is part of the imperial system and Kilometers is part of the metric system. The following formula can be used to convert miles into kilometers,

Distance in km = 1.60934 * distance in miles.

The following formula can be used to convert kilometers to miles,

Distance in miles = 0.621371 * distance in km

The following Java example program contains methods for converting miles to kilometers and vice versa.

import java.util.Scanner;

// Java example - converts miles to km and km to miles
public class DistanceConverter {
    public static void main(String[] args) {
        System.out.print("Enter distance in miles:");
        Scanner s = new Scanner(System.in);

        double distanceInMiles = s.nextDouble();

        System.out.println(distanceInMiles + " miles = " + milesTokm(distanceInMiles) + " km");

        System.out.print("Enter distance in km:");
        double distanceInKm = s.nextDouble();

        System.out.println(distanceInKm + " km = " + kmTomiles(distanceInKm) + " miles");
        s.close();

    }

    private static double milesTokm(double distanceInMiles) {
        return distanceInMiles * 1.60934;
    }

    private static double kmTomiles(double distanceInKm) {
        return distanceInKm * 0.621371;
    }
}

How to Calculate Age from Date of Birth in Java

The following Java program example calculates age of a person from his date of birth. This implementation is portable across Java versions. This implementation shows why date API in Java is bad before Java 8.

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Scanner;

// Calculate age from date of birth in Java
// Works in all Java versions
public class CalculateAge {

    public static void main(String[] args) throws Exception {
        System.out.print("Please enter date of birth in YYYY-MM-DD: ");
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        scanner.close();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar dob = Calendar.getInstance();
        dob.setTime(sdf.parse(input));
        System.out.println("Age is:" + getAge(dob));
    }

    // Returns age given the date of birth
    public static int getAge(Calendar dob) throws Exception {
        Calendar today = Calendar.getInstance();

        int curYear = today.get(Calendar.YEAR);
        int dobYear = dob.get(Calendar.YEAR);

        int age = curYear - dobYear;

        // if dob is month or day is behind today's month or day
        // reduce age by 1
        int curMonth = today.get(Calendar.MONTH);
        int dobMonth = dob.get(Calendar.MONTH);
        if (dobMonth > curMonth) { // this year can't be counted!
            age--;
        } else if (dobMonth == curMonth) { // same month? check for day
            int curDay = today.get(Calendar.DAY_OF_MONTH);
            int dobDay = dob.get(Calendar.DAY_OF_MONTH);
            if (dobDay > curDay) { // this year can't be counted!
                age--;
            }
        }

        return age;
    }
}

In Java 8, A much more elegant implementation to calculate age can be written using classes in the new java.time package. Following example also demonstrates the use of LocalDate and Period classes in Java 8.

import java.time.LocalDate;
import java.time.Period;
import java.util.Scanner;

// Java example program to calculate age from date of birth
// Works only in Java 8 and above
public class CalculateAgeJava8 {

    public static void main(String[] args) {
        System.out.print("Please enter date of birth in YYYY-MM-DD: ");
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        scanner.close();

        LocalDate dob = LocalDate.parse(input);
        System.out.println("Age is:" + getAge(dob));
    }

    // Returns age given the date of birth
    public static int getAge(LocalDate dob) {
        LocalDate curDate = LocalDate.now();
        return Period.between(dob, curDate).getYears();
    }

}

The above implementation uses the default time zone for calculating current date. You may want to specify a time zone for precise age(!) calculation. LocalDate.now() is overloaded to specify time zone.

Another option is to use Joda Time library. However in Java 8 and beyond java.time implementation is the best solution. If you are migrating a Java project using Joda time to Java 8, it is now recommended to switch to java.time package.

How to Send Email in Java Using Apache Commons

Apache commons has an email library built on top of Java Mail API. This simplifies the process of sending emails from Java programs. Apache commons email API has classes for sending HTML emails, emails with attachments or even emails with embedded images. For this article, Apache commons email version 1.4 and Java Mail version 1.5.6 is used.

In order to run these examples you need to have Java Mail API library and Apache commons email library.

The following examples use the SMTP email server provided by Google for Gmail. However you can use any other SMTP email server. Don't forget to change the username and password in the following examples. When using Gmail, you may get the following error,

org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:465

To solve the above issue you need to turn on Access for less secure apps from this Google link. This requirement is specific to Gmail accounts.

Following are the configuration attributes for various email providers that you can use in the Java program using Apache commons email library. All the accounts below use the SMTP port of 465 and are SSL enabled.

Email Provider Host name Comments
Gmail smtp.gmail.com Enable less secure access as mentioned above.
Yahoo Mail smtp.mail.yahoo.com From account security tab of your yahoo account, enable allow apps that use less secure sign in.
Sendgrid smtp.sendgrid.net Create an API key in Sendgrid. Use "apikey" as user name the actual API key as the password.
Mailgun smtp.mailgun.org Default SMTP user name and password are available from the default domain page in Mailgun panel. If you are using free account, you can only send to authorized recipients.

 

Sending Simple Text Email in Java Using Apache Commons

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.SimpleEmail;

// Java program to send simple email using apache commons email
// Uses the Gmail SMTP servers
public class SimpleEmailSender {
    private static final String HOST = "smtp.gmail.com";
    private static final int PORT = 465;
    private static final boolean SSL_FLAG = true; 

    public static void main(String[] args) {
        SimpleEmailSender sender = new SimpleEmailSender();
        sender.sendSimpleEmail();
    }

    private void sendSimpleEmail() {
        
        String userName = "username@gmail.com";
        String password = "password";
        
        String fromAddress="username@gmail.com";
        String toAddress =  "quickprogrammer@gmail.com";
        String subject = "Test Mail";
        String message = "Hello from Apache Mail";
        
        try {
            Email email = new SimpleEmail();
            email.setHostName(HOST);
            email.setSmtpPort(PORT);
            email.setAuthenticator(new DefaultAuthenticator(userName, password));
            email.setSSLOnConnect(SSL_FLAG);
            email.setFrom(fromAddress);
            email.setSubject(subject);
            email.setMsg(message);
            email.addTo(toAddress);
            email.send();
        }catch(Exception ex){
            System.out.println("Unable to send email");
            System.out.println(ex);
        }
    }
}

To compile and run the above programs, ensure that the Apache commons email library jar commons-email-1.4.jar and Java Mail library jar javax.mail.jar is in the same folder where Java source files are stored. Then use the following commands,

To compile in linux/mac,

javac -cp "javax.mail.jar:commons-email-1.4.jar:." SimpleEmailSender.java

To compile in Windows,

javac -cp "javax.mail.jar;commons-email-1.4.jar;." SimpleEmailSender.java

To run in linux/mac,

java -cp "javax.mail.jar:commons-email-1.4.jar:." SimpleEmailSender

To run in Windows,

java -cp "javax.mail.jar;commons-email-1.4.jar;." SimpleEmailSender

If you are using Gradle build system, you can use the following build.gradle for running Java programs using Apache commons email library,

apply plugin: 'java'

repositories {
    jcenter()
}

dependencies {
    compile 'org.apache.commons:commons-email:1.4'
}