Enums. In this article from my free Java 8 course, I will talk about the enum. Enums are constant values that can never be changed.

Similar documents
Loops. In Example 1, we have a Person class, that counts the number of Person objects constructed.

Checked and Unchecked Exceptions in Java

Shallow Copy vs. Deep Copy

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Basic Keywords Practice Session

Import Statements, Instance Members, and the Default Constructor

The Object clone() Method

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Immutables. At first glance, you d think that immutables were useless, however, they provide many advantages.

Static Imports, Default Values, Number Types and More!

Inheritance and Polymorphism in Java

CSE 142/143 Unofficial Style Guide

Java Collections Framework

class objects instances Fields Constructors Methods static

Datatypes, Variables, and Operations

Lesson 2A Data. Data Types, Variables, Constants, Naming Rules, Limits. A Lesson in Java Programming

2SKILL. Variables Lesson 6. Remembering numbers (and other stuff)...

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

CS 231 Data Structures and Algorithms, Fall 2016

The Java Main Method

ArrayList. Introduction. java.util.arraylist

Array. Prepared By - Rifat Shahriyar

CS 251 Intermediate Programming Coding Standards

Identifiers and Variables

Objective-C. Stanford CS193p Fall 2013

Program Fundamentals

CIS 194: Homework 6. Due Friday, October 17, Preface. Setup. Generics. No template file is provided for this homework.

Variables and Data Representation

Classes Classes 2 / 35

CS125 : Introduction to Computer Science. Lecture Notes #6 Compound Statements, Scope, and Advanced Conditionals

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

CS 351 Design of Large Programs Coding Standards

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

CIS220 In Class/Lab 1: Due Sunday night at midnight. Submit all files through Canvas (25 pts)

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

What is it? CMSC 433 Programming Language Technologies and Paradigms Spring Approach 1. Disadvantage of Approach 1

CS121/IS223. Object Reference Variables. Dr Olly Gotel

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Java Review. Fundamentals of Computer Science

4.7 Approximate Integration

Chapter 4 Defining Classes I

VARIABLES AND TYPES CITS1001

IT Web and Software Developer Software Development Standards

The Java Type System (continued)

Arduino IDE Friday, 26 October 2018

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

APCS Semester #1 Final Exam Practice Problems

CS 152 Computer Programming Fundamentals Coding Standards

CS18000: Problem Solving And Object-Oriented Programming

CPS122 Lecture: Defining a Class

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

Processing/Java Syntax. Classes, objects, arrays, and ArrayLists

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

CS125 : Introduction to Computer Science. Lecture Notes #11 Procedural Composition and Abstraction. c 2005, 2004 Jason Zych

Chapter 3 Data Types and Variables

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

CS61A Notes Week 6: Scheme1, Data Directed Programming You Are Scheme and don t let anyone tell you otherwise

Midterms Save the Dates!

