SlideShare ist ein Scribd-Unternehmen logo
1 von 14
Apr 15, 2015
 Sometimes you want a variable that can take on
only a certain listed (enumerated) set of values
 Examples:
◦ dayOfWeek: SUNDAY, MONDAY, TUESDAY, …
◦ month: JAN, FEB, MAR, APR, …
◦ gender: MALE, FEMALE
◦ title: MR, MRS, MS, DR
◦ appletState: READY, RUNNING, BLOCKED, DEAD
 The values are written in all caps because they
are constants
 What is the actual type of these constants?
 In the past, enumerations were usually
represented as integer values:
◦ public final int SPRING = 0;
public final int SUMMER = 1;
public final int FALL = 2;
public final int WINTER = 3;
 This is a nuisance, and is error prone as well
◦ season = season + 1;
◦ now = WINTER; …; month = now;
 Here’s the new way of doing it:
◦ enum Season { WINTER, SPRING, SUMMER, FALL }
 An enum is actually a new type of class
◦ You can declare them as inner classes or outer classes
◦ You can declare variables of an enum type and get type safety and
compile time checking
 Each declared value is an instance of the enum class
 Enums are implicitly public, static, and final
 You can compare enums with either equals or ==
◦ enums extend java.lang.Enum and implement java.lang.Comparable
 Hence, enums can be sorted
◦ Enums override toString() and provide valueOf()
◦ Example:
 Season season = Season.WINTER;
 System.out.println(season ); // prints WINTER
 season = Season.valueOf("SPRING"); // sets season to Season.SPRING
 Enums provide compile-time type safety
◦ int enums don't provide any type safety at all: season = 43;
 Enums provide a proper name space for the enumerated type
◦ With int enums you have to prefix the constants (for example,
seasonWINTER or S_WINTER) to get anything like a name space.
 Enums are robust
◦ If you add, remove, or reorder constants, you must recompile, and
then everything is OK again
 Enum printed values are informative
◦ If you print an int enum you just see a number
 Because enums are objects, you can put them in collections
 Because enums are classes, you can add fields and methods
 Except for constructors, an Enum is an ordinary class
 Each name listed within an Enum is actually a call to a
constructor
 Example:
◦ enum Season { WINTER, SPRING, SUMMER, FALL }
◦ This constructs the four named objects, using the default constructor
 Example 2:
◦ public enum Coin {
private final int value;
Coin(int value) { this.value = value; }
PENNY(1), NICKEL(5), DIME(10), QUARTER(25);
}
 Enum constructors are only available within the Enum itself
◦ An enumeration is supposed to be complete and unchangeable
 String toString() returns the name of this enum constant, as
contained in the declaration
 boolean equals(Object other) returns true if the specified object is
equal to this enum constant
 int compareTo(E o) compares this enum with the specified object
for order; returns a negative integer, zero, or a positive integer as
this object is less than, equal to, or greater than the specified object
 static enum-type valueOf(String s) returns the enumerated object
whose name is s
 static enum-type[] values() returns an array of the enumeration
objects
 The syntax is:
switch (expression) {
case value1 :
statements ;
break ;
case value2 :
statements ;
break ;
...(more cases)...
default :
statements ;
break ;
}
 The expression must yield
an integer or a character
 Each value must be a literal
integer or character
 Notice that colons ( : ) are
used as well as semicolons
 The last statement in every
case should be a break;
◦ I even like to do this in the last
case
 The default: case handles
every value not otherwise
handled
◦ The default case is usually last,
but doesn't have to be
Oops: If you forget a
break, one case
runs into the next!
expression?
statement statementstatementstatementstatement
value
value value value
value
switch (cardValue) {
case 1:
System.out.print("Ace");
break;
case 11:
System.out.print("Jack");
break;
case 12:
System.out.print("Queen");
break;
case 13:
System.out.print("King");
break;
default:
System.out.print(cardValue);
break;
}
 switch statements can now work with enums
◦ The switch variable evaluates to some enum value
◦ The values for each case must (as always) be constants
 switch (variable) { case constant: …; }
◦ In the switch constants, do not give the class name—that
is, you must say case SUMMER:, not case
Season.SUMMER:
 It’s still a very good idea to include a default case
