1 / 128

Enumerations, Autoboxing

Enumerations, Autoboxing. Enumerations Enumeration is a list of named constants. In languages such as C++, enumerations are simply lists of named integer constants. In Java, an enumeration defines a class type. Enumeration can have constructors, methods, and instance variables.

anoush
Download Presentation

Enumerations, Autoboxing

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Enumerations, Autoboxing

  2. Enumerations • Enumeration is a list of named constants. • In languages such as C++, enumerations are simply lists of named integer constants. • In Java, an enumeration defines a class type. • Enumeration can have constructors, methods, and instance variables.

  3. Enumeration Fundamentals • An enumeration is created using the enum keyword. // An enumeration of apple varieties. enum Apple { Jonathan, GoldenDel, RedDel, Winesap, Cortland }

  4. The identifiers Jonathan, GoldenDel, and so on, are called enumeration constants. • Each is implicitly declared as a public, static final member of Apple. • Their type is the type of the enumeration in which they are declared, which is Apple. • Once we have defined an enumeration, we can create a variable of that type.

  5. Even though its of class type, no need to instantiate an enum using new. • We can declare and use an enumeration variable. Eg: Apple ap; - ap is of type Apple, so it can be assigned the value only defined by the enumeration. Eg: ap = Apple.RedDel; • ap is having the value RedDel:

  6. To display an enumeration constant using println( ) statement. Eg: System.out.println(Apple.Winesap); Output : Winesap

  7. The values( ) and valueOf( ) Methods • All enumerations automatically contain two predefined methods: values( ) and valueOf( ). General forms : public static enum-type[ ] values( ) public static enum-type valueOf(String str) • values( ) method returns an array that contains a list of the enumeration constants. • valueOf( ) method returns the enumeration constant whose value corresponds to the string passed in str.

  8. // Use the built-in enumeration methods. // An enumeration of apple varieties. enum Apple { Jonathan, GoldenDel, RedDel, Winesap, Cortland } class EnumDemo2 { public static void main(String args[ ]) { Apple ap;

  9. Apple allapples[ ] = Apple.values(); for(Apple a : allapples) System.out.println(a); System.out.println(); ap = Apple.valueOf("Winesap"); System.out.println("ap contains " + ap); } }

  10. Output : Jonathan GoldenDel RedDel Winesap Cortland ap contains Winesap

  11. Java Enumerations Are Class Types • Java enumeration is a class type. • Even though we don’t instantiate an enum using new, it has the same capabilities as other classes. • It can have constructors, instance variables and methods. • Implement interfaces.

  12. // Use an enum constructor, instance variable and method. enum Apple { Jonathan(10), GoldenDel(9), RedDel(12), Winesap(15), Cortland(8); private int price; // price of each apple // Constructor Apple(int p) { price = p; } int getPrice() { return price; } }

  13. class EnumDemo3 { public static void main(String args[]) { Apple ap; // Display price of Winesap. System.out.println("Winesap costs " + Apple.Winesap.getPrice() + " cents.\n"); } }

  14. Output: Winesap costs 15 cents.

  15. Enumerations Inherit Enum • All enumerations automatically inherit java.lang.Enum. • This class defines several methods that are available for use by all enumerations. • ordinal( ), compareTo( ), equals( ).

  16. final int ordinal( ) - It returns the ordinal value of the invoking constant. i.e; position of enumeration constant in the list. • final int compareTo(enum-type e) - Compares the ordinal value of two constants. • equals( ) - Compares two enumeration constant. If they are equal it returns true.

  17. // Demonstrate ordinal(), compareTo() and equals(). // An enumeration of apple varieties. enum Apple { Jonathan, GoldenDel, RedDel, Winesap, Cortland } class EnumDemo4 { public static void main(String args[]) { Apple ap, ap2, ap3;

  18. // Obtain all ordinal values using ordinal(). System.out.println(“Apple constants" + " and their ordinal values: "); for(Apple a : Apple.values()) System.out.println(a + " " + a.ordinal()); ap = Apple.RedDel; ap2 = Apple.GoldenDel; ap3 = Apple.RedDel; System.out.println();

  19. // Demonstrate compareTo() and equals() if(ap.compareTo(ap2) < 0) System.out.println(ap + " comes before " + ap2); if(ap.equals(ap3)) System.out.println(ap + " equals " + ap3); if(ap.equals(ap2)) System.out.println("Error!"); } }

  20. Output: Apple constants and their ordinal values: Jonathan 0 GoldenDel 1 RedDel 2 Winesap 3 Cortland 4 GoldenDel comes before RedDel RedDel equals RedDel

  21. Autoboxing • Two important features: autoboxing and auto- unboxing. • Autoboxing is the process by which a primitive type is automatically encapsulated (boxed) into its equivalent type wrapper whenever an object of that type is needed. • Auto-unboxing is the process by which the value of a boxed object is automatically extracted (unboxed) from a type wrapper when its value is needed.

  22. In autoboxing its not necessary to manually construct an object to wrap a primitive type. • We need to only assign that value to a type-wrapper reference. • Eg: To construct an Integer object that has the value 100: Integer iOb = 100; // autobox an int

  23. To unbox an object, simply assign that object reference to a primitive-type variable. Eg: To unbox iOb int i = iOb; // auto-unbox

  24. // Demonstrate autoboxing/unboxing. class AutoBox { public static void main(String args[ ]) { Integer iOb = 100; // autobox an int int i = iOb; // auto-unbox System.out.println(i + " " + iOb); } } Output: 100 100

  25. Autoboxing and Methods • Autoboxing automatically occurs whenever a primitive type must be converted into an object. • Auto-unboxing takes place whenever an object must be converted into a primitive type. • Autoboxing/unboxing might occur when an argument is passed to a method, or when a value is returned by a method.

  26. class AutoBox2 { // Take an Integer parameter and return an int value static int m(Integer v) { return v ; // auto-unbox to int } public static void main(String args[]) { Integer iOb = m(100); System.out.println(iOb); } }

  27. Autoboxing/Unboxing Occurs in Expressions Eg: Integer iOb, iOb2; int i; iOb = 100; iOb2 = iOb + (iOb / 3);//autobox i = iOb + (iOb / 3);//unbox

  28. Auto-unboxing also allows to mix different types of numeric objects: Eg: Integer iOb = 100; Double dOb = 98.6; dOb = dOb + iOb;

  29. Autoboxing/Unboxing Boolean and Character Values Eg: Boolean b = true;//autobox if(b) //unbox System.out.println("b is true"); Eg: Autobox/unbox a char. Character ch = 'x'; // box a char char ch2 = ch; // unbox a char

  30. Generics

  31. It is possible to create classes, interfaces, and methods that will work with various kinds of data. Eg: Collections Framework. • Generics means parameterized types.

  32. Using generics, it is possible to create a single class, that automatically works with different types of data. • A class, interface, or method that operates on a parameterized type is called generic.

  33. A Simple Generics Example // A simple generic class. // Here, T is a type parameter that // will be replaced by a real type // when an object of type Gen is created. class Gen<T> { T ob; // declare an object of type T // Pass the constructor a reference to // an object of type T. Gen(T o) { ob = o; }

  34. // Return ob. T getob() { return ob; } // Show type of T. void showType() { System.out.println("Type of T is " + ob.getClass().getName()); } }

  35. // Demonstrate the generic class. class GenDemo { public static void main(String args[]) { // Create a Gen reference for Integers. Gen<Integer> iOb; // Create a Gen<Integer> object and assign its // reference to iOb. Notice the use of autoboxing // to encapsulate the value 88 within an Integer object. iOb = new Gen<Integer>(88); // Show the type of data used by iOb. iOb.showType();

  36. // Get the value in iOb. Notice that // no cast is needed. int v = iOb.getob(); System.out.println("value: " + v); System.out.println(); // Create a Gen object for Strings. Gen<String> strOb = new Gen<String>("Generics Test"); // Show the type of data used by strOb. strOb.showType();

  37. // Get the value of strOb. Again, notice // that no cast is needed. String str = strOb.getob(); System.out.println("value: " + str); } }

  38. Output: Type of T is java.lang.Integer value: 88 Type of T is java.lang.String value: Generics Test

  39. A Generic Class with Two Type Parameters • We can declare more than one type parameter in a generic type. • To specify two or more type parameters, simply use a comma-separated list.

  40. // A simple generic class with two type // parameters: T and V. class TwoGen<T, V> { T ob1; V ob2; // Pass the constructor a reference to // an object of type T and an object of type V. TwoGen(T o1, V o2) { ob1 = o1; ob2 = o2; }

  41. // Show types of T and V. void showTypes() { System.out.println("Type of T is " + ob1.getClass().getName()); System.out.println("Type of V is " + ob2.getClass().getName()); } T getob1() { return ob1; } V getob2() { return ob2; } }

  42. // Demonstrate TwoGen. class SimpGen { public static void main(String args[]) { TwoGen<Integer, String> tgObj = new TwoGen<Integer, String>(88, "Generics"); // Show the types. tgObj.showTypes(); // Obtain and show values. int v = tgObj.getob1(); System.out.println("value: " + v); String str = tgObj.getob2(); System.out.println("value: " + str); } }

  43. Output: Type of T is java.lang.Integer Type of V is java.lang.String value: 88 value: Generics

  44. The General Form of a Generic Class • The syntax for declaring a generic class: class class-name<type-param-list> { // ... • The syntax for declaring a reference to a generic class: class-name<type-arg-list> var-name = new class-name<type-arg-list>(cons-arg-list);

  45. String Handling

  46. String is a sequence of characters. • Java implements strings as objects of type String. • When we create a String object, we are creating a string that cannot be changed. • i.e; once a String object has been created, we cannot change the characters of the string.

  47. Still we can perform all types of string operations. • Each time if we need an altered version of an existing string, a new String object is created. • The original string is left unchanged.

  48. In cases where modifiable string is desired Java provides two options: StringBufferand StringBuilder. • Both hold strings that can be modified after they are created. • The String, StringBuffer, and StringBuilder classes are defined in java.lang.

  49. The String Constructors • The String class supports several constructors. • To create an empty String, call the default constructor. Eg: String s = new String(); • It wil create an instance of String with no characters in it.

  50. To create strings that have initial values. String(char chars[ ]) Eg: char chars[] = { 'a', 'b', 'c' }; String s = new String(chars);

More Related