Java 5 Part 2 CSE301 University of Sunderland Harry Erwin, PhD.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

New features in JDK 1.5 Can these new and complex features simplify Java development?
Language Fundamentals in brief C# - Introduction.
Written by: Dr. JJ Shepherd
1 ADT and Data Structure Example Generics / Parameterized Classes Using a Set Implementing a Set with an Array Example: SetADT interface Example: ArraySet.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
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,
Introduction to the C# Programming Language for the VB Programmer.
Java Generics.
Programming in Java CSE301 Half Lecture Harry Erwin, PhD University of Sunderland.
1 Java Object Model Part 1. 2 Type Definition: set of values – a set of values and set of operations –a set of operations that can be applied to those.
Java 1.5 & Effective Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
J2SE 5.0 New Features. J2SE 5.0 aka JDK 1.5 aka Tiger.
CSE373 Optional Section Java Collections 11/12/2013 Luyi Lu.
JavaServer Pages Syntax Harry Richard Erwin, PhD CSE301/CIT304.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
P Object type and wrapper classes p Object methods p Generic classes p Interfaces and iterators Generic Programming Data Structures and Other Objects Using.
FEN 2012 UCN Technology: Computer Science1 C# - Introduction Language Fundamentals in Brief.
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Effective Java: Generics Last Updated: Spring 2009.
Introduction to Java University of Sunderland CSE301 Harry R. Erwin, PhD.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
Basic Java Syntax CSE301 University of Sunderland Harry R Erwin, PhD.
1162 JDK 5.0 Features Christian Kemper Principal Architect Borland.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Vectors, Strings, and Enumeration Data Types.
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.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
CS 61B Data Structures and Programming Methodology July 3, 2008 David Sun.
Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators.
CompSci 100E 40.1 Java 5 New Features  Generics  Enhanced for loop  Autoboxing/unboxing  Typesafe enums  Other  Varargs  Static Import  Metadata.
Introduction to Java COM379 (Part-Time) University of Sunderland Harry R Erwin, PhD.
ISBN Chapter 6 Data Types Introduction Primitive Data Types User-Defined Ordinal Types.
Objects First With Java A Practical Introduction Using BlueJ Supplementary Material for Java
Introduction to Generics
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
An Advanced Code Pattern: Inner Classes CSE301 University of Sunderland Harry R. Erwin, PhD Half Lecture.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Recitation 5 Enums and The Java Collections classes/interfaces 1.
11-Jan-16 Bits and Pieces Some random things in Java.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Java Programming, Second Edition Chapter Twelve Advanced Inheritance Concepts.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
CS100Lecture 61 Announcements Homework P1 due on Thursday Homework P2 handed out.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
SCJP 5, 1/7 Declarations, Initialization and Scoping
Java Primer 1: Types, Classes and Operators
Generics, Lambdas, Reflections
Some random things in Java
Java Programming Language
Some random things in Java
More On Enumeration Types
Generics, Lambdas, Reflections
Some random things in Java
Presentation transcript:

Java 5 Part 2 CSE301 University of Sunderland Harry Erwin, PhD

Introduction Java 5 has been changed to improve the language. This lecture will discuss the changes. You will be tested on your knowledge of Java 5. References include: –McLaughlin and Flanagan, 2004, Java 1.5 Tiger: A Developer’s Notebook, O’Reilly –Flanagan, 2005, Java in a Nutshell, 5 th edition, O’Reilly

Topics Part 1 (Last Lecture) Arrays Queues Overriding return types Unicode StringBuilder Generics Part 2 (Today) Enumerated types Boxing Annotations for/in Static imports Formatting Threading

Enumerated types If you’ve worked with C++, you already know how enums can be used as integer types to avoid the need for ‘magic numbers’. In Java 1.4 and earlier, there were two ways to define new types: classes and interfaces. This did not cover some very specific programming needs. One such need was for a type that could have a very limited number of values. The new enumerated type or enum serves this need. (An enum is just a Java class.) Many potential questions throughout.

enum Syntax enum enumName {list of values}; –The value list names are all uppercase by convention. Comma-separated. See next slide for an example. Optional components: –interfaces that are implemented by the enum –variable definitions (an enum is a class) –method definitions (an enum is a class) –Value-specific class bodies

