SlideShare a Scribd company logo
The essential Java language features tour, Part 3
Autoboxing and unboxing, enhanced for loops, static imports, varargs, and
covariant return types
To satisfy the need for constant interfaces while avoiding the problems imposed
by the use of these interfaces, Java 5 introduced static imports. This language
feature can be used to import a class's static members. It's implemented via the
import static statement whose syntax appears below:
import static packagespec . classname . (
staticmembername | * );
This statement's placement of static after import distinguishes it from a
regular import statement. Its syntax is similar to the regular import statement
in terms of the standard period-separated list of package and subpackage names.
Either a single static member name or all static member names (thanks to the
asterisk) can be imported. Consider the following examples:
import static java.lang.Math.*; // Import all static members from Math.
import static java.lang.Math.PI; // Import the PI static constant only.
import static java.lang.Math.cos; // Import the cos() static method only.
Once imported, static members can be specified without having to prefix them
with their class names. For example, after specifying either the first or third
static import, you could specify cos directly, as in double cosine =
cos(angle);.
To fix Listing 6 so that it no longer relies on implements Switchable, we can
insert a static import, which Listing 7 demonstrates.
Listing 7. Light.java (version 2)
package foo;
import static foo.Switchable.*;
public class Light
{
private boolean state = OFF;
public void printState()
{
System.out.printf("state = %s%n", (state == OFF) ? "OFF" : "ON");
}
public void toggle()
{
state = (state == OFF) ? ON : OFF;
}
}
Listing 7 begins with a package foo; statement because you cannot import static
members from a type located in the default package. This package name appears as
part of the subsequent import static foo.Switchable.*; static import.
There are two additional cautions in regard to static imports:
When two static imports import the same named member, the compiler reports an
error. For example, suppose package physics contains a Math class that's
identical to java.lang's Math class in that it implements the same PI constant
and trigonometric methods. When confronted by the following code fragment, the
compiler reports errors because it cannot determine whether java.lang.Math's or
physics.Math's PI constant is being accessed and cos() method is being called:
import static java.lang.Math.cos;
import static physics.Math.cos;
double angle = PI;
System.out.println(cos(angle));
Overuse of static imports can make your code unreadable and unmaintainable
because it pollutes the code's namespace with all of the static members you
import. Also, anyone reading your code could have a hard time finding out which
class a static member comes from, especially when importing all static member
names from a class.
Varargs
The variable arguments (varargs) feature lets you pass a variable list of
arguments to a method or constructor without having to first box those arguments
into an array.
To use varargs, you must first declare the method or constructor with ... after
the rightmost parameter type name in the method's/constructor's parameter list.
Consider the following example:
static void printNames(String... names)
{
for (String name: names)
System.out.println(name);
}
In this example, printNames() declares a single names parameter. Note the three
dots after the String type name. Also, I use the enhanced for loop to iterate
over the variable number of String arguments passed to this method.
When invoking the method, specify a comma-separated list of arguments that match
the parameter type. For example, given the previous method declaration, you
could invoke this method as follows:
printNames("Java", "JRuby", "Jython", "Scala");
Behind the scenes, varargs is implemented in terms of an array and ... is syntax
sugar that hides the array implementation. However, you can access the array
from within the method, as follows:
static void printNames2(String... names)
{
for (int i = 0; i < names.length; i++)
System.out.println(names[i]);
}
Also, you can create and pass the array directly, although you would typically
not do so. Check out the example below:
printNames2(new String[] { "Java", "JRuby", "Jython", "Scala" });
Covariant return types
Java 5's final new language feature is the covariant return type, which is a
method return type that, in the superclass's method declaration, is the
supertype of the return type in the subclass's overriding method declaration.
Consider Listing 8.
Listing 8. CovarDemo.java
class Paper
{
@Override
public String toString()
{
return "paper instance";
}
}
class PaperFactory
{
Paper newInstance()
{
return new Paper();
}
}
class Cardboard extends Paper
{
@Override
public String toString()
{
return "cardboard instance";
}
}
class CardboardFactory extends PaperFactory
{
@Override
Cardboard newInstance()
{
return new Cardboard();
}
}
public class CovarDemo
{
public static void main(String[] args)
{
PaperFactory pf = new PaperFactory();
Paper paper = pf.newInstance();
System.out.println(paper);
CardboardFactory cf = new CardboardFactory();
Cardboard cardboard = cf.newInstance();
System.out.println(cardboard);
}
}
Listing 8 presents Paper, PaperFactory, Cardboard, CardboardFactory, and
CovarDemo classes. The key classes in this demo are PaperFactory and
CardboardFactory.
PaperFactory declares a newInstance() method that CardboardFactory overrides.
Notice that the return type changes from Paper in the PaperFactory superclass to
Cardboard in the CardboardFactory subclass. The return type is said to be
covariant.
Compile Listing 8 (javac CovarDemo.java) and run the application (java
CovarDemo). You should observe the following output:
paper instance
cardboard instance
Covariant return types eliminate explicit casts. For example, if
CardboardFactory's newInstance() method had been declared with a Paper return
type, you would have to specify Cardboard cardboard = (Cardboard)
cf.newInstance(); in the main() method.
Covariant return types and generics
Eliminating cast operations is common to covariant return types and generics,
which is why covariant return types were implemented as part of generics, and
why they're not included in Java 5's list of language features.
In conclusion
Java 5 improved type safety mainly through generics but also through typesafe
enums. It also improved developer productivity by introducing annotations,
autoboxing and unboxing, the enhanced for loop, static imports, varargs, and
covariant return types. Next up in the Java 101: The next generation series is a
look at productivity-oriented language features introduced in Java 7.

