Skip to content
  • Home
  • Search
  • Tools
  • About
  • Terms of Service Agreement
  • Log In
  • Guest

Java: Enum Examples – Templates for Enumerations

Posted on December 13, 2021October 15, 2022 By Andre Dias
java

Table of Contents

  • EXAMPLE #1 – Simplest
  • EXAMPLE #2
  • EXAMPLE #3
  • EXAMPLE #4
  • EXAMPLE #5
  • EXAMPLE #6
  • EXAMPLE #7
  • EXAMPLE #8
  • EXAMPLE #9
  • EXAMPLE #10

EXAMPLE #1 – Simplest

public enum Enum_ {

	SCJP, SCWCD, SWWD, WWFF;

	public static void main(String[] args) {
		System.out.println(Enum_.SCJP);
		System.out.println(Enum_.valueOf("SCJP"));
		Enum_[] e = Enum_.values();
		System.out.println("e[1] =  " + e[1]);
		System.out.println("Enum_.SCJP = " + Enum_.SCJP);
		System.out.println("Enum_.valueOf(\"SCJP\") = " + Enum_.valueOf("SCJP"));
		Enum_[] ae = Enum_.values();
		System.out.println("Enum_[] ae: ");
		for(Enum_ e1:ae) {
			System.out.println(e1);
		}
		Enum_ en = Enum_.SCJP;
		System.out.println("en.ordinal() = " + en.ordinal());
		System.out.println("en.name = " + en.name());
		System.out.println("done");
		System.out.println("en.ordinal() = " + en.ordinal());
		System.out.println("en.name() = " + en.name());

		System.out.println("\ndone");
	}

}

/* Output:
SCJP
SCJP
e[1] =  SCWCD
Enum_.SCJP = SCJP
Enum_.valueOf("SCJP") = SCJP
Enum_[] ae: 
SCJP
SCWCD
SWWD
WWFF
en.ordinal() = 0
en.name = SCJP
done
en.ordinal() = 0
en.name() = SCJP

done

*/

EXAMPLE #2

public class Enum_2 {

	static enum Weekday {SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY};

	@SuppressWarnings("static-access")
	public static void main(String[] args) {
		Weekday week = null;
		System.out.println("Arrays.toString: " + Arrays.toString(Weekday.values()));
		System.out.println("week.values() = " + week.values());
		System.out.println("Weekday.valueOf(\"SUNDAY\") = " + Weekday.valueOf("SUNDAY"));
		System.out.println("week.SUNDAY = " + Weekday.SUNDAY);
		System.out.println("week.SUNDAY.ordinal() = " + Weekday.SUNDAY.ordinal());
		System.out.println("week = " + week);
		week = Weekday.FRIDAY;
		System.out.println("week = Weekday.FRIDAY = " + week);
		System.out.println("week.ordinal() = " + week.ordinal());
		System.out.println("week.MONDAY.ordinal() = " + Weekday.MONDAY.ordinal());
	}

}

/*
 * - Output:

Arrays.toString: [SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY]
week.values() = [Lenums.Enum_2$Weekday;@659e0bfd
Weekday.valueOf("SUNDAY") = SUNDAY
week.SUNDAY = SUNDAY
week.SUNDAY.ordinal() = 0
week = null
week = Weekday.FRIDAY = FRIDAY
week.ordinal() = 5
week.MONDAY.ordinal() = 1

 */

EXAMPLE #3

enum Meal {

	BREAKFAST(30, 30), LUNCH(12, 15), DINNER(19, 45); // (1)

	// Non-default constructor (2)
	Meal(int hh, int mm) {
		this.hh = hh;
		this.mm = mm;
	}

	// Fields for the meal time: (3)
	private int hh;
	private int mm;

	// Instance methods: (4)
	public int getHour() {
		return this.hh;
	}

	public int getMins() {
		return this.mm;
	}
}

public class Enum_3 {

	public static void main(String[] args) {
		System.out.printf(
				// (5)
				"Please note that no eggs will be served at %s, %02d:%02d.%n",
				Meal.BREAKFAST, Meal.BREAKFAST.getHour(),
				Meal.BREAKFAST.getMins());

		System.out.println("Meal times are as follows:");
		Meal[] meals = Meal.values(); // (6)
		for (Meal meal : meals)
			System.out.printf("%s served at %02d:%02d%n", meal, meal.getHour(),	meal.getMins());

		Meal formalDinner = Meal.valueOf("DINNER"); // (8)
		System.out.printf("Formal dress is required for %s at %02d:%02d.%n",
				formalDinner, formalDinner.getHour(), formalDinner.getMins());
	}

}


