9-Jun-14 Enum s (and a review of switch statements)

Slides:



Advertisements
Similar presentations
Basic Java Constructs and Data Types – Nuts and Bolts
Advertisements

Java Language Quick-Reference Guide B. Oracle10g: Java Programming B - 2 Console Output Java applications and applets can output simple messages to the.
Everything You Ever Wanted To Know About Java O-O
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Interfaces (Part II) Course Lecture Slides 28 June 2010 A picture is.
1 CSE 331 Enumerated types ( enum ) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
New features in JDK 1.5 Can these new and complex features simplify Java development?
Object Oriented Programming with Java
1. Define the concept of assertions. 1 Explain the use of assertions. 2 Create Java program using assertions. 3 Run Java program using assertions. 4 2.
Recitation 4. 2-D arrays. Exceptions. Animal[] v= new Animal[3]; 2 declaration of array v v null Create array of 3 elements a6 Animal[] null Assign.
The if-else Statements
COSC 2006 Data Structures I Instructor: S. Xu URL:
Introduction to Programming G51PRG University of Nottingham Revision 1
Air Force Institute of Technology Electrical and Computer Engineering
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
Yoshi
Big Ideas behind Inheritance. Can you think of some possible examples of inheritance hierarchies?
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
More methods and classes, 4 of 4 Math 130 Introduction to Programming Lecture # 18 Monday, October 8, 2007.
Written by: Dr. JJ Shepherd
1-May-15 Java 1.5. Reason for changes “The new language features all have one thing in common: they take some common idiom and provide linguistic support.
8-May-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Slides 4/22 COP Topics Final Exam Review Final Exam The final exam is Friday, April 29 th at 10:00 AM in the usual room No notes, books, calculators,
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Random Number Generation public class Hand { private int card1; private int card2; private int card3; private Random rand; public static final int NO_CARD.
Additional control structures. The if-else statement The if-else statement chooses which of two statements to execute The if-else statement has the form:
16-Jun-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
The switch Statement, DecimalFormat, and Introduction to Looping
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 4.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Topic 3 The Stack ADT.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Compound Statements If you want to do more than one statement if an IF- else case, you can form a block of statements, or compound statement, by enclosing.
Introduction to Computer Science 2 Slide 1 Enumerated types We already know some data types int, float, char good for problems that involve int,
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Compound Statements If you want to do more than one statement if an if- else case, you can form a block of statements, or compound statement, by enclosing.
1 Enumerations and Structs Chapter 9. 2 Objectives You will be able to: Write programs that define and use enumeration variables. Write programs that.
ISBN Chapter 6 Data Types Introduction Primitive Data Types User-Defined Ordinal Types.
1-Dec-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall Java Programming.
CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park.
CONTENTS Wrapper Class Enumeration Garbage Collection Import static.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
11-Jan-16 Bits and Pieces Some random things in Java.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Written by: Dr. JJ Shepherd
1 Enums (Chapter 4) To enumerate is: to name things one after another in a list Java has a type, called an enum, where a programmer specifies a finite.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Seven Lecture Collection 1. 2 Some Legacy Collection Types  ArrayList  Enumeration  Vector  HashTable – self study.
Lecture 5:Interfaces and Abstract Classes
The switch Statement, and Introduction to Looping
Some random things in Java
Conditional Statements
(and a review of switch statements)
(and a review of switch statements)
Some random things in Java
Some random things in Java
Java 5 New Features 1-May-19.
Additional control structures
Presentation transcript:

9-Jun-14 Enum s (and a review of switch statements)

Enumerated values 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?

Enumerations 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; Heres the new way of doing it: enum Season { WINTER, SPRING, SUMMER, FALL }

enum s are classes 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 == enum s 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

Advantages of the new enum 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

Enums have weird constructors 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

Enums extend and inherit from Enum 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

Syntax of the switch statement 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

Flowchart for switch statement Oops: If you forget a break, one case runs into the next! expression? statement value

Example switch statement 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; }

Enums and the switch statement 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 namethat is, you must say case SUMMER:, not case Season.SUMMER: Its still a very good idea to include a default case

Example enum and switch 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:

Value-specific enum methods // 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:

The End 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 :53:39