More Related Content

What's hot (19)

PLSQL CURSOR
PLSQL CURSORPLSQL CURSOR
PLSQL CURSOR
Arun Sial
 
Java Generics
Java GenericsJava Generics
Java Generics
jeslie
 
Lecture 8 abstract class and interface
Lecture   8 abstract class and interfaceLecture   8 abstract class and interface
Lecture 8 abstract class and interface
manish kumar
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
Ganesh Samarthyam
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
manish kumar
 
TEMPLATES in C++
TEMPLATES in C++TEMPLATES in C++
TEMPLATES in C++
Prof Ansari
 
Inheritance
InheritanceInheritance
Inheritance
Mavoori Soshmitha
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
Python Programming Basics
Python Programming BasicsPython Programming Basics
Python Programming Basics
RichardAlexanderPhilip
 
Cursors
CursorsCursors
Cursors
Isha Aggarwal
 
Java generics final
Java generics finalJava generics final
Java generics final
Akshay Chaudhari
 
Java vs kotlin
Java vs kotlinJava vs kotlin
Java vs kotlin
Deesha Vora
 
LISP:Object System Lisp
LISP:Object System LispLISP:Object System Lisp
LISP:Object System Lisp
DataminingTools Inc
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java Generics
Yann-Gaël Guéhéneuc
 
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
 
Generic Programming in java
Generic Programming in javaGeneric Programming in java
Generic Programming in java
Garik Kalashyan
 
Cursors
CursorsCursors
Cursors
Priyanka Yadav
 
Java session4
Java session4Java session4
Java session4
Jigarthacker
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
Prerna Sharma
 
PLSQL CURSOR
PLSQL CURSORPLSQL CURSOR
PLSQL CURSOR
Arun Sial
 
Java Generics
Java GenericsJava Generics
Java Generics
jeslie
 
Lecture 8 abstract class and interface
Lecture   8 abstract class and interfaceLecture   8 abstract class and interface
Lecture 8 abstract class and interface
manish kumar
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
manish kumar
 
TEMPLATES in C++
TEMPLATES in C++TEMPLATES in C++
TEMPLATES in C++
Prof Ansari
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java Generics
Yann-Gaël Guéhéneuc
 
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
 