Computer Components. Software{ User Programs. Operating System. Hardware

CS112 Lecture: Working with Numbers

Topic 7: Algebraic Data Types

Arrays. COMS W1007 Introduction to Computer Science. Christopher Conway 10 June 2003

These are notes for the third lecture; if statements and loops.

CGS 3066: Spring 2015 JavaScript Reference

CSCI 1301: Introduction to Computing and Programming Summer 2018 Lab 07 Classes and Methods

CS1004: Intro to CS in Java, Spring 2005

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Classes Classes 2 / 36

1/29/2018. Starting a Program Executes its main Function. ECE 220: Computer Systems & Programming. The Function main Divides into Two Parts

data_type variable_name = value; Here value is optional because in java, you can declare the variable first and then later assign the value to it.

Java and OOP. Part 2 Classes and objects

Ex: If you use a program to record sales, you will want to remember data:

Java Identifiers, Data Types & Variables

09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013

User s Manual. for. Diagram Consistency and Validation in agenttool III

Classes, interfaces, & documentation. Review of basic building blocks

Problem 1: Building and testing your own linked indexed list

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

CSCI 1301: Introduction to Computing and Programming Spring 2019 Lab 10 Classes and Methods

Programming Paradigms

Constants are named in ALL_CAPS, using upper case letters and underscores in their names.

The Dynamic Typing Interlude

As a programmer, you know how easy it can be to get lost in the details

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Computational Expression

Enumerated Types. CSE 114, Computer Science 1 Stony Brook University

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

1B1b Classes in Java Part I

Discussion 1H Notes (Week 2, 4/8) TA: Brian Choi Section Webpage:

Tokens, Expressions and Control Structures

CSCI-1200 Data Structures Fall 2018 Lecture 3 Classes I

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Sample Examination Paper Programming and Software Development

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

CS260 Intro to Java & Android 03.Java Language Basics

BM214E Object Oriented Programming Lecture 8

If you don t, it will return the same thing as == But this may not be what you want... Several different kinds of equality to consider:

Java Threads and intrinsic locks

Transcription:

Enums Introduction In this article from my free Java 8 course, I will talk about the enum. Enums are constant values that can never be changed. The Final Tag To display why this is useful, I m going to start by introducing the concept of constant values in Java and talk about their flaws. Let s say we wanted to save an array, as is, so that any time it is used in the future,we know for sure which references are in which places. We could do this using the variable modifier final. A variable declared as final is locked in and cannot have a new value assigned to it. For example, if we made persons2 final, and then tried to set it to null, Java will give an exception. final Person[] persons2 = {new Person(), null, null; persons2 = null; // Compilation Error Example 1 This could be very useful if you have a set of values you want to stay constant. One of the things you could do is create a set of state values. State values, as the name implies, tell us what state our program is in. Let s say our three state values for a program are PENDING, PROCESSING, and PROCESSED. We could place these String values into an array and add the final tag to preserve them. We re also going to make the array static so that it s shared among all the objects. Since it can t be modified, there s no reason not to share it among objects; also it helps us communicate our intent that these state values are the same for all objects. We ll call this array MY_STATE_VALUES. Here s what this would look like: private static final String MY_STATE_VALUES[] = {"PENDING", "PROCESSING", "PROCESSED"; Example 2 You might notice that my variable name does not follow the default camelcase notation, but instead is composed of words in UPPERCASE LETTERS connected by underscores. This is because our variable, isn t really variable. It s static and final. You just want it read, the reference variable can never be modified; so to represent this difference, the naming convention is different. For static final variables, always use capital letters connected by underscores.

While we can t modify our array reference variable, we can iterate through it using a for-each loop. Inside this for-each loop, we could compare our states to a certain value and call some method when the value and the state match. Comparing Strings Since String is an object and not a primitive value, the equals operator ( == ) doesn t work. Instead, String has a method equals() to compare equality. We call it by using String.equals(otherString) and it returns a boolean value (true / false) as to whether or not the two strings are equal. If you re interested in learning more about this, you should check out my article about Identity and Equality in Java. In a for-each loop, I m going to create three if-statements, one for each state in our MY_STATE_VALUES array. Typically when you are comparing a constant String value and a variable using equals(), you write CONSTANT_VALUE.equals(variable), because a variable could be set to null and this would cause an error. If we had instead written PENDING.equals(state) and state was null, the condition would just return false and this would not cause any error. This is a general principle I advise you to aim for - whenever you can, aim to write stable code, even when the input given is invalid. In this case, I chose not to do this, because I assume that my variable is going to always be a constant and my code is more readable this way. for (String state : MY_STATE_VALUES) { Example 3 if (state.equals("pending")) { if (state.equals("processing")) { if (state.equals("processed")) { So this looks like it would work great. We iterate through everything in the MY_STATE_VALUES array and the three methods are all called in the proper order. Sadly though, that s not the case. While the final modifier protects our array reference variable, it doesn t protect the array object or any of its inner references at all. If state was changed to blah right before our if statements, that would be a huge problem. But don t worry, there s a solution: the enum.

Enum While an array that is tagged final provides us with an unchangeable array, as I ve shown above, those values can be changed, which is a problem. An enum allows us to define an enumeration which means a complete ordered list of a collection. This enumeration cannot be modified once created. An example of an enumeration in real life would be a traffic light. It has three distinct values: GREEN, YELLOW and RED; no matter what happens you can never change these values. This could be extremely useful if applied to something like the set of states we talked about in Examples 2 and 3. Let s create an enum called LoggingLevel which stores our three states: package com.marcusbiel.java8course; public enum LoggingLevel { PENDING, PROCESSING, PROCESSED; Example 4 An enum is declared similarly to a class, using public enum EnumName. I m going to call our enum LoggingLevel and for this example, I ll use the same three states we used in our array: PENDING, PROCESSING, and PROCESSED. Inside the declaration, we put in these values. You don t need double quotes, because these aren t strings. They re our own set of enumeration values. And that s it! You ve defined your enum. An enum is useful when we want to have a list of items, such as states or logging levels, that we want to use in our code, but we don t want them to be changeable. While the references contained in the array object can be modified, once created the enum can t be modified. Uses for Enums Enums are considered constant values. You can create reference variables that point to enums and print out enums values. You can also check the equality of enums using == instead of the equals() method. This is because all enums are constants and we know that no enum value is ever copied. Therefore, checking for identity is the same as checking for equality. If you re interested in the difference between these two, check out my article Identity and Equality in Java. LoggingLevel currentlogginglevel = LoggingLevel.PROCESSING; System.out.println( current LoggingLevel is: + currentlogginglevel); System.out.println(currentLoggingLevel == LoggingLevel.PROCESSING); // true Example 5

You can also search through your enumeration to find a specific enum value using a String. For example: LoggingLevel currentlogginglevel = LoggingLevel.valueOf( PROCESSING ); LoggingLevel illegallogginglevel = LoggingLevel.valueOf( processing );//Compiler Error Example 6 Please note that the functionality displayed in Example 6 is case sensitive, meaning that the second line of code would cause a compiler error. Adding Values to Enums Another feature of enums is that we can add constructors to them. We can assign many different types of values to each value in your enum. In this example, let s assign number values, different from the default values, to each LoggingLevel value. If we create a private variable i, and set it to the number we send our constructor, we can assign each logging level a value that is usable. Since both the constructor and the value should only be visible inside the class, I m going to make them private. Since the enum will call the constructor on its own, you re not allowed to construct enum values. This is why we make our enum constructor private. If you want to show off and seem smart, you should know that you can technically also make an enum constructor package-private, however, it's about as useful as the human appendix. Using the package-private modifier doesn t help because you still can t construct an enum from outside. public enum LoggingLevel { PENDING(1), PROCESSING(2), PROCESSED(3); private int i; private LoggingLevel(int i) { this.i = i; Example 7

Applying Enums to our Example Now if we go back to the example I used in the beginning, we don t even need our array anymore, because we already have those values defined in the enum. We can instead apply all our code using the LoggingLevel enum. To get all the values of our enum we use the values() method, which returns all of our enum values in an array. for (LoggingLevel state : LoggingLevel.values()) { if (state == LoggingLevel.PENDING) { if (state == LoggingLevel.PROCESSING) { if (state == LoggingLevel.PROCESSED) { Example 8 If you compared our code to the code in Example 3, you d notice that we don t need to use the equals() method because we re not comparing two different String objects anymore, we re comparing constant enum values. This works because that s how Java defines enums. Behind the scenes Java converts our enum values to final primitive values that are unchangeable. So we know that whenever we call LoggingLevel.PENDING, it will always be the same value. We can actually shorten our code even further if we add something called a switch-statement to replace the if statement we used in Example 5, but we ll do that in the next article which discusses the Java switch statement in detail. Thanks for reading! 2017, Marcus Biel, Software Craftsman https://cleancodeacademy.com All rights reserved. No part of this article may be reproduced or shared in any manner whatsoever without prior written permission from the author