/*
- Output:

Please note that no eggs will be served at BREAKFAST, 30:30.
Meal times are as follows:
BREAKFAST served at 30:30
LUNCH served at 12:15
DINNER served at 19:45
Formal dress is required for DINNER at 19:45.

 */

 

EXAMPLE #4

public class Enum4 {
	enum Drill {
		ATTENTION("Attention!"), EYES_RIGHT("Eyes right!"), EYES_LEFT("Eyes left!"), AT_EASE("At ease!");

		private String command;

		Drill(String command) {
			this.command = command;
		}

		public String getCommand() {
			return command;
		}

		public void setCommand(String command) {
			this.command = command;
		}
		
	}

	public static void main(String[] args) {
		System.out.println(Drill.ATTENTION); // (1)
		System.out.println(Drill.AT_EASE); // (2)
		System.out.println("Enum4.Drill.values().length = " + Enum4.Drill.values().length);
		Drill drill = Drill.ATTENTION;
		System.out.println("drill.getCommand() = " + drill.getCommand());
	}
}

/*
 - Output:

ATTENTION
AT_EASE
Enum4.Drill.values().length = 4

 */

EXAMPLE #5

enum Scale3 {

	GOOD(Grade.C), BETTER(Grade.B), BEST(Grade.A);

	enum Grade {
		A, B, C
	}

	private Grade grade;

	Scale3(Grade grade) {
		this.grade = grade;
	}

	public Grade getGrade() {
		return grade;
	}
}

public class Enum6_Scale3 {
	public static void main(String[] args) {
		System.out.println("1. " + Scale3.GOOD.getGrade());
		System.out.println("2. " + Scale3.Grade.C);
		System.out.print("3. "); System.out.println(Scale3.GOOD.getGrade().compareTo(Scale3.Grade.C) != 0);
		System.out.print("4. "); System.out.println(Scale3.GOOD.getGrade().compareTo(Scale3.Grade.A) > 0);
		System.out.println(Scale3.GOOD.getGrade() + " " + Scale3.Grade.A);
		System.out.println(Scale3.GOOD.getGrade().compareTo(Scale3.Grade.A));
		System.out.print("5. "); System.out.println(Scale3.GOOD.compareTo(Scale3.BEST) > 0);
		System.out.println(Scale3.GOOD.compareTo(Scale3.BEST));
		System.out.println(Scale3.GOOD + " " + Scale3.BEST);
		System.out.print("6. "); System.out.println(Scale3.GOOD.getGrade() instanceof Scale3.Grade);
		System.out.print("7. "); System.out.println(Scale3.GOOD instanceof Scale3);
		System.out.println(Scale3.GOOD.getClass() + " " + Scale3.class);
		System.out.print("8. "); System.out.println(Scale3.GOOD.getGrade().toString().equals(Scale3.Grade.C.toString()));
		System.out.print("9. "); System.out.println(Scale3.GOOD.getGrade().toString());

	}
}

/*
- Output:

1. C
2. C
3. false
4. true
C A
2
5. false
-2
GOOD BEST
6. true
7. true
class enums.Scale3 class enums.Scale3
8. true
9. C

*/

EXAMPLE #6

enum March {
	LEFT, RIGHT
} // (1)

public class Enum8 {

	enum March {
		LEFT, RIGHT
	} // (2)

	static enum Military {
		INFANTRY, AIRFORCE;
		enum March {
			LEFT, RIGHT
		} // (3)
	}

	enum NotMilitary {
		WALK, RUN;
		enum March {
			LEFT, RIGHT
		} // (3)
	}

	class Secret {
	}

// must be defined into a static member
//	class Secret {
//		enum March {
//			LEFT, RIGHT
//		} // (4)
//	}

	static class Open {
		enum March {
			LEFT, RIGHT
		} // (5)
		
//		public String getMessage(String fase) {
//			switch (FaseSlaDecisaoJudicialEnum.valueOf(fase.trim()).ordinal()) {
//				case 0:
//					return "CADASTRO";
//				case 1:
//					return "CONDUTA_ENVIO";
//				case 2:
//					return "SUPORTE ESCRITORIO";
//				case 3:
//					return "CUMPRIMENTO";
//				case 4:
//					return "VALIDACAO JURIDICO";
//				case 5:
//					return "CONTATO SEGURADO PRESTADOR";
//				default:
//					return "";
//			}
//		}

	}


