SlideShare a Scribd company logo
Agenda GenericsCompile-time type safety for collections without casting Enhanced for loopAutomates use of Iterators to avoid errors Autoboxing/unboxingAvoids manual conversion between primitive types (such as int)  and wrapper types (such as Integer) Typesafe enumsProvides all the well-known benefits of the Typesafe Enum pattern1
Generics - IntroTutorials : http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdfCompile-time type safety without casting.
Methods can be defined to operate on unknown types of Objects without using ‘Objects’ class. And no type casting is required.
Big advantage: collections are now type safe.2Example : ‘Generify ‘ your Java classes –public class Box<T> {  private T t ; public void add(Tt ) { this.t = t; } public T get() { return t; } }How to use this :Box<Integer> integerBox = new Box<Integer>(); 	…	integerBox.add(new Integer(25)); //typesafe only Integers can be passed	Integer myInt = integerBox.get() //no typecasting requiredT is a type parameter that will be replaced by a real type.T is the name of a type parameter.This name is used as a placeholder for the actual type that will be passed to Gen when an object is created.
Generics – Example 23Another Example public class GenericFactory<E> {    Class theClass = null;    public GenericFactory(Class theClass) {        this.theClass = theClass;    }    public E createInstance() throws …{        return (E) this.theClass.newInstance();    }Usage : Creates a Factory of Generic TypeGenericFactory<MyClass> factory =  new GenericFactory<MyClass>(MyClass.class);MyClass myClassInstance = factory.createInstance();
Generics – Generics in Methods4static <T> void fromArrayToCollection(T[] a, Collection<T> c) {        for (T o : a) {            c.add(o);        }    }    static <T> Collection<T> fromArrayToCollectionv2(T[] a) {        Collection<T> c = new ArrayList<T>();        for (T o : a) {            c.add(o);        }        return c ;    }One more Interesting Example…public <T> T ifThenElse(boolean b, T first, T second) { 	return b ? first : second; }
Generics – With Collections5ListsList<String> list = new ArrayList<String>(); list.add(“A String”); String string2 = list.get(0); // no type casting.Maps (can define multiple typed parameters)	Map<String, String> map = new HashMap<String, String>();map.put ("key1", "value1");map.put ("key2", "value2");String value1 = map.get("key1");Iterating a Generic List:List<String> list = new ArrayList<String>(); Iterator<String> iterator = list.iterator(); while(iterator.hasNext()){ String aString = iterator.next(); }Backward Compatibility	List list = new ArrayList<String>(); Nested Generic Types	List<List<String>> myListOfListsOfStrings;
Generics – Diving Deeper6Generics and SubtypingList<String> ls = new ArrayList<String>(); List<Object> lo = ls; //illegal won’t compile!!What’s the Problem ?lo.add(new Object()); String s = ls.get(0); // attempts to assign an Object to a String!In other words Collection<Object>  is not a supertype of all the types of collectionsTo cope with this sort of situation use Wildcardsstatic void printCollection2(Collection<?> c) {  // Collection<?> -“collection of unknown”        for (Object e : c) {            System.out.println(e);        } }Limitation in using unbounded wildcardAny method that takes Generic type of argument cannot be invoked :Collection<?> c = new ArrayList<String>();c.add(new Object()); // compile time error
Generics – Subtyping continued…7Bounded WildcardsList<? extends Shape> is an example of a bounded wildcard.A wildcard with an upper bound looks like " ? extends Type “
A wildcard with a lower bound looks like " ? super Type " Example :public class Collections {   public static <T> void copy    ( List<? super T> dest, List<? extends T> src) {  // uses bounded wildcards       for (int i=0; i<src.size(); i++)         dest.set(i,src.get(i));   } }List<Object> output = new ArrayList< Object >(); List<Long>    input = new ArrayList< Long >(); ... Collections.copy(output,input);  // fineList<String> output = new ArrayList< String >(); List<Long>    input = new ArrayList< Long >(); ... Collections.copy(output,input);  // error 
Enhanced for-loop or for each loop8New syntax of for loop that works for Collections and Arrays - Collections :void cancelAll(Collection<TimerTask> c) { for (TimerTask t : c) {		t.cancel();	} }Arrays :int sum(int[] a) { 	int result = 0; for (int i : a) {	result += i; 	}	return result; }Nested –for (Suit suit : suits) {	for (Rank rank : ranks){ 		sortedDeck.add(new Card(suit, rank));	}} No need to use iterators. (The compiler does this for you behind your back)
 The for-each construct gets rid of the clutter and the opportunity for error.Autoboxing9primitive types to be converted into respective wrapper objects and vice versa.(by the Compiler)int i; Integer j; j = 2;  // int to Integer automatic conversioni = j; // Integer.intValue() callj = i; // int to Integer automatic conversionAdvantages : 1.  Since Wrapper classes are immutable  intObject = new Integer(10); Before Java 5 int intPrimitive = intObject.intValue(); intPrimitive++; intObject = new Integer(intPrimitive); Java 5 AutoBoxingintObject++;2. Easy to use wrapper classes within Collections ArrayList<Integer> list = new ArrayList<Integer>(); for(int i = 0; i < 10; i++)	list.add(i); // Boxing
Enum - Introduction10Java Constants Before JDK 1.5 –public static final int SEASON_WINTER = 0; public static final int SEASON_SPRING = 1; ……Issues:Not Type-safe  Since season is represented as integer one can pass any integer values, without any compiler warnings.No Name space one may need to refer to java-docs (if any) to check the possible values in case more than one type of constants are declared in a single interface/class. Compile time binding Print Values not self explanatory.JDK 1.5 gets linguistic support for enumerated types as follows :enum Season { WINTER, SPRING, SUMMER, FALL }** Don’t confuse enum with the Enumeration interface, an almost obsolete way of iterating over Collections, replaced by Iterator.
Enum - Example11How to define them ..public enum Flavor {    CHOCOLATE(100), //declare all the possible values first.     VANILLA(120),    STRAWBERRY(80);    private int fCalories; // can have state (member variables)    int getCalories(){ // cusotm method      return fCalories;    }    private Flavor(int aCalories){ // constructor      fCalories = aCalories;    }  }How to use them …String getColor(Flavor flv){ // Used as normal java objects.. 	if(flv == Flavor.VANILLA) // “==“ can be used for value comparison	  	return “White” ;	…….		switch(flv) { 		case VANILLA :  // You can use enums as case labels		……}String color = getColor(Flavor.VANILLA) // no constructor only constant values.

More Related Content

What's hot (20)

Stl Containers
Stl ContainersStl Containers
Stl Containers
ppd1961
 
Java generics final
Java generics finalJava generics final
Java generics final
Akshay Chaudhari
 
Python programming
Python  programmingPython  programming
Python programming
Ashwin Kumar Ramasamy
 
Python for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.comPython for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.com
ShwetaAggarwal56
 
Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++
Anton Kolotaev
 
Java Generics
Java GenericsJava Generics
Java Generics
Carol McDonald
 
Generic Programming seminar
Generic Programming seminarGeneric Programming seminar
Generic Programming seminar
Gautam Roy
 
Modern C++
Modern C++Modern C++
Modern C++
Richard Thomson
 
Regular types in C++
Regular types in C++Regular types in C++
Regular types in C++
Ilio Catallo
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
Santosh Rajan
 
Smart pointers
Smart pointersSmart pointers
Smart pointers
Vishal Mahajan
 
Smart Pointers in C++
Smart Pointers in C++Smart Pointers in C++
Smart Pointers in C++
Francesco Casalegno
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
sanya6900
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and concepts
Nicola Bonelli
 
Life & Work of Robin Milner | Turing100@Persistent
Life & Work of Robin Milner | Turing100@PersistentLife & Work of Robin Milner | Turing100@Persistent
Life & Work of Robin Milner | Turing100@Persistent
Persistent Systems Ltd.
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
Ganesh Samarthyam
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
Mohamed Krar
 
Programming with Python
Programming with PythonProgramming with Python
Programming with Python
Rasan Samarasinghe
 
Scala
ScalaScala
Scala
Zhiwen Guo
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
Graham Royce
 
Stl Containers
Stl ContainersStl Containers
Stl Containers
ppd1961
 
Python for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.comPython for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.com
ShwetaAggarwal56
 
Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++
Anton Kolotaev
 
Generic Programming seminar
Generic Programming seminarGeneric Programming seminar
Generic Programming seminar
Gautam Roy
 
Regular types in C++
Regular types in C++Regular types in C++
Regular types in C++
Ilio Catallo
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
Santosh Rajan
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
sanya6900
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and concepts
Nicola Bonelli
 
Life & Work of Robin Milner | Turing100@Persistent
Life & Work of Robin Milner | Turing100@PersistentLife & Work of Robin Milner | Turing100@Persistent
Life & Work of Robin Milner | Turing100@Persistent
Persistent Systems Ltd.
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
Mohamed Krar
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
Graham Royce
 

Viewers also liked (20)

Oops
OopsOops
Oops
Gayathri Ganesh
 
Cr8.5 usermanual
Cr8.5 usermanualCr8.5 usermanual
Cr8.5 usermanual
teope_ruvina
 
Introduction à la programmation C#
Introduction à la programmation C#Introduction à la programmation C#
Introduction à la programmation C#
hamoji hamoji
 
Learn ASP
Learn ASPLearn ASP
Learn ASP
gurchet
 
Basic c#
Basic c#Basic c#
Basic c#
kishore4268
 
Plataforma de compiladores .NET, Visual Studio 2015, C# 6 e futuro C# 7
Plataforma de compiladores .NET,Visual Studio 2015, C# 6 e futuro C# 7Plataforma de compiladores .NET,Visual Studio 2015, C# 6 e futuro C# 7
Plataforma de compiladores .NET, Visual Studio 2015, C# 6 e futuro C# 7
Rogério Moraes de Carvalho
 
What's new in C# 6 - NetPonto Porto 20160116
What's new in C# 6  - NetPonto Porto 20160116What's new in C# 6  - NetPonto Porto 20160116
What's new in C# 6 - NetPonto Porto 20160116
Paulo Morgado
 
The Little Wonders of C# 6
The Little Wonders of C# 6The Little Wonders of C# 6
The Little Wonders of C# 6
BlackRabbitCoder
 
C# - Part 1
C# - Part 1C# - Part 1
C# - Part 1
Md. Mahedee Hasan
 
Crystal Report
Crystal ReportCrystal Report
Crystal Report
Bapem Sanggau
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
Shahzad
 
C#.NET
C#.NETC#.NET
C#.NET
gurchet
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
jeffz
 
.NET and C# Introduction
.NET and C# Introduction.NET and C# Introduction
.NET and C# Introduction
Siraj Memon
 
Crystal reports seminar
Crystal reports seminarCrystal reports seminar
Crystal reports seminar
teope_ruvina
 
tybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notestybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notes
WE-IT TUTORIALS
 
C# Crystal Reports
C# Crystal ReportsC# Crystal Reports
C# Crystal Reports
Muhammad Umer Riaz
 
C#/.NET Little Pitfalls
C#/.NET Little PitfallsC#/.NET Little Pitfalls
C#/.NET Little Pitfalls
BlackRabbitCoder
 
C#/.NET Little Wonders
C#/.NET Little WondersC#/.NET Little Wonders
C#/.NET Little Wonders
BlackRabbitCoder
 
Introduction à la programmation C#
Introduction à la programmation C#Introduction à la programmation C#
Introduction à la programmation C#
hamoji hamoji
 
Plataforma de compiladores .NET, Visual Studio 2015, C# 6 e futuro C# 7
Plataforma de compiladores .NET,Visual Studio 2015, C# 6 e futuro C# 7Plataforma de compiladores .NET,Visual Studio 2015, C# 6 e futuro C# 7
Plataforma de compiladores .NET, Visual Studio 2015, C# 6 e futuro C# 7
Rogério Moraes de Carvalho
 
What's new in C# 6 - NetPonto Porto 20160116
What's new in C# 6  - NetPonto Porto 20160116What's new in C# 6  - NetPonto Porto 20160116
What's new in C# 6 - NetPonto Porto 20160116
Paulo Morgado
 
The Little Wonders of C# 6
The Little Wonders of C# 6The Little Wonders of C# 6
The Little Wonders of C# 6
BlackRabbitCoder
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
Shahzad
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
jeffz
 
.NET and C# Introduction
.NET and C# Introduction.NET and C# Introduction
.NET and C# Introduction
Siraj Memon
 
Crystal reports seminar
Crystal reports seminarCrystal reports seminar
Crystal reports seminar
teope_ruvina
 
tybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notestybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notes
WE-IT TUTORIALS
 
Ad

Similar to Java New Programming Features (20)

Java 1.5 - whats new and modern patterns (2007)
Java 1.5 - whats new and modern patterns (2007)Java 1.5 - whats new and modern patterns (2007)
Java 1.5 - whats new and modern patterns (2007)
Peter Antman
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate Java
Philip Johnson
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
knutmork
 
Jdk1.5 Features
Jdk1.5 FeaturesJdk1.5 Features
Jdk1.5 Features
india_mani
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Carol McDonald
 
Java Generics.ppt
Java Generics.pptJava Generics.ppt
Java Generics.ppt
brayazar
 
Module 4_CSE3146-Advanced Java Programming-Anno_Lambda-PPTs.pptx
Module 4_CSE3146-Advanced Java Programming-Anno_Lambda-PPTs.pptxModule 4_CSE3146-Advanced Java Programming-Anno_Lambda-PPTs.pptx
Module 4_CSE3146-Advanced Java Programming-Anno_Lambda-PPTs.pptx
aruthras2323
 
javasebeyondbasics
javasebeyondbasicsjavasebeyondbasics
javasebeyondbasics
webuploader
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
Rakesh Madugula
 
Generics
GenericsGenerics
Generics
Kongu Engineering College, Perundurai, Erode
 
Java 7 New Features
Java 7 New FeaturesJava 7 New Features
Java 7 New Features
Jussi Pohjolainen
 
Effective Java Second Edition
Effective Java Second EditionEffective Java Second Edition
Effective Java Second Edition
losalamos
 
Effective Java - Still Effective After All These Years
Effective Java - Still Effective After All These YearsEffective Java - Still Effective After All These Years
Effective Java - Still Effective After All These Years
Marakana Inc.
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
Gurpreet singh
 
Javase5generics
Javase5genericsJavase5generics
Javase5generics
imypraz
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
Rakesh Waghela
 
Tiger: Java 5 Evolutions
Tiger: Java 5 EvolutionsTiger: Java 5 Evolutions
Tiger: Java 5 Evolutions
Marco Bresciani
 
Collection in java to store multiple values.pptx
Collection in java to store multiple values.pptxCollection in java to store multiple values.pptx
Collection in java to store multiple values.pptx
ASHUTOSH TRIVEDI
 
Generics Tutorial
Generics TutorialGenerics Tutorial
Generics Tutorial
wasntgosu
 
Generics Tutorial
Generics TutorialGenerics Tutorial
Generics Tutorial
wasntgosu
 
Java 1.5 - whats new and modern patterns (2007)
Java 1.5 - whats new and modern patterns (2007)Java 1.5 - whats new and modern patterns (2007)
Java 1.5 - whats new and modern patterns (2007)
Peter Antman
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate Java
Philip Johnson
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
knutmork
 
Jdk1.5 Features
Jdk1.5 FeaturesJdk1.5 Features
Jdk1.5 Features
india_mani
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Carol McDonald
 
Java Generics.ppt
Java Generics.pptJava Generics.ppt
Java Generics.ppt
brayazar
 
Module 4_CSE3146-Advanced Java Programming-Anno_Lambda-PPTs.pptx
Module 4_CSE3146-Advanced Java Programming-Anno_Lambda-PPTs.pptxModule 4_CSE3146-Advanced Java Programming-Anno_Lambda-PPTs.pptx
Module 4_CSE3146-Advanced Java Programming-Anno_Lambda-PPTs.pptx
aruthras2323
 
javasebeyondbasics
javasebeyondbasicsjavasebeyondbasics
javasebeyondbasics
webuploader
 
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
 
Effective Java - Still Effective After All These Years
Effective Java - Still Effective After All These YearsEffective Java - Still Effective After All These Years
Effective Java - Still Effective After All These Years
Marakana Inc.
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
Gurpreet singh
 
Javase5generics
Javase5genericsJavase5generics
Javase5generics
imypraz
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
Rakesh Waghela
 
Tiger: Java 5 Evolutions
Tiger: Java 5 EvolutionsTiger: Java 5 Evolutions
Tiger: Java 5 Evolutions
Marco Bresciani
 
Collection in java to store multiple values.pptx
Collection in java to store multiple values.pptxCollection in java to store multiple values.pptx
Collection in java to store multiple values.pptx
ASHUTOSH TRIVEDI
 
Generics Tutorial
Generics TutorialGenerics Tutorial
Generics Tutorial
wasntgosu
 
Generics Tutorial
Generics TutorialGenerics Tutorial
Generics Tutorial
wasntgosu
 
Ad

Recently uploaded (20)

Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 

Java New Programming Features

  • 1. Agenda GenericsCompile-time type safety for collections without casting Enhanced for loopAutomates use of Iterators to avoid errors Autoboxing/unboxingAvoids manual conversion between primitive types (such as int) and wrapper types (such as Integer) Typesafe enumsProvides all the well-known benefits of the Typesafe Enum pattern1
  • 2. Generics - IntroTutorials : http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdfCompile-time type safety without casting.
  • 3. Methods can be defined to operate on unknown types of Objects without using ‘Objects’ class. And no type casting is required.
  • 4. Big advantage: collections are now type safe.2Example : ‘Generify ‘ your Java classes –public class Box<T> { private T t ; public void add(Tt ) { this.t = t; } public T get() { return t; } }How to use this :Box<Integer> integerBox = new Box<Integer>(); … integerBox.add(new Integer(25)); //typesafe only Integers can be passed Integer myInt = integerBox.get() //no typecasting requiredT is a type parameter that will be replaced by a real type.T is the name of a type parameter.This name is used as a placeholder for the actual type that will be passed to Gen when an object is created.
  • 5. Generics – Example 23Another Example public class GenericFactory<E> { Class theClass = null; public GenericFactory(Class theClass) { this.theClass = theClass; } public E createInstance() throws …{ return (E) this.theClass.newInstance(); }Usage : Creates a Factory of Generic TypeGenericFactory<MyClass> factory = new GenericFactory<MyClass>(MyClass.class);MyClass myClassInstance = factory.createInstance();
  • 6. Generics – Generics in Methods4static <T> void fromArrayToCollection(T[] a, Collection<T> c) { for (T o : a) { c.add(o); } } static <T> Collection<T> fromArrayToCollectionv2(T[] a) { Collection<T> c = new ArrayList<T>(); for (T o : a) { c.add(o); } return c ; }One more Interesting Example…public <T> T ifThenElse(boolean b, T first, T second) { return b ? first : second; }
  • 7. Generics – With Collections5ListsList<String> list = new ArrayList<String>(); list.add(“A String”); String string2 = list.get(0); // no type casting.Maps (can define multiple typed parameters) Map<String, String> map = new HashMap<String, String>();map.put ("key1", "value1");map.put ("key2", "value2");String value1 = map.get("key1");Iterating a Generic List:List<String> list = new ArrayList<String>(); Iterator<String> iterator = list.iterator(); while(iterator.hasNext()){ String aString = iterator.next(); }Backward Compatibility List list = new ArrayList<String>(); Nested Generic Types List<List<String>> myListOfListsOfStrings;
  • 8. Generics – Diving Deeper6Generics and SubtypingList<String> ls = new ArrayList<String>(); List<Object> lo = ls; //illegal won’t compile!!What’s the Problem ?lo.add(new Object()); String s = ls.get(0); // attempts to assign an Object to a String!In other words Collection<Object> is not a supertype of all the types of collectionsTo cope with this sort of situation use Wildcardsstatic void printCollection2(Collection<?> c) { // Collection<?> -“collection of unknown” for (Object e : c) { System.out.println(e); } }Limitation in using unbounded wildcardAny method that takes Generic type of argument cannot be invoked :Collection<?> c = new ArrayList<String>();c.add(new Object()); // compile time error
  • 9. Generics – Subtyping continued…7Bounded WildcardsList<? extends Shape> is an example of a bounded wildcard.A wildcard with an upper bound looks like " ? extends Type “
  • 10. A wildcard with a lower bound looks like " ? super Type " Example :public class Collections { public static <T> void copy ( List<? super T> dest, List<? extends T> src) { // uses bounded wildcards for (int i=0; i<src.size(); i++) dest.set(i,src.get(i)); } }List<Object> output = new ArrayList< Object >(); List<Long>    input = new ArrayList< Long >(); ... Collections.copy(output,input);  // fineList<String> output = new ArrayList< String >(); List<Long>    input = new ArrayList< Long >(); ... Collections.copy(output,input);  // error 
  • 11. Enhanced for-loop or for each loop8New syntax of for loop that works for Collections and Arrays - Collections :void cancelAll(Collection<TimerTask> c) { for (TimerTask t : c) { t.cancel(); } }Arrays :int sum(int[] a) { int result = 0; for (int i : a) { result += i; } return result; }Nested –for (Suit suit : suits) { for (Rank rank : ranks){ sortedDeck.add(new Card(suit, rank)); }} No need to use iterators. (The compiler does this for you behind your back)
  • 12. The for-each construct gets rid of the clutter and the opportunity for error.Autoboxing9primitive types to be converted into respective wrapper objects and vice versa.(by the Compiler)int i; Integer j; j = 2; // int to Integer automatic conversioni = j; // Integer.intValue() callj = i; // int to Integer automatic conversionAdvantages : 1. Since Wrapper classes are immutable intObject = new Integer(10); Before Java 5 int intPrimitive = intObject.intValue(); intPrimitive++; intObject = new Integer(intPrimitive); Java 5 AutoBoxingintObject++;2. Easy to use wrapper classes within Collections ArrayList<Integer> list = new ArrayList<Integer>(); for(int i = 0; i < 10; i++) list.add(i); // Boxing
  • 13. Enum - Introduction10Java Constants Before JDK 1.5 –public static final int SEASON_WINTER = 0; public static final int SEASON_SPRING = 1; ……Issues:Not Type-safe Since season is represented as integer one can pass any integer values, without any compiler warnings.No Name space one may need to refer to java-docs (if any) to check the possible values in case more than one type of constants are declared in a single interface/class. Compile time binding Print Values not self explanatory.JDK 1.5 gets linguistic support for enumerated types as follows :enum Season { WINTER, SPRING, SUMMER, FALL }** Don’t confuse enum with the Enumeration interface, an almost obsolete way of iterating over Collections, replaced by Iterator.
  • 14. Enum - Example11How to define them ..public enum Flavor { CHOCOLATE(100), //declare all the possible values first. VANILLA(120), STRAWBERRY(80); private int fCalories; // can have state (member variables) int getCalories(){ // cusotm method return fCalories; } private Flavor(int aCalories){ // constructor fCalories = aCalories; } }How to use them …String getColor(Flavor flv){ // Used as normal java objects.. if(flv == Flavor.VANILLA) // “==“ can be used for value comparison return “White” ; ……. switch(flv) { case VANILLA : // You can use enums as case labels ……}String color = getColor(Flavor.VANILLA) // no constructor only constant values.
  • 15. Enum 12Facts about enmus :Enums can nave methods, constructors , static and member variables, static block etc..like other java classes.
  • 16. These can be passed around as Java objects.
  • 17. Constructors are never invoked outside the Enums (no new operator)
  • 18. Enums are implicitly final subclasses of java.lang.Enum
  • 19. equals() and == amount to the same thing.Advantages -You can use enums as case labels.
  • 20. Methods come built in with enums to do do things like convert enums names to ordinals, and combos with enumset.
  • 21. You can attach additional fields and code to enum constants.
  • 22. enums are type safe. With Strings all your items in all categories are the same type. There is nothing to stop you from feeding a fruit category to an animal parameter.
  • 23. You can compare enums quickly with ==. You don’t need to use equals as you do with String.Varargs and Static import13Arbitrary number of arguments can be passed using varargs.public static String format(String pattern, Object... arguments){ …..}Here we can pass –format( "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.", 7, new Date(), “abcd");We can also pass an array of objects.Varargs can be used only in the final argument positionStatic Importimport static java.lang.Math.PI;….double r = cos(PI * theta);Advantage :No need to refer same class/package more than one timeDisadvantage :Name space is lost. Makes code unmaintainable, Don’t overuse this.