SlideShare a Scribd company logo
1 of 20
Download to read offline
Java course - IAG0040




             Enums, Generics
               & Assertions



Anton Keks                           2011
Arrays helper class
 ●
     Arrays class provides operations on arrays
     –   asList() - provides a view of an array as a List
     –   binarySearch() - searches for an element from a sorted
         array
     –   equals() - checks two arrays for equality
     –   fill() - fills an array with the specified element
     –   sort() - sorts an array (using a tuned QuickSort algorithm)
     –   toString() - can be used for displaying of arrays
     –   deepToString() - the same for multidimensional arrays


Java course – IAG0040                                         Lecture 5
Anton Keks                                                      Slide 2
Collections helper class
 ●
     Provides constants and operations on Collections
      –   EMPTY_XXX or emptyXXX() - immutable empty collection
      –   sort(), binarySearch(), fill(), copy(), min(), max(),
          shuffle(), replaceAll(), rotate(), swap()
      –   singletonXXX() - immutable collection with one element
      –   enumeration() - for support of legacy classes
 ●   Wrappers
      –   checkedXXX() - a dynamically typesafe view
      –   unmodifiableXXX() - an unmodifiable view
      –   synchronizedXXX() - a synchronized view


Java course – IAG0040                                            Lecture 5
Anton Keks                                                         Slide 3
Tips
 ●   Program to interfaces
      –   List list = new ArrayList();
 ●   Copy (or conversion) constructors
      –   Set set = new TreeSet(map.values());
 ●   Checking if the Collection is empty
      –   collection.isEmpty()
      –   collection.size() == 0 may be very expensive
 ●   Remove all nulls (or other elements):
      –   collection.removeAll(Collections.singleton(null))
 ●   Convert to arrays
      –   String[] s = c.toArray(new String[c.size()]);
Java course – IAG0040                                    Lecture 5
Anton Keks                                                 Slide 4
Tips (cont)
 ●   Iterate Maps with Map.Entry if you need both keys and values
      –   for(Map.Entry e : map.entrySet()) {}
 ●   Initial capacity in case of HashSet, HashMap, and ArrayList
      –   new ArrayList(512)
 ●
     Operations on sublists are reflected in the main lists
      –   list.subList(15, 16).remove(object);
 ●   All collections implement toString()
      –   useful for displaying the contents quickly




Java course – IAG0040                                               Lecture 5
Anton Keks                                                            Slide 5
Inner classes
 ●   Inner classes can be defined inside of other classes
     –   class MyClass {
           class InnerClass { }
         }
     –   non static inner classes can access internals of parent
         classes
     –   static inner classes cannot




Java course – IAG0040                                       Lecture 5
Anton Keks                                                    Slide 6
Anonymous inner classes
 ●
     Classes can be created and instantiated 'inline'
      –   Runnable runnable = new Runnable() {
             public void run() {
                System.out.println("Running!");
             }
          };
          runnable.run();
 ●
     Analogous to initialization of arrays: new byte[] {1}
 ●   Very useful for implementation of short interfaces, where the
     code is needed as part of the surrounding code
 ●   Compiled into ParentClass$1.class, where $1 is the index of the
     anonymous class within the ParentClass

Java course – IAG0040                                         Lecture 5
Anton Keks                                                      Slide 7
Annotations
 ●
     Annotations are special type of interfaces
     –   @interface MyAnnotation { }
     –   Allow specification of meta data for source code elements
          ●   Used before the element in question, just like Javadoc
     –   In general, don't have effect at runtime
     –   Built-in: @SupressWarnings, @Deprecated,
                   @Override, @Generated, etc
     –   Can take parameters: @SupressWarnings(“unused”)
         or @SupressWarnings(value=“unused”)
 ●   Very useful in various frameworks, e.g. JUnit4, Spring2,
     Hibernate3, EJB3
Java course – IAG0040                                          Lecture 5
Anton Keks                                                       Slide 8
Enums
 ●   Special type of class (base class is java.lang.Enum)
 ●   enum Season {WINTER, SPRING, SUMMER, AUTUMN}
 ●   Only one instance of each constant is guaranteed; enums cannot be
     instantiated; they are implicitly final (cannot be extended)
 ●   Constructors can be used: WINTER(1), SPRING(“Hello”)
 ●   Accessed like constants: Season.WINTER
 ●   Every enum has the following methods:
      –   int ordinal() - returns an ordinal value of the constant
      –   String name() - returns the name of the constant
      –   static Enum valueOf(String name) - returns the enum constant
      –   static Season[] values() - returns an array of all constants
 ●   See Season and Planet in net.azib.java.lessons.enums