public void tellItLikeItIs(DayOfWeek day) {
switch (day) {
case MONDAY:
System.out.println("Mondays are bad.");
break;
case FRIDAY:
System.out.println("Fridays are better.");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekends are best.");
break;
default:
System.out.println("Midweek days are so-so.");
break;
}
} Source: http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html
// These are the the opcodes that our stack machine can execute.
abstract static enum Opcode {
PUSH(1),
ADD(0),
BEZ(1); // Remember the required semicolon after last enum value
int numOperands;
Opcode(int numOperands) { this.numOperands = numOperands; }
public void perform(StackMachine machine, int[] operands) {
switch(this) {
case PUSH: machine.push(operands[0]); break;
case ADD: machine.push(machine.pop( ) + machine.pop( )); break;
case BEZ: if (machine.pop( ) == 0) machine.setPC(operands[0]); break;
default: throw new AssertionError( );
}
}
}
From: http://snipplr.com/view/433/valuespecific-class-bodies-in-an-enum/
Over the last 7 years I have come to the following conclusions:
There are no instances in which TDD is impossible.
There are no instances in which TDD is not advantageous.
The impediments to TDD are human, not technical.
The alternative to TDD is code that is not repeatably testable.
--Robert Martin on the junit mailing list, Sunday, 17 Aug 2006 10:53:39

Weitere ähnliche Inhalte

Was ist angesagt?

Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classesShreyans Pathak
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsMahika Tutorials
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in JavaNiloy Saha
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in javaGoogle
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVAAnkita Totala
 
String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 

Was ist angesagt? (20)

Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Exception handling
Exception handlingException handling
Exception handling
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Interface in java
Interface in javaInterface in java
Interface in java
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Generics
GenericsGenerics
Generics
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 

Ähnlich wie enums

05a-enum.ppt
05a-enum.ppt05a-enum.ppt
05a-enum.pptMuthuMs8
 
Lecture 6 Enumeration in java ADVANCE.pptx
Lecture 6 Enumeration in java ADVANCE.pptxLecture 6 Enumeration in java ADVANCE.pptx
Lecture 6 Enumeration in java ADVANCE.pptxAbdulHaseeb956404
 
Maclennan chap5-pascal
Maclennan chap5-pascalMaclennan chap5-pascal
Maclennan chap5-pascalSerghei Urban
 
Chapter3 basic java data types and declarations
Chapter3 basic java data types and declarationsChapter3 basic java data types and declarations
Chapter3 basic java data types and declarationssshhzap
 
I am having some trouble getting this to compile, I have made seve.docx
I am having some trouble getting this to compile, I have made seve.docxI am having some trouble getting this to compile, I have made seve.docx
I am having some trouble getting this to compile, I have made seve.docxadampcarr67227
 
Identifiers, keywords and types
Identifiers, keywords and typesIdentifiers, keywords and types
Identifiers, keywords and typesDaman Toor
 
Week 7 Slides - Advanced Queries - SQL Functions (1).pptx
Week 7 Slides - Advanced Queries - SQL Functions (1).pptxWeek 7 Slides - Advanced Queries - SQL Functions (1).pptx
Week 7 Slides - Advanced Queries - SQL Functions (1).pptxSadhanaKumari43
 
CSC111-Chap_02.pdf
CSC111-Chap_02.pdfCSC111-Chap_02.pdf
CSC111-Chap_02.pdf2b75fd3051
 
UNIT 1- RELATIONAL DATABASE DESIGN USING PLSQL.pdf
UNIT 1- RELATIONAL DATABASE DESIGN USING PLSQL.pdfUNIT 1- RELATIONAL DATABASE DESIGN USING PLSQL.pdf
UNIT 1- RELATIONAL DATABASE DESIGN USING PLSQL.pdfKavitaShinde26
 
User defined data type
User defined data typeUser defined data type
User defined data typeAmit Kapoor
 

Ähnlich wie enums (16)

Enums in c
Enums in cEnums in c
Enums in c
 
Enumerations, structure and class IN SWIFT
Enumerations, structure and class IN SWIFTEnumerations, structure and class IN SWIFT
Enumerations, structure and class IN SWIFT
 
05a-enum.ppt
05a-enum.ppt05a-enum.ppt
05a-enum.ppt
 
Lecture 6 Enumeration in java ADVANCE.pptx
Lecture 6 Enumeration in java ADVANCE.pptxLecture 6 Enumeration in java ADVANCE.pptx
Lecture 6 Enumeration in java ADVANCE.pptx
 
How to Program
How to ProgramHow to Program
How to Program
 
Maclennan chap5-pascal
Maclennan chap5-pascalMaclennan chap5-pascal
Maclennan chap5-pascal
 
Chapter3 basic java data types and declarations
Chapter3 basic java data types and declarationsChapter3 basic java data types and declarations
Chapter3 basic java data types and declarations
 
I am having some trouble getting this to compile, I have made seve.docx
I am having some trouble getting this to compile, I have made seve.docxI am having some trouble getting this to compile, I have made seve.docx
I am having some trouble getting this to compile, I have made seve.docx
 