	public static void declareWar() {
		// Can only be defined inside a top-level class or interface or in a static context.
		// enum March {LEFT, RIGHT}
		//enum Walk { WALK, RUN}
	}

	@SuppressWarnings("unused")
	public void declarePeace() {
		// Can only be defined inside a top-level class or interface or in a static context.
		// enum March {LEFT, RIGHT}
		//enum Walk { WALK, RUN}

		Enum8 civil;
	}

	public static void main(String[] args) {
		System.out.println("" + Enum8.March.LEFT);
		System.out.println("" + Enum8.Military.INFANTRY);
		System.out.println("" + Enum8.NotMilitary.WALK);
	}
}

/*
- Output:

LEFT
INFANTRY
CIVIL

*/

 

EXAMPLE #7

 

import java.util.Date; 

import org.slf4j.Logger;

import javaLib.services.StrSvc;

public class Event {

	protected EventTypeEnum type = EventTypeEnum.NONE;
	protected String description = "";
	protected Date occurrencyTime = new Date();
	
	public Event(String description, EventTypeEnum type) {
		this.description = description;
		this.type = type;
	}

	public boolean empty() {
		return type == EventTypeEnum.NONE && StrSvc.isNullEmpty(description);
	}

	public void logIt(Logger logger) {
		switch(type) {
			case INFO:
				logger.info(description);
				break;
			case WARN:
				logger.warn(description);
				break;
			case ERROR:
				logger.error(description);
				break;
			default:
				logger.info(description);
		}
	}
	
	public EventTypeEnum getType() {
		return type;
	}

	public void setType(EventTypeEnum type) {
		this.type = type;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public Date getOccurrencyTime() {
		return occurrencyTime;
	}

	public void setOccurrencyTime(Date occurrencyTime) {
		this.occurrencyTime = occurrencyTime;
	}
	
}

EXAMPLE #8

public enum TipoPerfilEnum {

	ALUNO("Aluno"),
	PROFESSOR("Professor"),
	ESCOLA("Escola"),
	REGIAO("Região"),
	MUNICIPIO("Município"),
	ADM("Administrador");

	private final String descricao;

	TipoPerfilEnum(final String param) {
		this.descricao = param;
	}

	public static TipoPerfilEnum getEnumFromValue(final String value) {
		for (TipoPerfilEnum tipo : TipoPerfilEnum.values()) {
			if (tipo.getDescricao().equalsIgnoreCase(value)) {
				return tipo;
			}
		}
		return null;
	}

	public String getKey() {
		return "descricao." + this.name();
	}

	/**
	 * @return the descricao
	 */
	public String getDescricao() {
		return descricao;
	}

	public String getDescricaoSemAcentos() {
		if (descricao == null) {
			return null;
		}
		String temp = Normalizer.normalize(getDescricao(), Normalizer.Form.NFD);
		temp = temp.replaceAll("[^\\p{ASCII}]", "");
		return temp;
	}

	public static void main(String[] args) {

		System.out.println("TipoPerfilEnum.valueOf(ALUNO) = " + TipoPerfilEnum.valueOf("ALUNO"));
		System.out.println("TipoPerfilEnum.valueOf(ALUNO) = " + TipoPerfilEnum.getEnumFromValue("aluno"));
		//System.out.println("TipoPerfilEnum.valueOf(aluno) = " + TipoPerfilEnum.valueOf("aluno"));
		System.out.println("TipoPerfilEnum.valueOf(ALUNO) = " + TipoPerfilEnum.getEnumFromValue("administrador"));
	}
}


/*
- Output:

TipoPerfilEnum.valueOf(ALUNO) = ALUNO
TipoPerfilEnum.valueOf(ALUNO) = ALUNO
TipoPerfilEnum.valueOf(ALUNO) = ADM

*/

 

EXAMPLE #9

public enum FaseSlaDecisaoJudicialEnum {