Java course – IAG0040                                                    Lecture 5
Anton Keks                                                                 Slide 9
Introduction to Generics
 ●   Are there any problems with collections?
      –   String s = (String) list.get(3);
 ●
     Java 1.5 introduced generics for type safety checks
      –   List<String> list;
          String s = list.get(3);
 ●   Additionally, generics allow to abstract over types
      –   List<Integer> list = Arrays.asList(
                               new Integer[]{1,2});
      –   List<String> list = Arrays.asList(
                              “a”, “b”, “c”);
 ●   Provide more compile time information for error checking
Java course – IAG0040                                      Lecture 5
Anton Keks                                                  Slide 10
Defining generic classes
 ●   public interface List<E> {
        void add(E x);
        Iterator<E> iterator();
     }
 ●   public interface Iterator<E>{
        E next();
        boolean hasNext();
     }
 ●   Formal type parameters are in the angle brackets <>
 ●
     In invocations of generic types (parametrized types), all occurrences
     of formal types are replaced by the actual argument
 ●
     Primitives cannot be used as arguments, but arrays and wrappers can
      –   Iterator<int[]> i;       List<Integer> intList;

Java course – IAG0040                                             Lecture 5
Anton Keks                                                         Slide 11
Defining generics
 ●
     Generics can be thought of as if they were expanded
     –   public interface ListOfIntegers {
           void add(Integer x);
           Iterator<Integer> iterator();
         }
 ●   Actually they are not: generics introduce no memory or
     performance overhead
 ●   Information about type parameters is stored in class files
     and used during compilation
 ●   Use possibly meaningful single character names
     –   E = Element, T = Type, K = Key, V = Value, etc
Java course – IAG0040                                     Lecture 5
Anton Keks                                                 Slide 12
Generics usage in Java API
 ●
     Collection<E>, Iterable<E>, Iterator<E>
 ●
     Set<E>, List<E>, Queue<E>
      –   Set<String> set = new HashSet<String>();
      –   Queue<Dog> q = new LinkedList<Dog>();
 ●   Map<K, V>
      –   Map<String, Thread> map =
          new HashMap<String, Thread>();
 ●
     Comparator<T>, Comparable<T>
 ●
     Class<T>
      –   Date d = Date.class.newInstance();

Java course – IAG0040                             Lecture 5
Anton Keks                                         Slide 13
Subtyping
 ●   If A extends B, does List<A> extend List<B>?
 ●   List<String> ls = new ArrayList<String>();
     List<Object> lo = ls;
     –   this is illegal – List of Strings is not a List of Objects
 ●   lo.add(new Integer(42)); // adds an illegal object
     String s = ls.get(0);    // this is not a String!
     –   this code would break type safety at runtime!
 ●   However
     –   ls instanceof List & lo instanceof List
     –   Collection<String> cs = ls;                     // legal


Java course – IAG0040                                                 Lecture 5
Anton Keks                                                             Slide 14
Backward compatibility
 ●
     Generics are backward compatible
      –   Java 1.5 still had to be able to run old (unparameterized) code
      –   Backward compatibility has influenced the implementation
 ●   Old-style (unparameterized or raw-type) code can still be written
      –   ArrayList al = new ArrayList<String>();
          ArrayList<String> al = new ArrayList();
 ●   For now, checks are only done at compile time
      –   At runtime, generic collections hold Objects ('type erasure')
      –   Collections.checkedXXX() methods may be used for runtime
          type checking
      –   Implementation may change in future

Java course – IAG0040                                                Lecture 5
Anton Keks                                                            Slide 15
Wildcards
 ●   void printCollection(Collection<Object> c) {
        for (Object e : c)
           System.out.println(e);
     }
 ●   printCollection(new ArrayList<String>()) //           doesn't compile

 ●   void printCollection(Collection<?> c) { // ? is a wildcard
        for (Object e : c)
           System.out.println(e);
     }
 ●   However the following fails (at compile time!)
      –   c.add(new Object());
      –   Collection<?> means “collection of unknown”, it is read-only
      –   Unknown <?> can always be assigned to Object (when reading)

