SlideShare ist ein Scribd-Unternehmen logo
1 von 46
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 a
method using a different return type

In JDK 1.5, a method can be overridden with a
different return type as long as the new return
type extends the original

A 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 looping
int 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 c
static 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 when
declaring an instance of the generic type
Cannot 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 type
List<?> 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 types
An 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 method
import 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 class
double 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.
@Override
public 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 Output
Even 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 block
catch (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]]
?

Weitere ähnliche Inhalte

Was ist angesagt?

Generic Programming seminar
Generic Programming seminarGeneric Programming seminar
Generic Programming seminar
Gautam Roy
 
Ap Power Point Chpt5
Ap Power Point Chpt5Ap Power Point Chpt5
Ap Power Point Chpt5
dplunkett
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
HCMUTE
 
C0 review core java1
C0 review core java1C0 review core java1
C0 review core java1
tam53pm1
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
dplunkett
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2
dplunkett
 

Was ist angesagt? (19)

Effective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All ObjectsEffective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All Objects
 
Evolution of c# - by K.Jegan
Evolution of c# - by K.JeganEvolution of c# - by K.Jegan
Evolution of c# - by K.Jegan
 
Generic Programming seminar
Generic Programming seminarGeneric Programming seminar
Generic Programming seminar
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
Net framework session01
Net framework session01Net framework session01
Net framework session01
 
OCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & StatementsOCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & Statements
 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programming
 
Ap Power Point Chpt5
Ap Power Point Chpt5Ap Power Point Chpt5
Ap Power Point Chpt5
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
M C6java3
M C6java3M C6java3
M C6java3
 
C0 review core java1
C0 review core java1C0 review core java1
C0 review core java1
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
 
C# language basics (Visual studio)
C# language basics (Visual studio)C# language basics (Visual studio)
C# language basics (Visual studio)
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ Comparator
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2
 
Lecture 8 Library classes
Lecture 8 Library classesLecture 8 Library classes
Lecture 8 Library classes
 
Md03 - part3
Md03 - part3Md03 - part3
Md03 - part3
 

Ähnlich wie Jdk1.5 Features

New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
Rakesh Madugula
 
Effective Java Second Edition
Effective Java Second EditionEffective Java Second Edition
Effective Java Second Edition
losalamos
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
Vince Vo
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
trixiacruz
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate Java
Philip Johnson
 

Ähnlich wie Jdk1.5 Features (20)

Csharp4 generics
Csharp4 genericsCsharp4 generics
Csharp4 generics
 
Java New Programming Features
Java New Programming FeaturesJava New Programming Features
Java New Programming Features
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
Java Generics
Java GenericsJava Generics
Java Generics
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - Generics
 
Effective Java Second Edition
Effective Java Second EditionEffective Java Second Edition
Effective Java Second Edition
 
Generics_RIO.ppt
Generics_RIO.pptGenerics_RIO.ppt
Generics_RIO.ppt
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
Getters_And_Setters.pptx
Getters_And_Setters.pptxGetters_And_Setters.pptx
Getters_And_Setters.pptx
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
 
Generic programming in java
Generic programming in javaGeneric programming in java
Generic programming in java
 
Collections
CollectionsCollections
Collections
 
Generics
GenericsGenerics
Generics
 
Getting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem SolvingGetting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem Solving
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console Program
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
Java generics
Java genericsJava generics
Java generics
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate Java
 
Java generics final
Java generics finalJava generics final
Java generics final
 

Kürzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Jdk1.5 Features

  • 1. Can these new and complex features simplify Java development?
  • 2.
  • 3. New class addtion ?  java.lang.StringBuilder  java.lang.Formatter  java.util.Queue  java.util.concurrent.*
  • 4. Covariant ReturnTypes?  Prior to JDK 1.5, a subclass could not override a method using a different return type  In JDK 1.5, a method can be overridden with a different return type as long as the new return type extends the original  A return type that differs from that of the method it is overriding is called a “covariant return”
  • 5. 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"); }
  • 6. 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"); }
  • 7. 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.
  • 8. 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(); }
  • 9. Enhanced for loop (foreach)(cont)  More example for (Suit suit : suits) for (Rank rank : ranks) sortedDeck.add(new Card(suit, rank));  Array looping int sum(int[] a) { int result = 0; for (int i : a) result += i; return result; }
  • 10. 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
  • 11. 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 } }
  • 12. 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 );
  • 13. 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)
  • 14. 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 c static 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
  • 15. Generic Types (cont) interface Collection <E> { boolean add(E o); boolean addAll(Collection<? extends E> c); Iterator<E> iterator(); <T>T[] toArray(T[] a); … }
  • 16. 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 when declaring an instance of the generic type Cannot use primitive types but auto-boxing covers over the difference
  • 17. 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
  • 18. Generics Wildcard Parameters (cont) boolean addAll(Collection<? extends E> c); ? represents an unknown type List<?> 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)
  • 19. Generics bounded type parameters (cont) boolean addAll (Collection<? extends E> c); Constrains possible actual types An 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>)
  • 20. 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.
  • 21. 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.
  • 22. 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.
  • 23. 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);
  • 24. 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().
  • 25. 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 }
  • 26. 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; } }
  • 27. 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); }
  • 28. 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);
  • 29. 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]); } }
  • 30. 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!"); } }
  • 31. Static Imports (cont)  Static imports also allow the import of static methods and variables. import static java.util.Arrays.sort; //import sort method import 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 class double d = abs(-15); //abs is method in Math class } }
  • 32. 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”})
  • 33. 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. @Override public 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()
  • 34. Formatted Output Even 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
  • 35. 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
  • 36. 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
  • 37. 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 block catch (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();
  • 38. 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()
  • 39. 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
  • 40. 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
  • 41. 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.
  • 42. 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.
  • 43. 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);
  • 44. 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]
  • 45. 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]]
  • 46. ?