Generic Programming in java
Generic Programming in javaGeneric Programming in java
Generic Programming in java
Garik Kalashyan
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
Prerna Sharma
 

Similar to Java2 (20)

New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
Rakesh Madugula
 
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptxFINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
VGaneshKarthikeyan
 
Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]
Palak Sanghani
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
sholavanalli
 
Core & Advance Java Training For Beginner-PSK Technologies Pvt. Ltd. Nagpur
Core & Advance Java Training For Beginner-PSK Technologies Pvt. Ltd. NagpurCore & Advance Java Training For Beginner-PSK Technologies Pvt. Ltd. Nagpur
Core & Advance Java Training For Beginner-PSK Technologies Pvt. Ltd. Nagpur
PSK Technolgies Pvt. Ltd. IT Company Nagpur
 
--------------- FloatArrays-java - ckage csi213-lab05-import java-u.pdf
--------------- FloatArrays-java -    ckage csi213-lab05-import java-u.pdf--------------- FloatArrays-java -    ckage csi213-lab05-import java-u.pdf
--------------- FloatArrays-java - ckage csi213-lab05-import java-u.pdf
AdrianEBJKingr
 
java question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdfjava question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdf
dbrienmhompsonkath75
 
Class loader basic
Class loader basicClass loader basic
Class loader basic
명철 강
 
U3 JAVA.pptx
U3 JAVA.pptxU3 JAVA.pptx
U3 JAVA.pptx
madan r
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
aromanets
 
3 j unit
3 j unit3 j unit
3 j unit
kishoregali
 
Computer programming 2 -lesson 4
Computer programming 2  -lesson 4Computer programming 2  -lesson 4
Computer programming 2 -lesson 4
MLG College of Learning, Inc
 
Abstract factory
Abstract factoryAbstract factory
Abstract factory
Muthukumar P
 
For this lab, you will write the following filesAbstractDataCalc.pdf
For this lab, you will write the following filesAbstractDataCalc.pdfFor this lab, you will write the following filesAbstractDataCalc.pdf
For this lab, you will write the following filesAbstractDataCalc.pdf
alokindustries1
 
Scanner.pptx
Scanner.pptxScanner.pptx
Scanner.pptx
rhiene05
 
Java ppt
Java pptJava ppt
Java ppt
Rohan Gajre
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxing
Geetha Manohar
 
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
Eduardo Bergavera
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
Gousalya Ramachandran
 
J2ee standards > CDI
J2ee standards > CDIJ2ee standards > CDI
J2ee standards > CDI
harinderpisces
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
Rakesh Madugula
 
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptxFINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
VGaneshKarthikeyan
 
Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]
Palak Sanghani
 
--------------- FloatArrays-java - ckage csi213-lab05-import java-u.pdf
--------------- FloatArrays-java -    ckage csi213-lab05-import java-u.pdf--------------- FloatArrays-java -    ckage csi213-lab05-import java-u.pdf
--------------- FloatArrays-java - ckage csi213-lab05-import java-u.pdf
AdrianEBJKingr
 
java question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdfjava question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdf
dbrienmhompsonkath75
 
Class loader basic
Class loader basicClass loader basic
Class loader basic
명철 강
 
U3 JAVA.pptx
U3 JAVA.pptxU3 JAVA.pptx
U3 JAVA.pptx
madan r
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
aromanets
 
For this lab, you will write the following filesAbstractDataCalc.pdf
For this lab, you will write the following filesAbstractDataCalc.pdfFor this lab, you will write the following filesAbstractDataCalc.pdf
For this lab, you will write the following filesAbstractDataCalc.pdf
alokindustries1
 
Scanner.pptx
Scanner.pptxScanner.pptx
Scanner.pptx
rhiene05
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxing
Geetha Manohar
 
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
Eduardo Bergavera
 

More from Jahan Murugassan (6)