Java course – IAG0040                                          Lecture 5
Anton Keks                                                      Slide 16
Bounded wildcards
 ●
     <? extends T> means “anything that extends T”
     –   upper bounded wildcard, “read-only”
     –   List<? extends Number> vs List<Number>
     –   List<Integer> can be assigned to the first one, but not to the
         second one
     –   add() still doesn't work, because actual type is not known
 ●
     <? super T> means “anything that is a supertype of T”
     –   lower bounded wildcard, “write-only”
     –   List<? super Number> vs List<Number>
     –   add(new Integer(5)) works, because Integer can be
         assigned to any supertype of Number or Number itself

Java course – IAG0040                                             Lecture 5
Anton Keks                                                         Slide 17
Generic methods
 ●
     Methods can also be generic, independently from their classes
 ●   Generic methods can substitute wildcard types
      –   boolean containsAll(Collection<?> c);
          <T> boolean containsAll(Collection<T> c);
 ●
     But it is more reasonable to use in case a type is used many times
      –   <T> void copy(List<T> dest, List<? extends T> src);
          <T, S extends T> void copy(
                                 List<T> dest, List<S> src);
 ●   T is selected automatically based on the passed types (it is always
     the most specific type possible), its usage is implicit
 ●   Relative type dependencies are important (extends / super)


Java course – IAG0040                                             Lecture 5
Anton Keks                                                         Slide 18
Generics tasks
 ●
     Use generics in
     WordFrequencyCalculatorImpl and
     DuplicateRemoverImpl
 ●   Write some new classes
     –   Circle and Square
          ●   both should extend the provided
              net.azib.java.lessons.collections.Shape
     –   ShapeAggregatorImpl (which should implement
         the ShapeAggregator)


Java course – IAG0040                              Lecture 5
Anton Keks                                          Slide 19
Assertions
 ●
     assert keyword can be used for assertion of validity of
     boolean expressions (a debugging feature)
      –   assert boolean-expression : value-expression;
      –   assert A == 5 : “A is not 5!!!”;
 ●
     If boolean-expression evaluates to false, an AssertionError is
     thrown with the value-expression as detailed message (optional)
 ●
     Assertions are disabled by default, therefore have no runtime
     overhead
 ●
     When enabled, help to write self-documented code and trace
     bugs at runtime
 ●
     java -ea switch enables assertions (specific packages and classes
     may be specified if global activation is not desired)
Java course – IAG0040                                          Lecture 5
Anton Keks                                                      Slide 20

More Related Content

What's hot

Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaSanjeev Tripathi
 
Core java concepts
Core java  conceptsCore java  concepts
Core java conceptsRam132
 
Java tutorials
Java tutorialsJava tutorials
Java tutorialssaryu2011
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...Sagar Verma
 
Core java concepts
Core java concepts Core java concepts
Core java concepts javeed_mhd
 
Core Java Certification
Core Java CertificationCore Java Certification
Core Java CertificationVskills
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7Deniz Oguz
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.Tarunsingh198
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My HeartBui Kiet
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Sagar Verma
 
Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Kernel Training
 
Java Serialization Deep Dive
Java Serialization Deep DiveJava Serialization Deep Dive
Java Serialization Deep DiveMartijn Dashorst
 
Java Serialization
Java SerializationJava Serialization
Java Serializationimypraz
 

What's hot (20)

Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Core java
Core java Core java
Core java
 
Core Java Certification
Core Java CertificationCore Java Certification
Core Java Certification
 
Presentation to java
Presentation  to  javaPresentation  to  java
Presentation to java
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course
 
Java Serialization Deep Dive
Java Serialization Deep DiveJava Serialization Deep Dive
Java Serialization Deep Dive
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
Javatut1
Javatut1 Javatut1
Javatut1
 

Viewers also liked

Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure JavaAnton Keks
 
Android Mockup Toolkit
Android Mockup ToolkitAndroid Mockup Toolkit
Android Mockup ToolkitAlan Goo
 
Animation in Java
Animation in JavaAnimation in Java
Animation in JavaAlan Goo
 
