• Save
Jdk1.5 Features
Upcoming SlideShare
Loading in...5

Jdk1.5 Features



Detail description of JDK1.5

Detail description of JDK1.5



Total Views
Views on SlideShare
Embed Views



2 Embeds 44

http://chennaitechblog.wordpress.com 42
https://chennaitechblog.wordpress.com 2



Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
  • To download above ppt https://chennaitechblog.wordpress.com/2013/05/20/jdk5-0/
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

Jdk1.5 Features Jdk1.5 Features Presentation Transcript

  • Can these new and complex features simplify Java development?
  • New class addtion ?java.lang.StringBuilderjava.lang.Formatterjava.util.Queuejava.util.concurrent.*
  • Covariant ReturnTypes?Prior to JDK 1.5, a subclass could not override amethod using a different return typeIn JDK 1.5, a method can be overridden with adifferent return type as long as the new returntype extends the originalA return type that differs from that of themethod it is overriding is called a “covariantreturn”
  • Covariant Returns (con..)Prior to JDK1.5package com;public class CovarientParent{String str="";public CovarientParent(String str){str=this.str;}public CovarientParent getInstance(){return new CovarientParent("I amCovarientParent");}}Extended classpackage com;public class CovarientExample extendsCovarientParent{public CovarientExample(String str){super(str);}// Compiler error:The return type is incompatiblewith CovarientParent.getInstance()public CovarientExample getInstance()CovarientExample.javaJavaCollection{return new CovarientExample(" I mCovarientExample");}
  • Covariant Returns in JDK1.5 (cont)package com;public class CovarientParent{String str="";public CovarientParent(String str){str=this.str;}public CovarientParent getInstance(){return new CovarientParent("I amCovarientParent");}}Extended classpackage com;public class CovarientExample extendsCovarientParent{public CovarientExample(String str){super(str);}// No more compile time error// Compiler error:The return type isincompatible withCovarientParent.getInstance()public CovarientExample getInstance()CovarientExample.javaJavaCollection{return new CovarientExample(" I mCovarientExample");}
  • Enhanced for loop (foreach)Improves readabilityReduces boilerplate codeWorks with both arrays and objects thatexpose an iteratorThe enhanced for loop eliminates the need to usejava.util.Iterator to iterate over a collection.
  • Enhanced for loop (foreach)(cont) Before 1.5Void cancelAll(Collection c){for (Iterator i = c.iterator();i.hasNext(); )i.next().cancel();} JDK 1.5void cancelAll(Collection c){for (TimerTask t : c)t.cancel();}
  • Enhanced for loop (foreach)(cont) More examplefor (Suit suit : suits)for (Rank rank : ranks)sortedDeck.add(newCard(suit, rank)); Array loopingint sum(int[] a){int result = 0;for (int i : a)result += i;return result;}
  • Autoboxing/unboxingConversions between primitives and their equivalent wrappertypes are now automatic.Box primitive values into the appropriate wrapper class (whichis Integer in the case of int).When you take the object out of the collection,You get theInteger that you put in; if you need an int, you must unbox theInteger using the intValue method
  • Autoboxing/unboxing(cont) Before jdk1.5public class autoBoxing{ArrayList temp = new ArrayList();public void addArrayList(int value){// compiler error//The method add(int, Object) inthe //type ArrayList is notapplicable //for the arguments(int)temp.add(value);}} After JDK1.5public class autoBoxing{ArrayList temp = new ArrayList();public void addArrayList(int value){// compiler error//The method add(int, Object) in the //typeArrayList is not applicable//for the arguments (int)temp.add(value); // autoboxed}}
  • Autoboxing/unboxing(cont)More examplesAutoboxing supports Boolean typesas well.Boolean value1 = true;Boolean value2 = false;Boolean result = (value1 && value2);//result is falseAutoboxing /unboxing example.List ints = new ArrayList();ints.add( 1 ); // auto-boxing to newInteger( 1 )ints.add( 2 );ints.add( 3 );for ( int num : ints )// Auto-unboxing using obj.intValue()System.out.println( num );
  • What is Generics?Accepts “parameterized types” (parameters that acceptdata types)Improves type safetyAllows for compile time type checking. So Genericsimprove reflection alsoEliminates manual type-checking and type-castingE is a “type parameter” for ArrayList.The name “E” isarbitrary. It simply serves as a placeholder that canbe replaced with any Java class type.The compiler replaces every occurrence of E in themethods with the type that you specify when the ArrayListis created. Class ArrayList<E>boolean add(E e)E get(int index)
  • Generics (cont) Before jdk1.5// Removes 4-letter words from c.// Elements must be stringsstatic void expurgate(Collection c)for (Iterator i = c.iterator();i.hasNext(); )if (((String) i.next()).length() == 4)i.remove();} After jdk1.5// Removes the 4-letter words from cstatic void expurgate(Collection<String> c){for (Iterator<String> i = c.iterator(); i.hasNext(); )if (i.next().length() == 4)i.remove();} Type arguments can be specified when an object is declared/created. If an ArrayList is created using a type argument of “String”,the compiler enforces that the list can contain only String objects. Eliminates manual type-checking and type-casting
  • Generic Types (cont)interface Collection <E>{boolean add(E o);boolean addAll(Collection<? extends E> c);Iterator<E> iterator();<T>T[] toArray(T[] a);…}
  • Generic Interface (or Class) (cont)interface Collection <E> …Collection<Integer> integers;E is the type parameter for the generic typeCollection is the raw type after type erasureInteger is the actual type parameter used whendeclaring an instance of the generic typeCannot use primitive types but auto-boxing coversover the difference
  • Generic using the type parameters (cont)boolean add(E o);Where ever E is used, the compiler will check the type against theactual type parameter. At runtime E will be Object.Ex:(auto boxing with generics)List <Integer> temp= new ArrayList<Integer>()temp.add(1) // auto boxingtemp.add(“mani”) // compile time error
  • Generics Wildcard Parameters (cont)boolean addAll(Collection<?extends E> c);? represents an unknown typeList<?> list = newArrayList<String>();Not legal:List<Object> list = newArrayList<String>();Would allow list.add( newObject() );The JDK 1.5 compiler will issue“unchecked” type safetywarnings whenever a non-parameterized collection isused.To suppress warningswhen parameterization is notrequired, method parameterscan be declared using the “?”wildcard. For instance, thismethod accepts a list of anytype.void printList(List<?> list)
  • Generics bounded type parameters (cont)boolean addAll(Collection<? extends E> c);Constrains possible actual typesAn actual type must be same as Eor extend EGeneric types can be specify a rangeof types using the “extends”keyword. For instance, List<?extends Number> declares a Listthat only contains types thatextend Number (or Number itself).void printNumberList(List<? extendsNumber>)
  • Generics java doc paramers (cont)JDK 1.5’s Javadocs use type parameters named E,K, V, and T. These values stand for element, key,value, and type, respectively.The generic version of HashMap allows you todeclare a type for both key and value.Class HashMap<K,V>boolean put(K key, V value);<T> T[] toArray(T[] a); Infers the actual type from the actual parameterpassed to the method.
  • Generics implementation(cont)Type parameterization is implemented through aprocess called “erasure”. Erasure removes all typeinformation as the code is compiled.The compiler automatically adds any required typecasts to the bytecode.Since it occurs at runtime, type parameterizationdoes not effect code executed through reflection.
  • Why enum?// int Enum Pattern - has severe problems!public static final int SEASON_WINTER = 0;public static final int SEASON_SPRING = 1;public static final int SEASON_SUMMER = 2;public static final int SEASON_FALL = 3;This pattern has many problems, such as:Not typesafe - Since a season is just an int you can pass in any other int valuewhere a season is required, or add two seasons together (which makes no sense).No namespace -You must prefix constants of an int enum with a string (in thiscase SEASON_) to avoid collisions with other int enum types.Brittleness - Because int enums are compile-time constants, they are compiledinto clients that use them. If a new constant is added between two existingconstants or the order is changed, clients must be recompiled. If they are not,they will still run, but their behavior will be undefined.Printed values are uninformative - Because they are just ints, if you print oneout all you get is a number, which tells you nothing about what it represents, oreven what type it is.
  • Enumeraton (cont)The new enum data type allows the developer torestrict valid values to a specified set.The compiler enforces valid values.public enum CardSuit {HEARTS, DIAMONDS, CLUBS, SPADES};public setSuit(CardSuit suit) //method that accepts enum{ … }setSuit(CardSuit.CLUBS);
  • Ennumeration (cont)All enum types extend java.lang.Enum.enum types are classes not integers.This guaranteestype safety.enum types cannot be extended.enum values are public, static, and final.enum values can be compared with == or equals().
  • Ennumeration (cont)You can switch on enumerated types.When switching, there is no need to preface the enumvalues with the enum class name (in fact, the compiler doesnot allow it).switch (card.getSuit()){case HEARTS:System.out.println(“Hearts”);break;case DIAMONDS:System.out.println(“Diamonds”);break;// and so on}
  • Ennumeration (cont)Since they are classes, you can add constructors and methods to enum types.(Grades.A.getAssessment() returns “Excellent!”)public enum Grades {A(1), B(2), C(2), D(3), F(3); //integer values are passed to constructorprivate String assessment;Grades(int value) {switch (value) {case 1: assessment = “Excellent!”; break;case 2: assessment = “Not bad.”; break;case 3: assessment = “Needs improvement!”; break;}}public String getAssessment() {return assessment;}}
  • What is Variable arguments or varargs?Variable arguments, or varargs, allow a method toaccept any number of arguments.printNumberList(“Numbers”, 1, 2, 3); //method callvoid printNumberList(String header, int... list){System.out.println(header);for (int item : list){System.out.println(item);}
  • Variable arguments or varargs(cont)Only one vararg parameter is allowed per method.The vararg must be the last parameter.The vararg parameter is implemented as an array.Therefore, the compiler sees these methodsdeclarations as equivalent:Ex:void printNumberList(String header, int[] list);void printNumberList(String header, int... list);
  • Variable arguments or varargs(cont)Since the compiler implements variable arguments usingarrays, the vararg can be treated as an array.void printList(String header, int... list){System.out.println(header);for (int i = 0; i < list.length; i++){System.out.println(list[i]);}}
  • What is Static Imports?Static imports allow static classes to be imported.import static java.lang.System.out;public class StaticImportTest{public static void main(String[] args){out.println("Hello, world!");}}
  • Static Imports (cont)Static imports also allow the import of static methodsand variables.import static java.util.Arrays.sort; //import sort methodimport static java.lang.Math.*; //import static memberspublic class StaticImportTest{public static void main(String[] args){int[] numbers = {3, 6, 1, 4, 5, 2};sort(numbers); //sort is method in Arrays classdouble d = abs(-15); //abs is method in Mathclass}}
  • What are new Annotations(Meta-data)?Annotations provideadditional information aboutthe code to the compiler orruntime environment.Annotations are included inthe source code prefaced bythe “@” symbol.JDK 1.5 includes threestandard annotation types:@SuppressWarnings@Override and @DeprecatedThe @SuppressWarningsannotation turns off specifiedcompiler warnings.Defines a single parameter calledvalue.@SuppressWarnings(value=“unchecked”)public void nonGenericMethod()//these formats are also supported@SuppressWarnings(“unchecked”)@SuppressWarnings(value={“unchecked”, “fallthrough”})
  • Annotation(cont)The @Override annotationindicates that a method is intendedto override a parent method.If the method does not override aparent method (names/signaturesdo not match), the compiler issuesan error.@Overridepublic String toString(){// implementationThe @Deprecated annotationindicates that a method has beendeprecated.Works in conjunction with the@deprecated JavaDoc tag thatadds instruction on whichmethod to use instead.Classes that call a deprecatedmethod will receive a warning atcompile time.@Deprecatedpublic void MyDeprecatedMethod()
  • Formatted OutputEven though Java offers the excellent java.textpackage classes and methods for Formatting ofdata, people with C backgrounds still miss "printf"and its functionalityJava 5 added java.util.Formatter with newcapabilities to all of Javas output methodsFormatting may be applied using the locale andmay be directed to a "sink" (often a file)PrintStreamclass includes methods for "format()"and "printf()" using the same formattingcharacters; "format()" and "printf()" methods aresynonymous
  • Formatted Output (Cont) Here is an example of a numeric value being formatted using System.out.format()--System.out.printf() works identically:double balance = 1234.56;System.out.format("Balance is$ %,6.2f",balance);Output:Balance is $1,234.56 Here is an example of a date being formattedDate today = new Date();System.out.format("nToday is %TF %TT", today,today);Output:Today is 2005-06-09 20:15:26
  • Scanner Input (cont)Java programs commonly use useSystem.in and its"readLine()" method to access the keyboard(requiring that IOExceptionbe handled)Java 5 introduced the java.util.Scanner classdesigned specifically to reduce the amount of codeneeded to communicate with the keyboard
  • Scanner Input (cont)Before jdk1.5String firstName;InputStreamReaderinStream= newInputStreamReader(System.in);BufferedReaderinBuf= newBufferedReader(inStream);System.out.print("Please enter yourfirst name => ");try {firstName= inBuf.readLine();} // end of first try blockcatch (IOException e) {System.out.println("Problem readingfirst name");return;} // end catch blockAfter jdk1.5String lastName;System.out.print("Please enter your last name=> ");Scanner fromkeyboard= newScanner(System.in);llastName= fromkeyboard.next();
  • Scanner Input (cont)next()returns the next input buffer Stringtoken•next(comparePattern)Or next(compareString)uses patterns to return values•Numeric variations include:–nextBigDecimal()–nextBigInteger()–nextBoolean()–nextByte()–nextDouble()–nextFloat()–nextInt()–nextLine()–nextLong()–nextShort()
  • Concurrency UtilitiesBeginning with Java 5 (Java 1.5) thejava.util.concurrent.locks, java.util.concurrent, andjava.util.concurrent.atomicpackages are availableproviding better locking support than provided bythe "synchronized" modifier.All existing code still works as beforeThe java.util.concurrent.xxx packages includeinterfaces and classes used to simplifysynchronization and locking
  • Concurrency Utilities(cont)The java.util.concurrent.locks.Lockinterface hasseveral methods including:–lock() to obtain a lock (blocks if can’t get lock)–unlock() to release a lock–lockInterruptibility() gets lock, allows interruptions–tryLock() attempts to obtain a lock without a wait.The java.util.concurrent.locks.ReentrantLockclassbehaves like using synchronized does todayThe java.util.concurrent.locks.Conditioninterfaceallows complex and multiple conditional waitsThejava.util.concurrent.locks.ReadWriteLockinterfaceallows separate read/write locks
  • What is Class data sharing? Class data sharing (called CDS by Sun) is a mechanism which reducesthe startup time for Java applications, and also reduces memoryfootprint. When the JRE is installed, the installer loads a set of classesfrom the system jar file (the jar file containing all the Java class library,called rt.jar) into a private internal representation, and dumps thatrepresentation to a file, called a "shared archive". During subsequent JVM invocations, this shared archive is memory-mapped in, saving the cost of loading those classes and allowing muchof the JVMs Metadata for these classes to be shared amongmultiple JVM processes.The corresponding improvement for start-uptime is more noticeable for small programs.
  • What is StringBuilder ? New with Java 5, java.lang.StringBuilderclass provides a fasteralternative to StringBuffer In most ways StringBuilderworks exactly the same asStringBuffer StringBuilderis faster than StringBufferbecause it is notThreadSafe(multiple threads should not accessStringBuilderobjects without Synchronizing) Use StringBuilderwhen speed is important in a single-threadenvironment and use StringBufferif multiple threads mightrequire access.
  • StringBuilder Example (cont)String myString= "How";StringBuilder myStrBldr= new StringBuilder("How");myString+= " now";myString+= " Brown";myString+= " Cow?";myStrBldr.append(" now");myStrBldr.append(" Brown");myStrBldr.append(“Cow?");System.out.println("String= " +myString);System.out.println("StringBuilder= " + myStrBldr);
  • Changes in the arrayjava.util.Arrays.toString()java.util.Arraysclass has new methods including atoString() method to print the contents of anyarray/collectionint[] anArray= { 1, 3, 5, 7, 9, 11, 13, 15, 16, 20 };System.out.println(Arrays.toString(anArray));Generates the following output:[1, 3, 5, 7, 9, 11, 13, 15, 16, 20]
  • Changes in the array(cont)Arrays.deepToString()displays the contents of a multi-dimensional array:int[][] apartment = new int[5][4];The results of using Arrays.toString() andArrays.deepToString() are illustrated below. –First, using Arrays.toString() the contents of the first levelshow as addresses (Windows PC used for example):[[I@10b62c9, [I@82ba41, [I@923e30, [I@130c19b,[I@1f6a7b9]–Next, using Arrays.deepToString() the contents of the arrayare listed:[[0, 0, 0, 0], [0, 1, 2, 3], [0, 4, 5, 6], [0, 7, 8, 9], [0,10, 11, 12]]
  • ?