DOC PREVIEW
UMD CMSC 132 - Java 1.5 & Effective Java

This preview shows page 1-2-21-22 out of 22 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 22 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 22 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 22 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 22 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 22 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

Java 1.5 & Effective JavaJava 1.5 (Tiger)New Features in Java 1.5Generics – Motivating ExampleGeneric TypesGenerics – UsageScannerAutoboxing & UnboxingEnhanced For LoopVariable # of Arguments (Varargs)Enumerated TypesStatic ImportAnnotationsEffective JavaEffective Java – TopicsCreating and Destroying ObjectsMethods Common to All ObjectsClasses and InterfacesMethodsGeneral ProgrammingExceptionsThreadsJava 1.5 & Effective JavaFawzi EmadChau-Wen TsengDepartment of Computer ScienceUniversity of Maryland, College ParkJava 1.5 (Tiger)DescriptionReleased September 2004Largest revision to Java so farGoalsLess code complexityBetter readabilityMore compile-time type safetySome new functionality (generics, scanner)New Features in Java 1.5Generic typesScanner Autoboxing & unboxingEnhanced for loop Variable number of arguments (varargs)Enumerated types Static importsAnnotationsGenerics – Motivating ExampleProblemUtility classes handle arguments as Objects Objects must be cast back to actual classCasting can only be checked at runtimeExampleclass A { … }class B { … } List myL = new List();myL.add(new A()); // Add an object of type A…B b = (B) myL.get(0); // throws runtime exception// java.lang.ClassCastExceptionGeneric TypesParameterized types with <type parameter>Parameterize classes, interfaces, methods by typesParameters defined using <x> notationParameters replaced at compile time with castsProvide compile-time type safetySupport in java.utilExamplepublic class foo<x, y, z> { … }public class List<String> { … }Generics – UsageUsing generic typesSpecify <type parameter> for utility classAutomatically performs castsCan check class at compile timeExampleclass A { … }class B { … } List<A> myL = new List<A>();myL.add(new A()); // Add an object of type AA a = myL.get(0); // myL element  class A…B b = (B) myL.get(0); // causes compile time errorScannerIterator for Provides methods for input & parsingSupports String nextLine(), int nextInt()…Throws InputMismatchException if wrong formatExample// old approach to scanning inputBufferedReader br = new BufferedReader( new InputStreamReader(System.in)); String name = br.readLine();// new approach using scannerScanner in = new Scanner(System.in);String name = in.nextLine();Autoboxing & UnboxingAutomatically convert primitive data typesData value  Object (of matching class)Data types & classes convertedBoolean, Byte, Double, Short, Integer, Long, FloatExampleArrayList myL = new ArrayList();myL.add(1); // previously myL.add(new Integer(1));Integer X = new Integer(2);int y = X; // previously int y = X.intValue();Enhanced For LoopFor loop handles Iterator automaticallyTest hasNext(), then get & cast next()ExampleIterator it = myL.iterator(); // old usage of Iteratorwhile (it.hasNext()) { Integer num = (Integer) it.next(); // do something with num...}for (Integer num : myL) { // new enhanced for loop // do something with num...}Variable # of Arguments (Varargs)Method allow variable # of arguments (vararg)Arguments automatically stored in arrayOnly single vararg allowed, must be last argumentExamplevoid foo(int x, String ... myL) { for (String str : myL) { // do something with str... }} foo( 1, “car”, “boat”); foo( 2, “car”, “boat”, “plane”);foo( 3, String [ ] x );Enumerated TypesNew type of variable with set of fixed valuesEstablishes all possible values by listing themSupports values(), valueOf(), name(), compareTo()…Examplepublic Class Color { // old approach to enumeration private int c; public static final Color Black = new Color(1); public static final Color White = new Color(2);}public enum Color { Black, White } // new enumerationColor myC = Color.Black;for (Color c : Color.values()) System.out.println(c);Static ImportImport static members of packageExample// imports static members of packageimport static java.lang.Math.ceil // imports all static members of packageimport static java.lang.Math.* double x, y;x = ceil(y); // can use method name directlyAnnotationsAdd annotations (metadata) using @Annotate types, methods, fields for documentation, code generation, runtime servicesProvides built-in & custom annotations@Target, @Overrides, @Documented… Can control availability of annotations Source code, class file, runtime in JVMExample/* @author CMSC132Coder */public final class AnnotationsTest { @Overrides public String toString(int i) { return “ x “ };}Effective JavaTitleEffective Java Programming Language GuideAuthorJoshua BlochContentsUseful tips for Java programmingEffective Java – Topics1. Creating and Destroying Objects2. Methods Common to All Objects3. Classes and Interfaces4. Substitutes for C Constructs5. Methods6. General Programming7. Exceptions8. Threads9. SerializationCreating and Destroying ObjectsConsider providing static factory methods instead of constructorsEnforce singleton property with a private constructorEnforce noninstantiability with a private constructorAvoid creating duplicate objectsEliminate obsolete object referencesAvoid finalizersMethods Common to All ObjectsObey the general contract when overriding equalsAlways override hashCode when you override equalsAlways override toStringOverride clone judiciouslyConsider implementing ComparableClasses and InterfacesMinimize the accessibility of classes and membersFavor immutabilityFavor composition over inheritanceDesign and document for inheritance or else prohibit itPrefer interfaces to abstract classesUse interfaces only to define typesFavor static member classes over nonstaticMethodsCheck parameters for validityMake defensive copies when neededDesign method signatures carefullyUse overloading judiciouslyReturn zero-length arrays, not nullsWrite doc comments for all exposed API elementsGeneral ProgrammingMinimize the scope of local variablesKnow and use the librariesAvoid float and double if exact answers are requiredAvoid strings where other types are more appropriateBeware the performance of string concatenationRefer to objects by their interfacesPrefer interfaces to reflectionUse native methods judiciouslyOptimize judiciouslyAdhere to generally accepted naming conventionsExceptionsUse exceptions only for exceptional conditionsUse checked exceptions for recoverable conditions and run-time exceptions for programming errorsAvoid unnecessary use of checked exceptionsFavor the use of standard exceptionsThrow exceptions appropriate to the abstractionDocument all exceptions


View Full Document

UMD CMSC 132 - Java 1.5 & Effective Java

Documents in this Course
Notes

Notes

8 pages

Recursion

Recursion

12 pages

Sorting

Sorting

31 pages

HTML

HTML

7 pages

Trees

Trees

19 pages

HTML

HTML

18 pages

Trees

Trees

19 pages

Honors

Honors

19 pages

Lecture 1

Lecture 1

11 pages

Quiz #3

Quiz #3

2 pages

Hashing

Hashing

21 pages

Load more
Download Java 1.5 & Effective Java
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Java 1.5 & Effective Java and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Java 1.5 & Effective Java 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?