Bca i-fundamental of computer-u-4-data communication and network
Bca  i-fundamental of  computer-u-4-data communication and networkBca  i-fundamental of  computer-u-4-data communication and network
Bca i-fundamental of computer-u-4-data communication and networkRai University
 
SMART TOOLS: DISSECT, DIGEST AND DELIVER BIG DATA from Structure:Data 2012
SMART TOOLS: DISSECT, DIGEST AND DELIVER BIG DATA from Structure:Data 2012SMART TOOLS: DISSECT, DIGEST AND DELIVER BIG DATA from Structure:Data 2012
SMART TOOLS: DISSECT, DIGEST AND DELIVER BIG DATA from Structure:Data 2012Gigaom
 
The PlayStation®3’s SPUs in the Real World: A KILLZONE 2 Case Study
The PlayStation®3’s SPUs in the Real World: A KILLZONE 2 Case StudyThe PlayStation®3’s SPUs in the Real World: A KILLZONE 2 Case Study
The PlayStation®3’s SPUs in the Real World: A KILLZONE 2 Case StudyGuerrilla
 
Android Application And Unity3D Game Documentation
Android Application And Unity3D Game DocumentationAndroid Application And Unity3D Game Documentation
Android Application And Unity3D Game DocumentationSneh Raval
 
Car Game - Final Year Project
Car Game - Final Year ProjectCar Game - Final Year Project
Car Game - Final Year ProjectVivek Naskar
 
Structure Data 2014: IS VIDEO BIG DATA?, Steve Russell
Structure Data 2014: IS VIDEO BIG DATA?, Steve RussellStructure Data 2014: IS VIDEO BIG DATA?, Steve Russell
Structure Data 2014: IS VIDEO BIG DATA?, Steve RussellGigaom
 
Game project Final presentation
Game project Final presentationGame project Final presentation
Game project Final presentationgemmalunney
 
Game Design: The Production Plan
Game Design: The Production PlanGame Design: The Production Plan
Game Design: The Production PlanKevin Duggan
 
Game Development Step by Step
Game Development Step by StepGame Development Step by Step
Game Development Step by StepBayu Sembada
 
An Introduction To Game development
An Introduction To Game developmentAn Introduction To Game development
An Introduction To Game developmentAhmed
 
The Real-time Volumetric Cloudscapes of Horizon Zero Dawn
The Real-time Volumetric Cloudscapes of Horizon Zero DawnThe Real-time Volumetric Cloudscapes of Horizon Zero Dawn
The Real-time Volumetric Cloudscapes of Horizon Zero DawnGuerrilla
 

Viewers also liked (20)

Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure Java
 
Android Mockup Toolkit
Android Mockup ToolkitAndroid Mockup Toolkit
Android Mockup Toolkit
 
Animation in Java
Animation in JavaAnimation in Java
Animation in Java
 
Bca i-fundamental of computer-u-4-data communication and network
Bca  i-fundamental of  computer-u-4-data communication and networkBca  i-fundamental of  computer-u-4-data communication and network
Bca i-fundamental of computer-u-4-data communication and network
 
SMART TOOLS: DISSECT, DIGEST AND DELIVER BIG DATA from Structure:Data 2012
SMART TOOLS: DISSECT, DIGEST AND DELIVER BIG DATA from Structure:Data 2012SMART TOOLS: DISSECT, DIGEST AND DELIVER BIG DATA from Structure:Data 2012
SMART TOOLS: DISSECT, DIGEST AND DELIVER BIG DATA from Structure:Data 2012
 
Soco java games 2011
Soco java games 2011Soco java games 2011
Soco java games 2011
 
The PlayStation®3’s SPUs in the Real World: A KILLZONE 2 Case Study
The PlayStation®3’s SPUs in the Real World: A KILLZONE 2 Case StudyThe PlayStation®3’s SPUs in the Real World: A KILLZONE 2 Case Study
The PlayStation®3’s SPUs in the Real World: A KILLZONE 2 Case Study
 
Advance Network Technologies
Advance Network TechnologiesAdvance Network Technologies
Advance Network Technologies
 
Android Application And Unity3D Game Documentation
Android Application And Unity3D Game DocumentationAndroid Application And Unity3D Game Documentation
Android Application And Unity3D Game Documentation
 
