Java for C++ ProgrammersOverviewSecond Night AgendaEnumerated Values in C++Enumerated Values in JavaSlide 6Enumerations in JavaSlide 8Slide 9Slide 10EnumerationsExceptions in C++Slide 13Slide 14Slide 15ExceptionsExceptions in JavaSlide 18Slide 19Slide 20Java Exception HierarchyHandling Checked ExceptionsSlide 23Slide 24Console I/O in C++Console Input/Output in JavaConsole Input in JavaConsole I/O in JavaFile Input in C++File Input in JavaFile Output in C++File Output in JavaExercisesBreakC++ TemplatesSlide 36Slide 37Slide 38Java GenericsSlide 40Slide 41Generics GotchasWrapper ClassesWrapper Classes & GenericsSlide 45Generics BoundingC++ STLJava SE APIJava Collections FrameworkC++ VectorJava VectorC++ ListJava ListC++ MapJava MapC++ DequeJava DequeSlide 58Java for C++ ProgrammersSecond NightOverview•First Night–Basics–Classes and Objects•Second Night–Enumerations–Exceptions–Input/Output–Templates vs. Generics–STL vs. JavaSE APISecond Night Agenda•Enumerations, Exceptions, Input/Output – enumeration declaration & usage, exception hierarchy, checked vs. unchecked exceptions, throwing & catching exceptions, scanner class, console I/O, file I/O–Discussion–Lab exercises•Break•Templates vs. Generics, STL vs. JavaSE API – –Discussion–Lab exercisesEnumerated Values in C++•One way to define a set of enumerated values/constants in C++ is as follows…•Example usage…const int CLUBS = 0;const int DIAMONDS = 1;const int HEARTS = 2;const int SPADES = 3;// good invocationsDrawSuit(CLUBS);DrawSuit(HEARTS);void DrawSuit(int s) { // draws the suit in a GUI}Enumerated Values in Java•Here’s the Java port of that C++ code…•Everything looks good, right?public class Suit { public static final int CLUBS = 0; public static final int DIAMONDS = 1; public static final int HEARTS = 2; public static final int SPADES = 3;}// good invocationsdrawCard(Suit.CLUBS);drawCard(Suit.DIAMONDS);static void drawCard(int s) { // draws the suit in a GUI}Enumerated Values in Java•Well, sort of – as long as the user behaves themselves…•Using something unbounded like an int or a String can be problematic, need to restrict the available choices// bad invocationsdrawCard(Suit.HEARTS * 5);drawCard(-516);static void drawCard(int s) { // draws the suit in a GUI}Enumerations in Java•Thankfully, there’s a better way to enumerate a set of values, staring in Java 5 there is an enumerated type–Similar to enum construct in C/C++–Enums are declared similarly to classespublic enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES}Enumerations in Java•Now, each constant is strongly typed•When something is expecting a suit, we specify a Suit enum type•Invalid usage is now caught at compile time// good invocationsdrawCard(Suit.CLUBS);drawCard(Suit.DIAMONDS);// compiler errorsdrawCard(Suit.HEARTS * 5);drawCard(-516);static void drawCard(Suit s) { // draws the symbol for the suit in a GUI}Enumerations in Java•Additionally, we can switch on enums…// draws the symbol for the suit in a GUIstatic void drawCard(Suit s) { switch(s) { case CLUBS: case SPADES: // switch color to black, then draw break; default: // switch color to red, then draw break; }}Enumerations in Java•We can also give enums in Java additional members and methodspublic enum Planet { VENUS(4.8685e24,6051.8e3), EARTH(5.9736e24,6378.1e3), MARS(0.64185e24,3397e3); public static final double G = 6.67300E-11; final double mass; final double radius; Planet(double mass, double radius) { this.mass = mass; this.radius = radius; } double surfaceGravity() { return G * mass / (radius * radius); } double surfaceWeight(double otherMass) { return otherMass * surfaceGravity(); }}Enumerations•Example usage, similar to a class…•But we get compiler errors, if we try to construct more…// compiler errorsPlanet.EARTH = new Planet(1.0, 1.0); Planet p = new Planet(1.0, 1.0);// acceptable usagedrawPlanet(Planet.EARTH);System.out.println("Surface gravity on earth: ");System.out.println(Planet.EARTH.surfaceGravity());Exceptions in C++•C++ allows us to throw anything as an exception•Here is a modified factorial function which throws the number back if it is less than 0int factorial(int n) { // check for exceptional case if(n < 0) { throw n; } // computation for normal case int result = 1; for(int i = n; i > 0; i--) { result *= i; } return result;}Exceptions in C++•Example catching of that exception in C++…int main(int argc, char** argv) { int num = -4; try { cout << "factorial(" << num << "): " << factorial(num) << endl; } catch(int i) { cerr << i << " is not valid" << endl; } return 0;}Exceptions in C++•We can also throw more complex types, for example, here is a custom exception class which stores an error message…class Exception { private: string m_message; public: Exception(string message) : m_message(message) { }; string GetMessage() { return this->m_message; };};Exceptions in C++•Factorial function modified to throw custom exception type…int factorial(int n) { // check for exceptional case if(n < 0) { throw Exception("number must be positive"); } // computation for normal case int result = 1; for(int i = n; i > 0; i--) { result *= i; } return result;}Exceptions•Example catching of that exception in C++…int main(int argc, char** argv) { int num = -4; try { cout << "factorial(" << num << "): " << factorial(num) << endl; } catch(Exception e) { cerr << e.GetMessage() << endl; } return 0;}Exceptions in Java•In Java, we cannot throw primitives or most objects•Anything that is thrown must be a Throwable (or a valid subclass)–Though, typically we throw Exceptions (or subclasses)Error ExceptionRuntimeExceptionErrorError…ErrorError…ErrorError…ThrowableObjectExceptions in Java•Here’s a Java port of that second example–We’re using the built-in Exception class…static int factorial(int n) { // check for exceptional case if(n < 0) { throw new Exception("number must be positive"); } // computation for normal case int result = 1; for(int i = n; i > 0; i--) { result *= i; } return result;}Exceptions in Java•Here is the invoking function in Java, with the try/catch block added…public static void main(String[] args) { int num = -4; try { System.out.println("factorial(" + num + "): " + factorial(num)); }
View Full Document