Beruflich Dokumente
Kultur Dokumente
static imports enhanced for loop variable argument methods assertions (1.4 ) Generics enumerations Auto boxing / unboxing
static imports
Used to import static members of a class After import they can be referred directly eg :
import static java.lang.System.out; import static java.lang.Integer.*; public class TestStaticImport { public static void main(String[] args) { out.println(MAX_VALUE); out.println(toHexString(42)); } }
Objective 7.1
now
int a[ ] = {10, 20, 30, 40, 50} ; for(int i : a) System.out.println(i);
Objective 2.2
Objective 2.2
// x2 is already declared // can't stuff an array into an int // can't stuff a long into an int // you might get a Cat!
Objective 2.2
<variable> is implicitly an array variable argument should be at the end Overloading can be done (with no ambiguity)
Objective 2.3
Objective 2.3
// ambiguous
Objective 2.3
Assertions
Assertions are used to test assumptions Can be enabled or disabled at runtime
Assertions
Formats assert condition assert condition : expression
Objective 2.3
Assertions
example 1 public static void main(String args[]) { int n; for(int i=0; i < 10; i++) { n = getnum(); assert n > 0 ; // will fail with n is 0
Assertions
example 2 public static void main(String args[]) { int n; for(int i=0; i < 10; i++) { n = getnum();
assert n > 0 : n is not positive // Display this message System.out.println("n is " + n); } } }
Objective 2.3
Assertions
If assert is used as identifier in old programs, it is a problem (oops!) No worry ! Just inform the compiler which compiles with warning
javac javac javac javac -source 1.3 MyCode.java -source 1.4 MyCode.java -source 1.5 MyCode.java -source 5 MyCode.java
Objective 2.3
Assertions
Enabling / Disabling assertions java -ea MyCode java -ea pack.MyCode java -enableassertions MyCode Assertions are java -da MyCode disabled java -disableassertions MyCode by default java -ea -da:Test2 MyCode // disable only for Test2 java -da:myPackage MyCode // disable for all classes of myPackage java -da:myPackage MyCode // disable for myPackage and sub packages java -esa MyCode // enable for system classes // other flags for system classes -dsa -enablesystemassertions -disablesystemassertions
Objective 2.3
Assertions
Using assertions appropriately Do not use assertions
to validate arguments of public methods to validate command line arguments that can cause side effects (to do something which is required even when assertions are disabled)
Objective 2.3
Generics
Legacy way of using collections
creation
List myList = new ArrayList(); // can't declare a type legacy collections myList.add("Fred"); // OK, it will hold Strings are not myList.add(new Dog()); // and it will hold Dogs too type safe myList.add(new Integer(42)); // and Integers...
retrieval
String s = (String) myList.get(0); String s = (String) myList.get(1) ; // goes fine // OOPS !!! ClassCastException
retrieval
String s = myList.get(0); // no casting required. Compiler knows it
Generics
method parameters
Legacy void checkAndRemove(Collection c) { String s = null; for ( Iterator i = c.iterator( ); i.hasNext( ); ) { s = (String) i.next( ); if (s.length( ) > 4) System.out.println(s); } } Generic void checkAndRemove(Collection <String> c) { String s = null; for ( Iterator<String> i = c.iterator( ); i.hasNext( ); ) { s = i.next( ); if ( s.length( ) > 4) System.out.println(s); } }
Generics
return types
public Set<Dog> getDogList() { Set<Dog> dogs = new HashSet<Dog>(); . return dogs; } Dog d = getDogList().get(0); //no need to cast
Objective 6.3 6.4
Generics
Generic using non-generic
List<Integer> myList = new ArrayList<Integer>(); myList.add(6); Adder adder = new Adder(); int total = adder.addAll(myList);
Adder class compiles fine as the method is not changing the list
//The older, non-generics class we want to use: class Adder { int addAll(List list) { Iterator it = list.iterator(); int total = 0; while (it.hasNext()) { int i = ((Integer)it.next()).intValue(); total += i; } return total; } }
Generics
Generic using non-generic
List<Integer> myList = new ArrayList<Integer>(); myList.add(4); Inserter class compiles with warning as the myList.add(6); method is changing the list Inserter in = new Inserter(); javac Inserter.java in.insert(myList); Note: Inserter.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
class Inserter { // method with a non-generic List argument void insert(List list) { list.add(new Integer(42)); // adds to the incoming list } }
Generics
Generics & polymorphism
class Parent { } class Child extends Parent { } List<Parent> myList = new ArrayList<Child>();
Does not work as ArrayList<child> is not a subclass of List<Parent> Compiler checks for Exact match
Objective 6.3 6.4
Generics
Generics & polymorphism
List<Dog> dog = new ArrayList<Dog>( ); addIt(dog);
void addIt(List<Animal> a) { . }
Generics
Wildcard <?> Used to declare generic subtypes
Bounded wildcard
List <? extends Animal> a = new ArrayList<Animal>( ); List <? extends Animal> a = new ArrayList<Dog>( ); List <? extends Animal> a = new ArrayList<Cat>( );
Takes List of Animal or any subtype of Animal But objects cannot be added
a.add(new Dog( ) ); //fails a.add(new Animal() ); //fails
Objective 6.3 6.4
Generics
Wildcard <?>
Lower Bounded wildcard
List <? super Dog> a = new ArrayList<Animal>( ); List <? super Dog> a = new ArrayList<Object>( ); List <? super Dog> a = new ArrayList<Dog>( );
Takes List of Dog or any super type of Dog Allows adding Dog objects
Generics
Wildcard <?>
List<?>
Generics
Wildcard <?> Check out !!!
List<?> list = new ArrayList<Dog>(); // valid List<? extends Animal> aList = new ArrayList<Dog>(); // valid List<?> foo = new ArrayList<? extends Animal>(); //wrong! should be on the left side List<? extends Dog> cList = new ArrayList<Integer>(); //not valid List<? super Dog> bList = new ArrayList<Animal>(); //valid. But only Dog objects can be added List<? super Animal> dList = new ArrayList<Dog>(); // not valid
Generics
Generic class declaration class Box<T> { private T t; public void add(T t) { this.t = t; } public T get() { return t; }
public static void main(String[] args) { Box<Dog> box = new Box<Dog>(); box.add(new Dog( ) ); } }
Objective 6.3 6.4
Generics
Generic class declaration
public class AnimalHolder<T extends Animal> { // use "T" instead of "? T animal; public static void main(String[] args) { AnimalHolder<Dog> dogHolder = new AnimalHolder<Dog>(); // OK AnimalHolder<Integer> x = new AnimalHolder<Integer>(); // NO! } }
Generics
Generic methods
public <T> void makeArrayList(T t) { List<T> list = new ArrayList<T>(); list.add(t); }
public <T extends Animal> void makeArrayList(T t) { List<T> list = new ArrayList<T>(); list.add(t); }
Enums
In prior releases, enumerated types were simulated using static final which were not type safe enums added in release 5.0 enum is a type with a set of constant values enums implemented as class
Objective 1.3
Enums
enum Season {WINTER, SPRING, SUMMER, FALL} Season sea = Season.WINTER; switch(sea) { case WINTER : case SUMMER : } for (Season x : Season.values() ) System.out.println(x);
Objective 1.3
Enums
what goes on inside ?
creates a class Season with static final variables WINTER, SPRING etc static method values() which returns an array static method valueOf(String) that returns appropriate enum value other methods like equals(), hashCode(), toString() etc The class implements Comparable<Season> and Serializable
Objective 1.3
Enums
Constructors, methods and variables
enum Size { SMALL(21), MEDIUM(35), BIG(45) ; Size(int s) { measure = s; } private int measure; public int getSize() { return measure; } } Size size; size = Size.BIG; System.out.println(size.getSize()); // prints 45
Objective 1.3
Enums
Read on to know more Constructors can be overloaded Constructors can never be invoked directly enums can be inside or outside the class enums cannot be defined in a method (local enums) Semicolon at the end of enum declaration is optional
Objective 1.3
Objective 3.1
Objective 3.1
boxing
public static void main(String [] args) { int i = 5; go(i); // which go() will be invoked? } } output
long
Objective 3.1
int,int
Objective 3.1
Byte, Byte
Objective 3.1
No way !!
Objective 3.1
Objective 3.1
Objective 3.1