Car Game - Final Year Project
Car Game - Final Year ProjectCar Game - Final Year Project
Car Game - Final Year Project
 
Structure Data 2014: IS VIDEO BIG DATA?, Steve Russell
Structure Data 2014: IS VIDEO BIG DATA?, Steve RussellStructure Data 2014: IS VIDEO BIG DATA?, Steve Russell
Structure Data 2014: IS VIDEO BIG DATA?, Steve Russell
 
OOP java
OOP javaOOP java
OOP java
 
Game project Final presentation
Game project Final presentationGame project Final presentation
Game project Final presentation
 
Game Design: The Production Plan
Game Design: The Production PlanGame Design: The Production Plan
Game Design: The Production Plan
 
Ppt.online games
Ppt.online gamesPpt.online games
Ppt.online games
 
Introduction to Game Development
Introduction to Game DevelopmentIntroduction to Game Development
Introduction to Game Development
 
Game Development Step by Step
Game Development Step by StepGame Development Step by Step
Game Development Step by Step
 
An Introduction To Game development
An Introduction To Game developmentAn Introduction To Game development
An Introduction To Game development
 
The Real-time Volumetric Cloudscapes of Horizon Zero Dawn
The Real-time Volumetric Cloudscapes of Horizon Zero DawnThe Real-time Volumetric Cloudscapes of Horizon Zero Dawn
The Real-time Volumetric Cloudscapes of Horizon Zero Dawn
 
Big data ppt
Big data pptBig data ppt
Big data ppt
 

Similar to Java Course 5: Enums, Generics, Assertions

Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaAyush Mishra
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersMiles Sabin
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersMiles Sabin
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosGenevaJUG
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersMiles Sabin
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersSkills Matter
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play frameworkFelipe
 

Similar to Java Course 5: Enums, Generics, Assertions (20)

Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in Scala
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian Dragos
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play framework
 

More from Anton Keks

Being a professional software tester
Being a professional software testerBeing a professional software tester
Being a professional software testerAnton Keks
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIAnton Keks
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingAnton Keks
 
Java Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsJava Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsAnton Keks
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design PatternsAnton Keks
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyAnton Keks
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionAnton Keks
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsAnton Keks
 
Java Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, HibernateJava Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, HibernateAnton Keks
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problemAnton Keks
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database RefactoringAnton Keks
 
Scrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerScrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerAnton Keks
 
Being a Professional Software Developer
Being a Professional Software DeveloperBeing a Professional Software Developer
Being a Professional Software DeveloperAnton Keks
 

More from Anton Keks (13)

Being a professional software tester
Being a professional software testerBeing a professional software tester
Being a professional software tester
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUI
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & Logging
 
Java Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsJava Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & Servlets
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and Reflection
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Java Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, HibernateJava Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, Hibernate
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problem
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database Refactoring
 
Scrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerScrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineer
 
Being a Professional Software Developer
Being a Professional Software DeveloperBeing a Professional Software Developer
Being a Professional Software Developer
 

Recently uploaded

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 

Recently uploaded (20)

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 

