JAVA V Assertions Java, winter semester

Similar documents
JAVA V Source files Java, winter semester

Java Generics Java, summer semester

Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Subtyping for behaviour?

Java Enum Java, winter semester ,2018 1

Subtyping for behaviour?

Java. Platforms, etc.

Java. Platforms, etc.

1.1. Annotations History Lesson - C/C++

Subtyping for behaviour?

Java Generics. Lecture CS1122 Summer 2008

The collections interfaces

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

#Students per correct answers

11/7/18 JAVA GENERICS. Java Collections. Java Collections. Using Java Collections. Proposals for adding Generics to Java.

Announcements. Lecture 15 Generics 2. Announcements. Big picture. CSE 331 Software Design and Implementation

CSE 331 Software Design and Implementation. Lecture 15 Generics 2

Generalizing Collection Classes Using Generics with other Java 1.5 Features Integration of Generics with Previous Releases User built generic classes

Parametric polymorphism and Generics

Photo credit: Andrew Kennedy JAVA GENERICS

Announcements. Java Graphics. Exceptions. Java Odds & Ends

Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism

CSE 331. Generics (Parametric Polymorphism)

CS108, Stanford Handout #8. Java Generics

Java: exceptions and genericity

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 19 19:36: CS61B: Lecture #25 1

CSE 331 Software Design & Implementation

CSCE 314 Programming Languages

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 18 21:04: CS61B: Lecture #25 1

Outline. 1 Generic Classes. 2 Generics and Subtyping. Generics. Guy Wiener. Generic Classes. Generics and Subtyping

Problems. Java Generics. Example. Example. Often you need the same behavior for different kind of classes

CSC 172 Data Structures and Algorithms. Lecture 3 Spring 2018 TuTh 3:25 pm 4:40 pm

Java Lectures. Enhancements in Java 1.5

PARAMETRIC POLYMORPHISM

CSE Lecture 7: Polymorphism and generics 16 September Nate Nystrom UTA

Polymorphism (generics)

INF3110 Programming Languages Object Orientation and Types, part II

CMSC 132: Object-Oriented Programming II

Software Engineering. Prof. Agostino Poggi

301AA - Advanced Programming [AP-2017]

CSE 331 Software Design & Implementation

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 7. Nadia Polikarpova

Java Generics -- an introduction. Based on

301AA - Advanced Programming [AP-2017]

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Exercise 8 Parametric polymorphism November 18, 2016

Outline. iterator review iterator implementation the Java foreach statement testing

Advanced Topics in Java and on Security in Systems Effective Generics. Eirik Eltvik 26 th of February 2007

PIC 20A Collections and Data Structures

generic programming alberto ferrari university of parma

Taming the Tiger. Joshua Bloch, Distinguished Engineer Neal Gafter, Senior Staff Engineer Sun Microsystems. java.sun.

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

CS61B Lecture #23. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

INF3110 Programming Languages Object orientation part II

Java Collections. Wrapper classes. Wrapper classes

Java Collections. Engi Hafez Seliem

Exercise Session Week 6

AP CS Unit 7: Interfaces. Programs

Collections, Maps and Generics

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Java Review: Objects

COMP1008 An overview of Polymorphism, Types, Interfaces and Generics

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, ,

CS61B Lecture #24. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

Assertions, pre/postconditions

Java 5 New Language Features

Polymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism

Announcements. Lecture 14 Generics 1. Announcements. CSE 331 Software Design and Implementation. Leah Perlmutter / Summer 2018

CSE 331 Software Design and Implementation. Lecture 14 Generics 1

What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one

Prelim 1. CS 2110, October 1, 2015, 5:30 PM Total Question Name True Short Testing Strings Recursion

//instance variables //methods. Foo x = new Foo(); Interface: also a type of objects public interface Bar {

Modulo I Java Generics

Introduction to Programming Using Java (98-388)

Programming Languages and Techniques (CIS120)

CMSC 202H. Containers and Iterators

CSCI 136 Written Exam #0 Fundamentals of Computer Science II Spring 2015

Pieter van den Hombergh Richard van den Ham. March 1, 2018

Java Magistère BFA

CSE 331 Software Design and Implementation. Lecture 13 Generics 1

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Generics. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 10

Exercise 8 Parametric polymorphism November 17, 2017

COMP 250. Lecture 32. interfaces. (Comparable, Iterable & Iterator) Nov. 22/23, 2017

CMSC 202. Containers

Advanced Programming Generics Collections

Making New instances of Classes

CMSC 433 Section 0101 Fall 2012 Midterm Exam #1

CSE 331 Final Exam 3/16/15 Sample Solution

ITI Introduction to Computing II

Timing ListOperations

public static boolean isoutside(int min, int max, int value)

The list abstract data type defined a number of operations that all list-like objects ought to implement:

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Enum Types. Built-in support for types of discrete values Advantages over C++ s enum: Type-safety Body can include methods and fields

Array Based Lists. Collections

Topic 7: Algebraic Data Types

Transcription:

JAVA Assertions 1

Assertion since Java 1.4 the statement with a boolean expression a developer supposes that the expression is always satisfied (evaluates to true) if it is evaluated to false -> error intended for debugging assertions can be enabled or disable for whole program or for several classes only disabled by default must not have any side effects 2

Usage assert Expression1; assert Expression1 : Expression2; disabled assertions the statement does nothing expressions are not evaluated enabled assertions Expression1 is true program continues normally Expression1 is false Expression2 is presented throw new AssertionError(Expression2) Expression2 is not presented throw new AssertionError() 3

Enabling and disabling arguments for the virtual machine enabling -ea[:packagename... :ClassName] -enableassertions[:packagename... :ClassName] disabling -da[:packagename... :ClassName] -disableassertions[:packagename... :ClassName] without class or package for all classes assertions in "system" classes -esa -enablesystemasserions -dsa -disablesystemasserions decision whether the assertions are enabled, is evaluated just once during initialization of a class (before anything is called/used on this class) 4

java.lang.assertionerror extends java.lang.error constructors AssertionError() AssertionError(boolean b) AssertionError(char c) AssertionError(double d) AssertionError(float f) AssertionError(int i) AssertionError(long l) AssertionError(Object o) 5

Examples invariants if (i%3 == 0) {... else if (i%3 == 1) {... else { assert i%3 == 2;... 6

Examples "unreachable places" in a program class Directions { public static final int RIGHT = 1; public static final int LEFT = 2;... switch(direction) { case Directions.LEFT:... case Directions.RIGHT:... default: assert false; 7

Examples preconditions testing arguments of private methods private void setinterval(int i) { assert i>0 && i<=max_interval;... unrecommended for testing arguments of public methods public void setinterval(int i) { if (i<=0 && i>max_interval) throw new IllegalArgumentException();... 8

Examples postconditions public String foo() { String ret;... assert ret!= null; return ret; 9

Java Generics 10

Introduction since Java 5 similar to the generics in C# typed arguments goal clear code type safety 11

Motivational example without generics (<=Java 1.4) List myintlist = new LinkedList(); myintlist.add(new Integer(0)); Integer x = (Integer) myintlist.iterator().next(); >= Java 5 List<Integer> myintlist = new LinkedList<Integer>(); myintlist.add(new Integer(0)); Integer x = myintlist.iterator().next(); no explicit casting type checks during compilation 12

Definition of generics public interface List<E> { void add(e x); Iterator<E> iterator(); E get(int i); public interface Iterator<E> { E next(); boolean hasnext(); List<Integer> can be seen as public interface IntegerList { void add(integer x); Iterator<Integer> iterator(); but in reality no such code exists 13

Compilation of gen. types to simplify during compilation, all information about generic types are erased "erasure" List<Integer> myintlist = new LinkedList<Integer>(); myintlist.add(new Integer(0)); Integer x = myintlist.iterator().next(); at runtime, it behaves as List myintlist = new LinkedList(); myintlist.add(new Integer(0)); Integer x = (Integer) myintlist.iterator().next(); 14

Compilation of gen. types always the same class, even if parametrized by anything LinkedList<String> LinkedList<Integer> LinkedList<Foo> just a single byte-code primitive types cannot be used as type parameters List<int> 15

New instances ArrayList<Integer> list = new ArrayList<Integer>(); ArrayList<ArrayList<Integer>> list2 = new ArrayList<ArrayList<Integer>>(); HashMap<String, ArrayList<ArrayList<Integer>>> h = new HashMap<String, ArrayList<ArrayList<Integer>>>(); since Java 7 ( diamond operator) ArrayList<Integer> list = new ArrayList<>(); ArrayList<ArrayList<Integer>> list2 = new ArrayList<>(); HashMap<String, ArrayList<ArrayList<Integer>>> h = new HashMap<>(); 16

Type relations no changes in typed arguments are allowed List<String> ls = new ArrayList<String>(); List<Object> lo = ls; lo.add(new Object()); String s = ls.get(0); error assigning Object to String second line causes compilation error 17

Type relations example printing all elements in a collection <= Java 1.4 void printcollection(collection c) { Iterator i = c.iterator(); for (k = 0; k < c.size(); k++) { System.out.println(i.next()); naive attempt in Java 5 void printcollection(collection<object> c) { for (Object e : c) { System.out.println(e); does not work (see the previous example) 18

Type relations Collection<Object> is not supertype of all collections correctly void printcollection(collection<?> c) { for (Object e : c) { System.out.println(e); Collection<?> is supertype of all collections collection of unknown any collection can be assigned there BUT to Collection<?> nothing can be added Collection<?> c = new ArrayList<String>(); c.add(new Object()); <= compilation error get() can be called return type is Object 19

Type relations? - wildcard bounded wildcard public abstract class Shape { public abstract void draw(canvas c); public class Circle extends Shape {... public class Canvas { public void drawall(list<shape> shapes) { for (Shape s:shapes) { s.draw(this) can draw lists of the type List<Shape> only but not e.g. List<Circle> 20

Type relations solution bounded? public void drawall(list<? extends Shape> shapes){ for (Shape s:shapes) { s.draw(this) but still you cannot add to this List shapes.add(0, new Rectangle()); compilation error 21

Generic methods static void fromarraytocollection(object[] a, Collection<?> c) { for (Object o : a) { c.add(o); compilation error static <T> void fromarraytocollection(t[] a, Collection<T> c) { for (T o : a) { c.add(o); OK 22

Generic methods usage the compiler determines actual types automatically Object[] oa = new Object[100]; Collection<Object> co = new ArrayList<Object>(); fromarraytocollection(oa, co); // T Object String[] sa = new String[100]; Collection<String> cs = new ArrayList<String>(); fromarraytocollection(sa, cs); // T String fromarraytocollection(sa, co); // T Object bounds can be used with methods also class Collections { public static <T> void copy(list<t> dest, List<? extends T> src){... 23

Array and generics array of generics can be declared cannot be instantiated List<String>[] lsa = new List<String>[10]; wrong List<?>[] lsa = new List<?>[10]; OK + warning why? arrays can be cast to Object List<String>[] lsa = new List<String>[10]; Object[] oa = (Object[]) lsa; List<Integer> li = new ArrayList<Integer>(); li.add(new Integer(3)); oa[1] = li; String s = lsa[1].get(0); ClassCastException 24

Old and new code old code without generics public class Foo { public void add(list lst) {... public List get() {... new code that uses the old one List<String> lst1 = new ArrayList<String>(); Foo o = new Foo(); o.add(lst1); OK - List corresponds to List<?> List<String> lst2 = o.get(); compilation warning 25

Old and new code new code with generics public class Foo { public void add(list<string> lst) {... public List<String> get() {... old code that uses the new one List lst1 = new ArrayList(); Foo o = new Foo(); o.add(lst1); compilation warning List lst2 = o.get(); OK - List corresponds to List<?> 26

Additional type relations class Collections { public static <T> void copy(list<t> dest, List<? extends T> src){... actual declaration is class Collections { public static <T> void copy(list<? super T> dest, List<? extends T> src){... 27

Java Enum 28

Enumerations <= Java 1.4 public static final int COLOR_BLUE = 0; public static final int COLOR_RED = 1; public static final int COLOR_GREEN = 2; possible problems type (un)safety no namespace constants hard-compiled in clients only numbers when printed 29

Enum public enum Color { BLUE, RED, GREEN... public Color clr = Color.BLUE; normal class can have fields, methods, even the main method subclass of java.lang.enum for each value single instance public static final field protected constructor 30

Enum without enum how to implement enum in Java 1.4 (and how enums are implemented) class Color { private int value; public static final Color RED = new Color(0); public static final Color GREEN = new Color(1); public static final Color BLUE = new Color(2); protected Color(int v) { value = v;... 31

java.lang.enum public abstract class Enum <E extends Enum<E>> {... methods String name() int ordinal() each enum has the method values() returns an array with all enum's values public Colors clr = Colors.BLUE; System.out.println(clr); BLUE 32

Fields and methods public enum Planet { MERCURY (3.303e+23, 2.4397e6), VENUS (4.869e+24, 6.0518e6), EARTH (5.976e+24, 6.37814e6),... private final double mass; private final double radius; Planet(double mass, double radius){ this.mass = mass; this.radius = radius; double surfacegravity() { return G * mass / (radius * radius); 33

Fields and methods example public enum Operation { PLUS, MINUS, TIMES, DIVIDE; double eval(double x, double y){ switch(this) { case PLUS: return x + y; case MINUS: return x - y; case TIMES: return x * y; case DIVIDE: return x / y; throw new AssertionError("Unknown op: " + this); 34

Fields and methods abstract methods particular implementations with each of the values public enum Operation { PLUS { double eval(double x, double y) { return x+y;, MINUS { double eval(double x, double y) { return x-y;, TIMES { double eval(double x, double y) { return x*y;, DIVIDE { double eval(double x, double y) { return x/y;; abstract double eval(double x, double y); 35

Java Variable number of arguments 36

... three dots only as the last argument either an array or list of arguments can be passed in the method, available as an array void argtest(object... args) { for (int i=0;i <args.length; i++) { System.out.println(args[i]); argtest("hello", "how", "are", "you"); argtest(new Object[] {"Hello", "how", "are", "you"); methods printf System.out.printf("%s %d\n", user, total); 37

Test Are the calls equivalent? argtest("ahoj", "jak", "se", "vede"); argtest(new Object[] {"Ahoj", "jak", "se", "vede"); argtest((object) new Object[] {"Ahoj", "jak", "se", "vede"); a) Yes, all of them b) Only 1. and 2. c) Only 2. and 3. d) Each of them will print something different 38

Java, winter Slides semester version 2016 J04.en.2016.01 This slides are licensed under a Creative Commons Attribution-NonCommercial 4.0 International License. 39