enum Syntax Example public enum Foo { BAR(0), BAZ(1), QUUX(42); //values come first Foo(int val){ // constructor (private by default) this.val = val; } private int val = 0; // internal variable public void quuux(long val2) {return;} public String getDescription(){ switch(this){ case BAR: return “BAR-0”; break; case BAZ: return “BAZ-1”; break; default: return “”+val+“?”; }

A Few Points An enum is a class, not a primitive type. Enums extend java.lang.Enum, which is not an enumerated type. Enumerated types are not integers. Enumerated types can’t have public constructors. Enumerated values are public, static, and final. Enumerated values support comparison by == and equals().

More Points Enums are comparable (have an order). Enums provide toString(), returning the name of the value. Enums provide a valueOf(String val) method to convert a String to a value. Recognises the names. Enums provide a final method named ordinal(), which is the integer position of the value in the list. Enums provide a values() method to support enumeration over the value list.

Inline Enums You can declare an enum type within your class rather than at the top level if it is associated with that class. To access it outside your class, make it visible (i.e., not private) and refer to it as YourClassName.EnumName

Iterating Over an Emun First, you use the values() method to get an array of the values in the type. Name[] nameValues = Name.values(); Then you can iterate in the normal way. Or, use the following syntax: for(Name n : Name.values()){ whatever you want to do with each name; } This is a variant of the new for/in syntax (qv).

Enum and Switch Do the following: switch(enumerated value){ case value1: …; case value2: …; … case lastvalue: …; default: …; } Java writes a jump-table to handle this.

Enum and Map The values of an enum are Objects and can serve as indices of a map! Suppose you have an enum called Foo, and corresponding values in some class called Bar, You can create an EnumMap around the two classes An easy way that stores a full list of the enum is: EnumMap theMap = EnumMap (Foo.class); Then all you need to do is initialise the values!

EnumSet This is used to represent combinations of features that can occur independently. First you define the enum enumName Then you create an enumSet to represent the features. There are a number of static member functions in EnumSet to do this.

EnumSet Static Member Functions allOf(Class elementType); complementOf(EnumSet e); copyOf(Collection c); noneOf(Class elementType); of(one to five elements of the enum); range(E from, E to); // avoid! If the enum changes, you’re hash! clone(); contains(E e); // to check whether e is present.

Boxing Instances of primitive types are not objects. To create an object for a primitive type value, you have to wrap it in the corresponding reference type—Boolean, Character, Integer, Float, etc. You must use reference types in Collections. This can be an utter pain. Java has added autoboxing and unboxing. Those features automagically handle this wrapping and unwrapping via typecasts. Don’t unbox null; you’ll get an exception! Also watch for problems with boolean expressions! Test questions.

varargs Advanced topic. Just be aware that you can write Java methods that take multiple arguments of the same type. The number of arguments need not be predetermined.

Annotations This is a standard way to annotate your code. There are three standard annotation types: just before a method definition indicates that it overrides a superclass method. just before a definition indicates that its use is discouraged of “warnings”}) indicates that the following code should have specific compiler warnings turned off You can also invent your own annotations and even annotate your annotations.

for/in Also known as the enhanced for. Gets rid of the need to use an Iterator and simplifies for loops. Syntax: for(Object obj : collection){ operate on obj; // pseudo-code } This also works with a generic collection with members that are of a given type. String concatenation doesn’t work well, though. Test questions.

for/in for Arrays Suppose anArray is of type T[], where T is a reference or primitive type. Then you can loop through it as follows: for(T t : anArray){ // t gets set to anArray[i] //for each i from 0 to the end of the array operate on t // again pseudo-code } Note the types must be compatible. The collection or array can be declared final (non-modifiable) for safety. Test questions.

Static imports This allows you to import a static class, variable, or enum and reference them with a simple name. import static java.lang.System.out; Now you can refer to out, rather than java.lang.System.out. Also works for static methods (see Arrays and Collections), member types, and enums. Wildcards (*) still work. Test questions.

Formatting Advanced topic. import java.util.Formatter; Allows you to use printf().

Threading Advanced topic covered in a later lecture. I won’t be testing your knowledge of Java 5 threading changes. On the other hand, if you need to use threads in your final year project or other modules, Chris Knowles or I will be happy to discuss this material off-line.