Java Course 5: Enums, Generics, Assertions

  • 1. Java course - IAG0040 Enums, Generics & Assertions Anton Keks 2011
  • 2. Arrays helper class ● Arrays class provides operations on arrays – asList() - provides a view of an array as a List – binarySearch() - searches for an element from a sorted array – equals() - checks two arrays for equality – fill() - fills an array with the specified element – sort() - sorts an array (using a tuned QuickSort algorithm) – toString() - can be used for displaying of arrays – deepToString() - the same for multidimensional arrays Java course – IAG0040 Lecture 5 Anton Keks Slide 2
  • 3. Collections helper class ● Provides constants and operations on Collections – EMPTY_XXX or emptyXXX() - immutable empty collection – sort(), binarySearch(), fill(), copy(), min(), max(), shuffle(), replaceAll(), rotate(), swap() – singletonXXX() - immutable collection with one element – enumeration() - for support of legacy classes ● Wrappers – checkedXXX() - a dynamically typesafe view – unmodifiableXXX() - an unmodifiable view – synchronizedXXX() - a synchronized view Java course – IAG0040 Lecture 5 Anton Keks Slide 3
  • 4. Tips ● Program to interfaces – List list = new ArrayList(); ● Copy (or conversion) constructors – Set set = new TreeSet(map.values()); ● Checking if the Collection is empty – collection.isEmpty() – collection.size() == 0 may be very expensive ● Remove all nulls (or other elements): – collection.removeAll(Collections.singleton(null)) ● Convert to arrays – String[] s = c.toArray(new String[c.size()]); Java course – IAG0040 Lecture 5 Anton Keks Slide 4
  • 5. Tips (cont) ● Iterate Maps with Map.Entry if you need both keys and values – for(Map.Entry e : map.entrySet()) {} ● Initial capacity in case of HashSet, HashMap, and ArrayList – new ArrayList(512) ● Operations on sublists are reflected in the main lists – list.subList(15, 16).remove(object); ● All collections implement toString() – useful for displaying the contents quickly Java course – IAG0040 Lecture 5 Anton Keks Slide 5
  • 6. Inner classes ● Inner classes can be defined inside of other classes – class MyClass { class InnerClass { } } – non static inner classes can access internals of parent classes – static inner classes cannot Java course – IAG0040 Lecture 5 Anton Keks Slide 6
  • 7. Anonymous inner classes ● Classes can be created and instantiated 'inline' – Runnable runnable = new Runnable() { public void run() { System.out.println("Running!"); } }; runnable.run(); ● Analogous to initialization of arrays: new byte[] {1} ● Very useful for implementation of short interfaces, where the code is needed as part of the surrounding code ● Compiled into ParentClass$1.class, where $1 is the index of the anonymous class within the ParentClass Java course – IAG0040 Lecture 5 Anton Keks Slide 7
  • 8. Annotations ● Annotations are special type of interfaces – @interface MyAnnotation { } – Allow specification of meta data for source code elements ● Used before the element in question, just like Javadoc – In general, don't have effect at runtime – Built-in: @SupressWarnings, @Deprecated, @Override, @Generated, etc – Can take parameters: @SupressWarnings(“unused”) or @SupressWarnings(value=“unused”) ● Very useful in various frameworks, e.g. JUnit4, Spring2, Hibernate3, EJB3 Java course – IAG0040 Lecture 5 Anton Keks Slide 8
  • 9. Enums ● Special type of class (base class is java.lang.Enum) ● enum Season {WINTER, SPRING, SUMMER, AUTUMN} ● Only one instance of each constant is guaranteed; enums cannot be instantiated; they are implicitly final (cannot be extended) ● Constructors can be used: WINTER(1), SPRING(“Hello”) ● Accessed like constants: Season.WINTER ● Every enum has the following methods: – int ordinal() - returns an ordinal value of the constant – String name() - returns the name of the constant – static Enum valueOf(String name) - returns the enum constant – static Season[] values() - returns an array of all constants ● See Season and Planet in net.azib.java.lessons.enums Java course – IAG0040 Lecture 5 Anton Keks Slide 9
  • 10. Introduction to Generics ● Are there any problems with collections? – String s = (String) list.get(3); ● Java 1.5 introduced generics for type safety checks – List<String> list; String s = list.get(3); ● Additionally, generics allow to abstract over types – List<Integer> list = Arrays.asList( new Integer[]{1,2}); – List<String> list = Arrays.asList( “a”, “b”, “c”); ● Provide more compile time information for error checking Java course – IAG0040 Lecture 5 Anton Keks Slide 10
  • 11. Defining generic classes ● public interface List<E> { void add(E x); Iterator<E> iterator(); } ● public interface Iterator<E>{ E next(); boolean hasNext(); } ● Formal type parameters are in the angle brackets <> ● In invocations of generic types (parametrized types), all occurrences of formal types are replaced by the actual argument ● Primitives cannot be used as arguments, but arrays and wrappers can – Iterator<int[]> i; List<Integer> intList; Java course – IAG0040 Lecture 5 Anton Keks Slide 11
  • 12. Defining generics ● Generics can be thought of as if they were expanded – public interface ListOfIntegers { void add(Integer x); Iterator<Integer> iterator(); } ● Actually they are not: generics introduce no memory or performance overhead ● Information about type parameters is stored in class files and used during compilation ● Use possibly meaningful single character names – E = Element, T = Type, K = Key, V = Value, etc Java course – IAG0040 Lecture 5 Anton Keks Slide 12
  • 13. Generics usage in Java API ● Collection<E>, Iterable<E>, Iterator<E> ● Set<E>, List<E>, Queue<E> – Set<String> set = new HashSet<String>(); – Queue<Dog> q = new LinkedList<Dog>(); ● Map<K, V> – Map<String, Thread> map = new HashMap<String, Thread>(); ● Comparator<T>, Comparable<T> ● Class<T> – Date d = Date.class.newInstance(); Java course – IAG0040 Lecture 5 Anton Keks Slide 13
  • 14. Subtyping ● If A extends B, does List<A> extend List<B>? ● List<String> ls = new ArrayList<String>(); List<Object> lo = ls; – this is illegal – List of Strings is not a List of Objects ● lo.add(new Integer(42)); // adds an illegal object String s = ls.get(0); // this is not a String! – this code would break type safety at runtime! ● However – ls instanceof List & lo instanceof List – Collection<String> cs = ls; // legal Java course – IAG0040 Lecture 5 Anton Keks Slide 14
  • 15. Backward compatibility ● Generics are backward compatible – Java 1.5 still had to be able to run old (unparameterized) code – Backward compatibility has influenced the implementation ● Old-style (unparameterized or raw-type) code can still be written – ArrayList al = new ArrayList<String>(); ArrayList<String> al = new ArrayList(); ● For now, checks are only done at compile time – At runtime, generic collections hold Objects ('type erasure') – Collections.checkedXXX() methods may be used for runtime type checking – Implementation may change in future Java course – IAG0040 Lecture 5 Anton Keks Slide 15
  • 16. Wildcards ● void printCollection(Collection<Object> c) { for (Object e : c) System.out.println(e); } ● printCollection(new ArrayList<String>()) // doesn't compile ● void printCollection(Collection<?> c) { // ? is a wildcard for (Object e : c) System.out.println(e); } ● However the following fails (at compile time!) – c.add(new Object()); – Collection<?> means “collection of unknown”, it is read-only – Unknown <?> can always be assigned to Object (when reading) Java course – IAG0040 Lecture 5 Anton Keks Slide 16
  • 17. Bounded wildcards ● <? extends T> means “anything that extends T” – upper bounded wildcard, “read-only” – List<? extends Number> vs List<Number> – List<Integer> can be assigned to the first one, but not to the second one – add() still doesn't work, because actual type is not known ● <? super T> means “anything that is a supertype of T” – lower bounded wildcard, “write-only” – List<? super Number> vs List<Number> – add(new Integer(5)) works, because Integer can be assigned to any supertype of Number or Number itself Java course – IAG0040 Lecture 5 Anton Keks Slide 17
  • 18. Generic methods ● Methods can also be generic, independently from their classes ● Generic methods can substitute wildcard types – boolean containsAll(Collection<?> c); <T> boolean containsAll(Collection<T> c); ● But it is more reasonable to use in case a type is used many times – <T> void copy(List<T> dest, List<? extends T> src); <T, S extends T> void copy( List<T> dest, List<S> src); ● T is selected automatically based on the passed types (it is always the most specific type possible), its usage is implicit ● Relative type dependencies are important (extends / super) Java course – IAG0040 Lecture 5 Anton Keks Slide 18
  • 19. Generics tasks ● Use generics in WordFrequencyCalculatorImpl and DuplicateRemoverImpl ● Write some new classes – Circle and Square ● both should extend the provided net.azib.java.lessons.collections.Shape – ShapeAggregatorImpl (which should implement the ShapeAggregator) Java course – IAG0040 Lecture 5 Anton Keks Slide 19
  • 20. Assertions ● assert keyword can be used for assertion of validity of boolean expressions (a debugging feature) – assert boolean-expression : value-expression; – assert A == 5 : “A is not 5!!!”; ● If boolean-expression evaluates to false, an AssertionError is thrown with the value-expression as detailed message (optional) ● Assertions are disabled by default, therefore have no runtime overhead ● When enabled, help to write self-documented code and trace bugs at runtime ● java -ea switch enables assertions (specific packages and classes may be specified if global activation is not desired) Java course – IAG0040 Lecture 5 Anton Keks Slide 20