AWS TRAINING
AWS TRAININGAWS TRAINING
AWS TRAINING
Jahan Murugassan
 
JAVASCRIPT DEVELOPER SALARY FOR FRESHERS
JAVASCRIPT DEVELOPER SALARY FOR FRESHERSJAVASCRIPT DEVELOPER SALARY FOR FRESHERS
JAVASCRIPT DEVELOPER SALARY FOR FRESHERS
Jahan Murugassan
 
AWS TRAINING
AWS TRAININGAWS TRAINING
AWS TRAINING
Jahan Murugassan
 
Selenium
SeleniumSelenium
Selenium
Jahan Murugassan
 
Angularjs on line training
Angularjs on line trainingAngularjs on line training
Angularjs on line training
Jahan Murugassan
 
ANDROID TRAINING IN CHENNAI
ANDROID TRAINING IN CHENNAIANDROID TRAINING IN CHENNAI
ANDROID TRAINING IN CHENNAI
Jahan Murugassan
 

Recently uploaded (20)

UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Diabetic neuropathy peripheral autonomic
Diabetic neuropathy peripheral autonomicDiabetic neuropathy peripheral autonomic
Diabetic neuropathy peripheral autonomic
Pankaj Patawari
 
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd yearVitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
ARUN KUMAR
 
Studying Drama: Definition, types and elements
Studying Drama: Definition, types and elementsStudying Drama: Definition, types and elements
Studying Drama: Definition, types and elements
AbdelFattahAdel2
 
Timber Pitch Roof Construction Measurement-2024.pptx
Timber Pitch Roof Construction Measurement-2024.pptxTimber Pitch Roof Construction Measurement-2024.pptx
Timber Pitch Roof Construction Measurement-2024.pptx
Tantish QS, UTM
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Diabetic neuropathy peripheral autonomic
Diabetic neuropathy peripheral autonomicDiabetic neuropathy peripheral autonomic
Diabetic neuropathy peripheral autonomic
Pankaj Patawari
 
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd yearVitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
ARUN KUMAR
 
Studying Drama: Definition, types and elements
Studying Drama: Definition, types and elementsStudying Drama: Definition, types and elements
Studying Drama: Definition, types and elements
AbdelFattahAdel2
 
Timber Pitch Roof Construction Measurement-2024.pptx
Timber Pitch Roof Construction Measurement-2024.pptxTimber Pitch Roof Construction Measurement-2024.pptx
Timber Pitch Roof Construction Measurement-2024.pptx
Tantish QS, UTM
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 