Identifiers, keywords and types
Identifiers, keywords and typesIdentifiers, keywords and types
Identifiers, keywords and types
 
Week 7 Slides - Advanced Queries - SQL Functions (1).pptx
Week 7 Slides - Advanced Queries - SQL Functions (1).pptxWeek 7 Slides - Advanced Queries - SQL Functions (1).pptx
Week 7 Slides - Advanced Queries - SQL Functions (1).pptx
 
CSC111-Chap_02.pdf
CSC111-Chap_02.pdfCSC111-Chap_02.pdf
CSC111-Chap_02.pdf
 
UNIT 1- RELATIONAL DATABASE DESIGN USING PLSQL.pdf
UNIT 1- RELATIONAL DATABASE DESIGN USING PLSQL.pdfUNIT 1- RELATIONAL DATABASE DESIGN USING PLSQL.pdf
UNIT 1- RELATIONAL DATABASE DESIGN USING PLSQL.pdf
 
User defined data type
User defined data typeUser defined data type
User defined data type
 
Variables
VariablesVariables
Variables
 
c# Enumerations
c# Enumerationsc# Enumerations
c# Enumerations
 
CHAPTER 5
CHAPTER 5CHAPTER 5
CHAPTER 5
 

Mehr von teach4uin

Master pages
Master pagesMaster pages
Master pagesteach4uin
 
.Net framework
.Net framework.Net framework
.Net frameworkteach4uin
 
Scripting languages
Scripting languagesScripting languages
Scripting languagesteach4uin
 
State management
State managementState management
State managementteach4uin
 
security configuration
security configurationsecurity configuration
security configurationteach4uin
 
static dynamic html tags
 static dynamic html tags static dynamic html tags
static dynamic html tagsteach4uin
 
static dynamic html tags
static dynamic html tagsstatic dynamic html tags
static dynamic html tagsteach4uin
 
New microsoft office power point presentation
New microsoft office power point presentationNew microsoft office power point presentation
New microsoft office power point presentationteach4uin
 
.Net overview
.Net overview.Net overview
.Net overviewteach4uin
 
Stdlib functions lesson
Stdlib functions lessonStdlib functions lesson
Stdlib functions lessonteach4uin
 
storage clas
storage classtorage clas
storage clasteach4uin
 
Cprogrammingprogramcontrols
CprogrammingprogramcontrolsCprogrammingprogramcontrols
Cprogrammingprogramcontrolsteach4uin
 

Mehr von teach4uin (20)

Controls
ControlsControls
Controls
 
validation
validationvalidation
validation
 
validation
validationvalidation
validation
 
Master pages
Master pagesMaster pages
Master pages
 
.Net framework
.Net framework.Net framework
.Net framework
 
Scripting languages
Scripting languagesScripting languages
Scripting languages
 
Css1
Css1Css1
Css1
 
Code model
Code modelCode model
Code model
 
Asp db
Asp dbAsp db
Asp db
 
State management
State managementState management
State management
 
security configuration
security configurationsecurity configuration
security configuration
 
static dynamic html tags
 static dynamic html tags static dynamic html tags
static dynamic html tags
 
static dynamic html tags
static dynamic html tagsstatic dynamic html tags
static dynamic html tags
 
New microsoft office power point presentation
New microsoft office power point presentationNew microsoft office power point presentation
New microsoft office power point presentation
 
.Net overview
.Net overview.Net overview
.Net overview
 
Stdlib functions lesson
Stdlib functions lessonStdlib functions lesson
Stdlib functions lesson
 
memory
memorymemory
memory
 
array
arrayarray
array
 
storage clas
storage classtorage clas
storage clas
 
Cprogrammingprogramcontrols
CprogrammingprogramcontrolsCprogrammingprogramcontrols
Cprogrammingprogramcontrols
 

Kürzlich hochgeladen

Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 

Kürzlich hochgeladen (20)

Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 

