SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 
Java Data Types
Java Data TypesJava Data Types
Java Data TypesSpotle.ai
 
ITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in javaITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in javaAtul Sehdev
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programmingavikdhupar
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20myrajendra
 
Enumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | EdurekaEnumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | EdurekaEdureka!
 
If else statement in c++
If else statement in c++If else statement in c++
If else statement in c++Bishal Sharma
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVAAnkita Totala
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)Ravi_Kant_Sahu
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statementsKuppusamy P
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packagesVINOTH R
 

What's hot (20)

String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Features of java
Features of javaFeatures of java
Features of java
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
ITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in javaITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in java
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Data types
Data typesData types
Data types
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
 
Enumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | EdurekaEnumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | Edureka
 
If else statement in c++
If else statement in c++If else statement in c++
If else statement in c++
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 

Similar to 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
 

Similar to 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
 

More from 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
 

More from 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
 

Recently uploaded

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Recently uploaded (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 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