Java2

  • 1. The essential Java language features tour, Part 3 Autoboxing and unboxing, enhanced for loops, static imports, varargs, and covariant return types To satisfy the need for constant interfaces while avoiding the problems imposed by the use of these interfaces, Java 5 introduced static imports. This language feature can be used to import a class's static members. It's implemented via the import static statement whose syntax appears below: import static packagespec . classname . ( staticmembername | * ); This statement's placement of static after import distinguishes it from a regular import statement. Its syntax is similar to the regular import statement in terms of the standard period-separated list of package and subpackage names. Either a single static member name or all static member names (thanks to the asterisk) can be imported. Consider the following examples: import static java.lang.Math.*; // Import all static members from Math. import static java.lang.Math.PI; // Import the PI static constant only. import static java.lang.Math.cos; // Import the cos() static method only. Once imported, static members can be specified without having to prefix them with their class names. For example, after specifying either the first or third static import, you could specify cos directly, as in double cosine = cos(angle);. To fix Listing 6 so that it no longer relies on implements Switchable, we can insert a static import, which Listing 7 demonstrates. Listing 7. Light.java (version 2) package foo; import static foo.Switchable.*; public class Light { private boolean state = OFF; public void printState() { System.out.printf("state = %s%n", (state == OFF) ? "OFF" : "ON"); } public void toggle() { state = (state == OFF) ? ON : OFF; } } Listing 7 begins with a package foo; statement because you cannot import static members from a type located in the default package. This package name appears as part of the subsequent import static foo.Switchable.*; static import. There are two additional cautions in regard to static imports: When two static imports import the same named member, the compiler reports an error. For example, suppose package physics contains a Math class that's identical to java.lang's Math class in that it implements the same PI constant and trigonometric methods. When confronted by the following code fragment, the compiler reports errors because it cannot determine whether java.lang.Math's or physics.Math's PI constant is being accessed and cos() method is being called: import static java.lang.Math.cos; import static physics.Math.cos; double angle = PI;
  • 2. System.out.println(cos(angle)); Overuse of static imports can make your code unreadable and unmaintainable because it pollutes the code's namespace with all of the static members you import. Also, anyone reading your code could have a hard time finding out which class a static member comes from, especially when importing all static member names from a class. Varargs The variable arguments (varargs) feature lets you pass a variable list of arguments to a method or constructor without having to first box those arguments into an array. To use varargs, you must first declare the method or constructor with ... after the rightmost parameter type name in the method's/constructor's parameter list. Consider the following example: static void printNames(String... names) { for (String name: names) System.out.println(name); } In this example, printNames() declares a single names parameter. Note the three dots after the String type name. Also, I use the enhanced for loop to iterate over the variable number of String arguments passed to this method. When invoking the method, specify a comma-separated list of arguments that match the parameter type. For example, given the previous method declaration, you could invoke this method as follows: printNames("Java", "JRuby", "Jython", "Scala"); Behind the scenes, varargs is implemented in terms of an array and ... is syntax sugar that hides the array implementation. However, you can access the array from within the method, as follows: static void printNames2(String... names) { for (int i = 0; i < names.length; i++) System.out.println(names[i]); } Also, you can create and pass the array directly, although you would typically not do so. Check out the example below: printNames2(new String[] { "Java", "JRuby", "Jython", "Scala" }); Covariant return types Java 5's final new language feature is the covariant return type, which is a method return type that, in the superclass's method declaration, is the supertype of the return type in the subclass's overriding method declaration. Consider Listing 8. Listing 8. CovarDemo.java class Paper { @Override public String toString() { return "paper instance"; } } class PaperFactory { Paper newInstance() { return new Paper(); }
  • 3. } class Cardboard extends Paper { @Override public String toString() { return "cardboard instance"; } } class CardboardFactory extends PaperFactory { @Override Cardboard newInstance() { return new Cardboard(); } } public class CovarDemo { public static void main(String[] args) { PaperFactory pf = new PaperFactory(); Paper paper = pf.newInstance(); System.out.println(paper); CardboardFactory cf = new CardboardFactory(); Cardboard cardboard = cf.newInstance(); System.out.println(cardboard); } } Listing 8 presents Paper, PaperFactory, Cardboard, CardboardFactory, and CovarDemo classes. The key classes in this demo are PaperFactory and CardboardFactory. PaperFactory declares a newInstance() method that CardboardFactory overrides. Notice that the return type changes from Paper in the PaperFactory superclass to Cardboard in the CardboardFactory subclass. The return type is said to be covariant. Compile Listing 8 (javac CovarDemo.java) and run the application (java CovarDemo). You should observe the following output: paper instance cardboard instance Covariant return types eliminate explicit casts. For example, if CardboardFactory's newInstance() method had been declared with a Paper return type, you would have to specify Cardboard cardboard = (Cardboard) cf.newInstance(); in the main() method. Covariant return types and generics Eliminating cast operations is common to covariant return types and generics, which is why covariant return types were implemented as part of generics, and why they're not included in Java 5's list of language features. In conclusion Java 5 improved type safety mainly through generics but also through typesafe enums. It also improved developer productivity by introducing annotations, autoboxing and unboxing, the enhanced for loop, static imports, varargs, and covariant return types. Next up in the Java 101: The next generation series is a look at productivity-oriented language features introduced in Java 7.