enums

  • 2.  Sometimes you want a variable that can take on only a certain listed (enumerated) set of values  Examples: ◦ dayOfWeek: SUNDAY, MONDAY, TUESDAY, … ◦ month: JAN, FEB, MAR, APR, … ◦ gender: MALE, FEMALE ◦ title: MR, MRS, MS, DR ◦ appletState: READY, RUNNING, BLOCKED, DEAD  The values are written in all caps because they are constants  What is the actual type of these constants?
  • 3.  In the past, enumerations were usually represented as integer values: ◦ public final int SPRING = 0; public final int SUMMER = 1; public final int FALL = 2; public final int WINTER = 3;  This is a nuisance, and is error prone as well ◦ season = season + 1; ◦ now = WINTER; …; month = now;  Here’s the new way of doing it: ◦ enum Season { WINTER, SPRING, SUMMER, FALL }
  • 4.  An enum is actually a new type of class ◦ You can declare them as inner classes or outer classes ◦ You can declare variables of an enum type and get type safety and compile time checking  Each declared value is an instance of the enum class  Enums are implicitly public, static, and final  You can compare enums with either equals or == ◦ enums extend java.lang.Enum and implement java.lang.Comparable  Hence, enums can be sorted ◦ Enums override toString() and provide valueOf() ◦ Example:  Season season = Season.WINTER;  System.out.println(season ); // prints WINTER  season = Season.valueOf("SPRING"); // sets season to Season.SPRING
  • 5.  Enums provide compile-time type safety ◦ int enums don't provide any type safety at all: season = 43;  Enums provide a proper name space for the enumerated type ◦ With int enums you have to prefix the constants (for example, seasonWINTER or S_WINTER) to get anything like a name space.  Enums are robust ◦ If you add, remove, or reorder constants, you must recompile, and then everything is OK again  Enum printed values are informative ◦ If you print an int enum you just see a number  Because enums are objects, you can put them in collections  Because enums are classes, you can add fields and methods
  • 6.  Except for constructors, an Enum is an ordinary class  Each name listed within an Enum is actually a call to a constructor  Example: ◦ enum Season { WINTER, SPRING, SUMMER, FALL } ◦ This constructs the four named objects, using the default constructor  Example 2: ◦ public enum Coin { private final int value; Coin(int value) { this.value = value; } PENNY(1), NICKEL(5), DIME(10), QUARTER(25); }  Enum constructors are only available within the Enum itself ◦ An enumeration is supposed to be complete and unchangeable
  • 7.  String toString() returns the name of this enum constant, as contained in the declaration  boolean equals(Object other) returns true if the specified object is equal to this enum constant  int compareTo(E o) compares this enum with the specified object for order; returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object  static enum-type valueOf(String s) returns the enumerated object whose name is s  static enum-type[] values() returns an array of the enumeration objects
  • 8.  The syntax is: switch (expression) { case value1 : statements ; break ; case value2 : statements ; break ; ...(more cases)... default : statements ; break ; }  The expression must yield an integer or a character  Each value must be a literal integer or character  Notice that colons ( : ) are used as well as semicolons  The last statement in every case should be a break; ◦ I even like to do this in the last case  The default: case handles every value not otherwise handled ◦ The default case is usually last, but doesn't have to be
  • 9. Oops: If you forget a break, one case runs into the next! expression? statement statementstatementstatementstatement value value value value value
  • 10. switch (cardValue) { case 1: System.out.print("Ace"); break; case 11: System.out.print("Jack"); break; case 12: System.out.print("Queen"); break; case 13: System.out.print("King"); break; default: System.out.print(cardValue); break; }
  • 11.  switch statements can now work with enums ◦ The switch variable evaluates to some enum value ◦ The values for each case must (as always) be constants  switch (variable) { case constant: …; } ◦ In the switch constants, do not give the class name—that is, you must say case SUMMER:, not case Season.SUMMER:  It’s still a very good idea to include a default case
  • 12. public void tellItLikeItIs(DayOfWeek day) { switch (day) { case MONDAY: System.out.println("Mondays are bad."); break; case FRIDAY: System.out.println("Fridays are better."); break; case SATURDAY: case SUNDAY: System.out.println("Weekends are best."); break; default: System.out.println("Midweek days are so-so."); break; } } Source: http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html
  • 13. // These are the the opcodes that our stack machine can execute. abstract static enum Opcode { PUSH(1), ADD(0), BEZ(1); // Remember the required semicolon after last enum value int numOperands; Opcode(int numOperands) { this.numOperands = numOperands; } public void perform(StackMachine machine, int[] operands) { switch(this) { case PUSH: machine.push(operands[0]); break; case ADD: machine.push(machine.pop( ) + machine.pop( )); break; case BEZ: if (machine.pop( ) == 0) machine.setPC(operands[0]); break; default: throw new AssertionError( ); } } } From: http://snipplr.com/view/433/valuespecific-class-bodies-in-an-enum/
  • 14. Over the last 7 years I have come to the following conclusions: There are no instances in which TDD is impossible. There are no instances in which TDD is not advantageous. The impediments to TDD are human, not technical. The alternative to TDD is code that is not repeatably testable. --Robert Martin on the junit mailing list, Sunday, 17 Aug 2006 10:53:39