Get Month Name

Map the given integer to a month.


For month = 1, the output should be

getMonthName(month) = "Jan"

For month = 0, the output should be

getMonthName(month) = "invalid month"


import java.util.Locale;
import java.text.DateFormatSymbols;

public class MonthNamer {

  private final static INVALID_MONTH_LABEL = "invalid month";

  private String getMonthName(Integer month){		
	if(month < 1 || month > 12){
	return new DateFormatSymbols(Locale.ENGLISH).getShortMonths()[month-1];

  public static void main(String[] args){
	Integer month = 1;
	String result = new MonthNamer().getMonthName(month);
	assert result == 'Jan'

To download the code:

git clone https://github.com/josdem/algorithms-workshop.git
cd get-month-name

To run the code:

javac MonthNamer.java
java -ea MonthNamer

Return to the main article

With your donation, you help me to maintain this site and posts.

comments powered by Disqus