	CADASTRO("CADASTRO"),
	CONDUTA_ENVIO("CONDUTA_ENVIO"),
	SUPORTE_ESCRITORIO("SUPORTE_ESCRITORIO"),
	CUMPRIMENTO("CUMPRIMENTO"),
	VALIDACAO_JURIDICO("VALIDACAO_JURIDICO"),
	CONTATO_SEGURADO_PRESTADOR("CONTATO_SEGURADO_PRESTADOR");

	FaseSlaDecisaoJudicialEnum(String fase) {
		this.fase = fase;
	}

	private String fase;

	public String getFase() {
		return fase;
	}

	public void setFase(String fase) {
		this.fase = fase;
	}

	public static class Translator {
		
		public static String getMessage(String fase) {
			switch (FaseSlaDecisaoJudicialEnum.valueOf(fase.trim()).ordinal()) {
				case 0:
					return "CADASTRO";
				case 1:
					return "CONDUTA ENVIO";
				case 2:
					return "SUPORTE ESCRITORIO";
				case 3:
					return "CUMPRIMENTO";
				case 4:
					return "VALIDACAO JURIDICO";
				case 5:
					return "CONTATO SEGURADO PRESTADOR";
				default:
					return "";
			}
		}
	}

	public static void main(String[] args) {
		System.out.println("" + FaseSlaDecisaoJudicialEnum.CADASTRO);
		System.out.println("" + FaseSlaDecisaoJudicialEnum.values().length);
		System.out.println("" + FaseSlaDecisaoJudicialEnum.valueOf("CUMPRIMENTO").ordinal());
		System.out.println("" + FaseSlaDecisaoJudicialEnum.Translator.getMessage("CONDUTA_ENVIO"));
		
	}
}

 

EXAMPLE #10

package enums;

public enum Enum10 {
	
	GOOD, BETTER, BEST;
	public char getGrade() {
		char grade = '\u0000';
		switch (this) {
		case GOOD:
			grade = 'C';
			break;
		case BETTER:
			grade = 'B';
			break;
		case BEST:
			grade = 'A';
			break;
		}
		return grade;
	}

	public static void main(String[] args) {
		System.out.println("GOOD.getGrade() = " + GOOD.getGrade());
		System.out.println("GOOD = " + GOOD);
		System.out.println("Enum10.GOOD = " + Enum10.GOOD);
		System.out.println("Enum10.GOOD.getGrade() = " + Enum10.GOOD.getGrade());
	}
}

/*
- Output:

GOOD.getGrade() = C
GOOD = GOOD
Enum10.GOOD = GOOD
Enum10.GOOD.getGrade() = C

 */
Andre Dias
Andre Dias

Brazilian system analyst graduated by UNESA (University Estácio de Sá – Rio de Janeiro). Geek by heart.

Post navigation

❮ Previous Post: Node.js: Using multiple versions of Node.js with NVM command
Next Post: Docker: Step-by-Step For An Angular Project Using Spring Boot Web Service [ML33743] ❯

Search

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Filter by Categories
angular
bootstrap
browser
computer science
container
data persistence
database
devops
editors
hardware
health
hosting
info
internet
it
java
javascript
network
node.js
play
protocol
security
self-help
selfhelp
server
services
soft
software engeneering
sql
support
Systems
techs
Uncategorized
versioning
web
web design
windows
wordpress

Recent Posts

  • Assay for Route Recognition by Neural Network
  • Ensaio para Reconhecimento de Rotas por Rede Neural
  • Angular From Scratch Tutorial – Step 9: Modal
  • Angular From Scratch Tutorial – Step 8: Miscellany
  • Angular From Scratch Tutorial – Index

Categories

  • angular (19)
  • bootstrap (6)
  • browser (4)
  • computer science (4)
  • container (1)
  • data persistence (2)
  • database (11)
  • devops (1)
  • editors (1)
  • hardware (4)
  • health (2)
  • hosting (1)
  • info (1)
  • internet (2)
  • it (1)
  • java (13)
  • javascript (32)
  • network (6)
  • node.js (1)
  • play (1)
  • protocol (1)
  • security (4)
  • self-help (1)
  • selfhelp (1)
  • server (2)
  • services (1)
  • soft (1)
  • software engeneering (1)
  • sql (1)
  • support (2)
  • Systems (1)
  • techs (3)
  • Uncategorized (4)
  • versioning (6)
  • web (1)
  • web design (5)
  • windows (3)
  • wordpress (4)

Copyright © 2025 .

Theme: Oceanly by ScriptsTown

We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT