can these new and complex features simplify java development?

Post on 09-Jan-2016

31 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

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 Return Types?. Prior to JDK 1.5, a subclass could not override a method using a different return type - PowerPoint PPT 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 Return Types?

Prior to JDK 1.5, a subclass could not override a method using a different return typeIn JDK 1.5, a method can be overridden with a different return type as long as the new return type extends the originalA return type that differs from that of the method it is overriding is called a “covariant return”

Covariant Returns (con..)

Prior to JDK1.5

package com;public class CovarientParent { String str="";

public CovarientParent(String str){

str=this.str;}

public CovarientParent getInstance(){return new CovarientParent("I am CovarientParent");}

}

Extended class

package com;public class CovarientExample extends

CovarientParent {public CovarientExample(String str){super(str);} // Compiler error: The return type is

incompatible with CovarientParent.getInstance()

public CovarientExample getInstance() CovarientExample.javaJavaCollection

{return new CovarientExample(" I m

CovarientExample");}

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 am

CovarientParent");}}

Extended class

package com;public class CovarientExample extends

CovarientParent {public CovarientExample(String str){super(str);}

// No more compile time error // Compiler error: The return type is

incompatible with CovarientParent.getInstance()

public CovarientExample getInstance() CovarientExample.javaJavaCollection

{return new CovarientExample(" I m

CovarientExample");}

Enhanced for loop (foreach) Improves readability

Reduces boilerplate code

Works with both arrays and objects

that

expose an iterator The enhanced for loop eliminates the need

to use java.util.Iterator to iterate over a

collection.

Enhanced for loop (foreach)(cont)

Before 1.5

Void cancelAll(Collection c){ for (Iterator i = c.iterator(); i.hasNext(); ) i.next().cancel();}

JDK 1.5

void cancelAll(Collection c) { for (TimerTask t : c) t.cancel();}

Enhanced for loop (foreach)(cont)

More example

for (Suit suit : suits)for (Rank rank : ranks)sortedDeck.add(new

Card(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 wrapper types are now automatic.

Box primitive values into the appropriate wrapper

class (which is Integer in the case of int).

When you take the object out of the collection, You

get the Integer that you put in; if you need an int,

you must unbox the Integer using the intValue

method

Autoboxing/unboxing(cont)

Before jdk1.5

public class autoBoxing {ArrayList temp = new ArrayList();

public void addArrayList(int value){// compiler error//The method add(int, Object) in

the //type ArrayList is not applicable //for the arguments (int)

temp.add(value);}

}

After JDK1.5

public class autoBoxing {ArrayList temp = new ArrayList();

public void addArrayList(int value){// compiler error//The method add(int, Object) in the //type

ArrayList is not applicable //for the arguments (int)temp.add(value); // autoboxed }}

Autoboxing/unboxing(cont)

More examples

Autoboxing supports Boolean types as well.

Boolean value1 = true;Boolean value2 = false;Boolean result = (value1 && value2);

//result is false

Autoboxing /unboxing example.

List ints = new ArrayList();ints.add( 1 ); // auto-boxing to new

Integer( 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 accept data types) Improves type safety Allows for compile time type checking. So Generics improve reflection also Eliminates manual type-checking and type-casting E is a “type parameter” for ArrayList. The name “E” is arbitrary. It simply serves as a placeholder that can be replaced with any Java class type. The compiler replaces every occurrence of E in the methods with the type that you specify when the ArrayList is 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 strings

static 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 typeCollection is the raw type after type erasureInteger is the actual type parameter used when declaring an instance of the generic typeCannot use primitive types but auto-boxing covers over the difference

Generic using the type parameters (cont)

boolean add(E o);

Where ever E is used, the compiler will check the type against the actual type parameter. At runtime E will be Object.

Ex:(auto boxing with generics)List <Integer> temp= new ArrayList<Integer>()temp.add(1) // auto boxing temp.add(“mani”) // compile time error

Generics Wildcard Parameters (cont)

boolean addAll(Collection<? extends E> c);

? represents an unknown typeList<?> list = new

ArrayList<String>();

Not legal:List<Object> list = new

ArrayList<String>();Would allow list.add( new

Object() );

The JDK 1.5 compiler will issue “unchecked” type safety warnings whenever a non-parameterized collection is used. To suppress warnings when parameterization is not required, method parameters can be declared using the “?” wildcard. For instance, this method accepts a list of any type.

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 E

or extend E

Generic types can be specify a range of types using the “extends” keyword. For instance, List<? extends Number> declares a List that only contains types that extend Number (or Number itself).

void printNumberList(List<? extends Number>)

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 to declare 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 parameter passed to the method.

Generics implementation(cont)

Type parameterization is implemented through a process called “erasure”. Erasure removes all type information as the code is compiled.

The compiler automatically adds any required type casts to the bytecode.

Since it occurs at runtime, type parameterization does 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 value where 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 this case SEASON_) to avoid collisions with other int enum types. Brittleness - Because int enums are compile-time constants, they are compiled into clients that use them. If a new constant is added between two existing constants 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 one out all you get is a number, which tells you nothing about what it represents, or even what type it is.

Enumeraton (cont) The new enum data type allows the developer to restrict 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

guarantees type 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 enum values with the enum class name (in fact, the compiler does not 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 constructor

private 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 to accept any number of arguments.

printNumberList(“Numbers”, 1, 2, 3); //method call

void 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 methods declarations 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 using arrays, 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 methods and variables.

import static java.util.Arrays.sort; //import sort methodimport static java.lang.Math.*; //import static members

public 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 Math class

}}

What are new Annotations(Meta-data)?Annotations provide additional information about the code to the compiler or runtime environment.Annotations are included in the source code prefaced by the “@” symbol.

JDK 1.5 includes three standard annotation types: @SuppressWarnings@Override and @Deprecated

The @SuppressWarnings annotation turns off specified compiler warnings.

Defines a single parameter called value.

@SuppressWarnings(value=“unchecked”)

public void nonGenericMethod()

//these formats are also supported@SuppressWarnings(“unchecked”)@SuppressWarnings(value={“unchecked

”, “fallthrough”})

Annotation(cont)

The @Override annotation indicates that a method is intended to override a parent method. If the method does not override a parent method (names/signatures do not match), the compiler issues an error.

@Overridepublic String toString(){

// implementation

The @Deprecated annotation indicates that a method has been deprecated.

Works in conjunction with the @deprecated JavaDoc tag that adds instruction on which method to use instead.

Classes that call a deprecated method will receive a warning at compile time.

@Deprecated public void MyDeprecatedMethod()

Formatted OutputEven though Java offers the excellent java.text

package classes and methods for Formatting of data, people with C backgrounds still miss "printf" and its functionality

Java 5 added java.util.Formatter with new capabilities to all of Java's output methods

Formatting may be applied using the locale and may be directed to a "sink" (often a file)

PrintStreamclass includes methods for "format()" and "printf()" using the same formatting characters; "format()" and "printf()" methods are synonymous

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 formatted

Date 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 class designed specifically to reduce the amount of code needed to communicate with the keyboard

Scanner Input (cont)

Before jdk1.5

String firstName;InputStreamReaderinStream=

new InputStreamReader(System.in);

BufferedReaderinBuf= new BufferedReader(inStream);

System.out.print("Please enter your first name => ");

try {firstName= inBuf.readLine();} // end of first try blockcatch (IOException e) {System.out.println("Problem

reading first name");return;} // end catch block

After jdk1.5

String lastName;

System.out.print("Please enter your last name => ");

Scanner fromkeyboard= new Scanner(System.in);l

lastName= fromkeyboard.next();

Scanner Input (cont)

next() returns the next input buffer

String token•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) the java.util.concurrent.locks, java.util.concurrent, and java.util.concurrent.atomicpackages are available providing better locking support than provided by the "synchronized" modifier.

All existing code still works as before

The java.util.concurrent.xxx packages include interfaces and classes used to simplify synchronization and locking

Concurrency Utilities(cont)

The java.util.concurrent.locks.Lockinterface has several 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.ReentrantLockclass

behaves like using synchronized does today The java.util.concurrent.locks.Conditioninterface

allows complex and multiple conditional waits The

java.util.concurrent.locks.ReadWriteLockinterface allows separate read/write locks

What is Class data sharing?

Class data sharing (called CDS by Sun) is a mechanism which reduces the startup time for Java applications, and also reduces memory footprint. When the JRE is installed, the installer loads a set of classes from the system jar file (the jar file containing all the Java class library, called rt.jar) into a private internal representation, and dumps that representation 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 much of the JVM's Metadata for these classes to be shared among multiple JVM processes.The corresponding improvement for start-up time is more noticeable for small programs.

What is StringBuilder ? New with Java 5, java.lang.StringBuilderclass provides a faster

alternative to StringBuffer

In most ways StringBuilderworks exactly the same as StringBuffer

StringBuilderis faster than StringBufferbecause it is not ThreadSafe(multiple threads should not access StringBuilderobjects without Synchronizing)

Use StringBuilderwhen speed is important in a single-thread environment and use StringBufferif multiple threads might require 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 a toString() method to print the contents of any array/collection

int[] 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() and

Arrays.deepToString() are illustrated below. –First, using Arrays.toString() the contents of

the first level show 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 array are listed:[[0, 0, 0, 0], [0, 1, 2, 3], [0, 4, 5, 6], [0, 7, 8, 9], [0, 10, 11, 12]]

?

top related