Principles of So3ware Construc9on: Objects, Design, and Concurrency. Introduc9on to Java. Josh Bloch Charlie Garrod Darya Melicher

Size: px
Start display at page:

Download "Principles of So3ware Construc9on: Objects, Design, and Concurrency. Introduc9on to Java. Josh Bloch Charlie Garrod Darya Melicher"

Transcription

1 Principles of So3ware Construc9on: Objects, Design, and Concurrency Introduc9on to Java Josh Bloch Charlie Garrod Darya Melicher 1

2 Administrivia Homework 1 due next Thursday 11:59 p.m. Everyone must read and sign our collabora9on policy First reading assignment due Tuesday Effec9ve Java Items 15 and 16 2

3 Outline I. Hello World! explained II. The type system III. Quick n dirty I/O IV. Collec9ons V. Methods common to all Objects 3

4 The simplest Java Program class HelloWorld { public static void main(string[] args) { System.out.println("Hello world!"); 4

5 Complica9on 1: you must use a class even if you aren t doing OO programming class HelloWorld { public static void main(string[] args) { System.out.println("Hello world!"); 5

6 Complica9on 2: main must be public class HelloWorld { public static void main(string[] args) { System.out.println("Hello world!"); 6

7 Complica9on 3: main must be static class HelloWorld { public static void main(string[] args) { System.out.println("Hello world!"); 7

8 Complica9on 4: main must return void class HelloWorld { public static void main(string[] args) { System.out.println("Hello world!"); 8

9 Complica9on 5: main must declare command line arguments even if unused class HelloWorld { public static void main(string[] args) { System.out.println("Hello world!"); 9

10 Complica9on 6: standard I/O requires use of static field of System class HelloWorld { public static void main(string[] args) { System.out.println("Hello world!"); 10

11 Execu9on is a bit complicated First you compile the source file javac HelloWorld.java Produces class file HelloWorld.class Then you launch the program java HelloWorld Java Virtual Machine (JVM) executes main method 11

12 On the bright side Has many good points to balance shortcomings Some verbosity is not a bad thing Can reduce errors and increase readability Modern IDEs eliminate much of the pain Type psvm instead of public static void main Managed run9me has many advantages Safe, flexible, enables garbage collec9on It may not be best language for Hello World But Java is very good for large-scale programming! 12

13 Outline I. Hello World! explained II. The type system III. Quick n dirty I/O IV. Collec9ons V. Methods common to all Objects 13

14 Java type system has two parts Primi/ves int, long, byte, short, char, float, double, boolean No iden9ty except their value Immutable On stack, exist only when in use Object Reference Types Classes, interfaces, arrays, enums, annota9ons Have iden9ty dis9nct from value Some mutable, some not On heap, garbage collected Can t achieve unity of expression Unity of expression with generics Dirt cheap More costly 14

15 Programming with primi9ves A lot like C! public class TrailingZeros { public static void main(string[] args) { int i = Integer.parseInt(args[0]); System.out.println(trailingZerosInFactorial(i)); static int trailingzerosinfactorial(int i) { int result = 0; // Conventional name for return value while (i >= 5) { i /= 5; result += i; return result; // Same as i = i / 5; Remainder discarded 15

16 Primi9ve type summary int 32-bit signed integer long 64-bit signed integer byte 8-bit signed integer short 16-bit signed integer char 16-bit unsigned integer/character float 32-bit IEEE 754 floa9ng point number double 64-bit IEEE 754 floa9ng point number boolean Boolean value: true or false 16

17 Deficient primi9ve types byte, short use int instead! byte is broken should have been unsigned float use double instead! Provides too lijle precision Only compelling use case is large arrays, especially in resource-constrained environments 17

18 The class hierarchy The root is Object (all non-primi9ves are objects) All classes except Object have one parent class Specified with an extends clause class Guitar extends Instrument {... If extends clause omijed, defaults to Object A class is an instance of all its superclasses Object Instrument Toy Guitar Yoyo 18

19 Implementa9on inheritance A class: Inherits visible fields and methods from its superclasses Can override methods to change their behavior Overriding method implementa9on must obey contract(s) of its superclass(es) Ensures subclass can be used anywhere superclass can Liskov Subs9tu9on Principle (LSP) 19

20 Interface types Defines a type without an implementa9on Much more flexible than class types An interface can extend one or more others A class can implement mul9ple interfaces interface Comparable<T> { /** * Returns a negative number, 0, or a positive number as this * object is less than, equal to, or greater than other. */ int compareto(t other); 20

21 Enum types Java has object-oriented enums In simple form, they look just like C enums: enum Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE But they have many advantages! Compile-9me type safety Mul9ple enum types can share value names Can add or reorder without breaking exis9ng uses High-quality Object methods are provided Screaming fast collec9ons (EnumSet, EnumMap) Can iterate over all constants of an enum 21

22 Boxed primi9ves Immutable containers for primi9ve types Boolean, Integer, Short, Long, Character, Float, Double Lets you use primi9ves in contexts requiring objects Canonical use case is collec/ons Don t use boxed primi/ves unless you have to! Language does autoboxing and auto-unboxing Blurs but does not eliminate dis9nc9on There be dragons! 22

23 Pop Quiz! 23

24 What does this fragment print? int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ; int i; int sum1 = 0; for (i = 0; i < a.length; i++) { sum1 += a[i]; int j; int sum2 = 0; for (j = 0; i < a.length; j++) { sum2 += a[j]; System.out.println(sum1 - sum2); 24

25 Maybe not what you expect! int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ; int i; int sum1 = 0; for (i = 0; i < a.length; i++) { sum1 += a[i]; int j; int sum2 = 0; for (j = 0; i < a.length; j++) { // Copy/paste error! sum2 += a[j]; System.out.println(sum1 - sum2); You might expect it to print 0, but it prints 55 25

26 You could fix it like this int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ; int i; int sum1 = 0; for (i = 0; i < a.length; i++) { sum1 += a[i]; int j; int sum2 = 0; for (j = 0; j < a.length; j++) { sum2 += a[j]; System.out.println(sum1 - sum2); // Now prints 0, as expected 26

27 But this fix is far bejer int sum1 = 0; for (int i = 0; i < a.length; i++) { sum1 += a[i]; int sum2 = 0; for (int i = 0; i < a.length; i++) { sum2 += a[i]; System.out.println(sum1 - sum2); // Prints 0 Reduces scope of index variable to loop Shorter and less error prone 27

28 This fix is bejer s9ll! int sum1 = 0; for (int x : a) { sum1 += x; int sum2 = 0; for (int x : a) { sum2 += x; System.out.println(sum1 - sum2); // Prints 0 Eliminates scope of index variable en/rely! Even shorter and less error prone 28

29 Lessons from the quiz Minimize scope of local variables [EJ Item 57] Declare variables at point of use Ini9alize variables in declara9on Use common idioms Watch out for bad smells in code Such as index variable declared outside loop 29

30 Outline I. Hello World! explained II. The type system III. Quick n dirty I/O IV. Collec9ons V. Methods common to all Objects 30

31 Output Unformajed System.out.println("Hello World"); System.out.println("Radius: " + r); System.out.println(r * Math.cos(theta)); System.out.println(); System.out.print("*"); Formajed System.out.printf("%d * %d = %d%n", a, b, a * b); // Varargs 31

32 Command line input example Echos all command line arguments class Echo { public static void main(string[] args) { for (String arg : args) { System.out.print(arg + " "); $ java Echo Woke up this morning, had them weary blues Woke up this morning, had them weary blues 32

33 Command line input with parsing Prints GCD of two command line arguments class Gcd { public static void main(string[] args) { int i = Integer.parseInt(args[0]); int j = Integer.parseInt(args[1]); System.out.println(gcd(i, j)); static int gcd(int i, int j) { return i == 0? j : gcd(j % i, i); $ java Gcd

34 Scanner input Counts the words on standard input class Wc { public static void main(string[] args) { Scanner sc = new Scanner(System.in); long result = 0; while (sc.hasnext()) { sc.next(); // Swallow token result++; System.out.println(result); $ java Wc < Wc.java 32 34

35 Outline I. Hello World! explained II. The type system III. Quick n dirty I/O IV. Collec9ons V. Methods common to all Objects 35

36 Primary collec9on interfaces Collection Map Set List Queue Deque 36

37 Primary collec9on implementa9ons Interface Set List Queue Deque [stack] Map Implementa/on HashSet ArrayList ArrayDeque ArrayDeque ArrayDeque HashMap 37

38 Other noteworthy collec9on impls Interface Set Queue Map Implementa/on(s) LinkedHashSet TreeSet EnumSet PriorityQueue LinkedHashMap TreeMap EnumMap 38

39 Collec9ons usage example 1 Squeeze duplicate words out of command line public class Squeeze { public static void main(string[] args) { Set<String> s = new LinkedHashSet<>(); for (String word : args) s.add(word); System.out.println(s); $ java Squeeze I came I saw I conquered [I, came, saw, conquered] 39

40 Collec9ons usage example 2 Print unique words in lexicographic order public class Lexicon { public static void main(string[] args) { Set<String> s = new TreeSet<>(); for (String word : args) s.add(word); System.out.println(s); $ java Lexicon I came I saw I conquered [I, came, conquered, saw] 40

41 Collec9ons usage example 3 Print index of first occurrence of each word class Index { public static void main(string[] args) { Map<String, Integer> index = new TreeMap<>(); // Iterate backwards so first occurrence wins for (int i = args.length - 1; i >= 0; i--) { index.put(args[i], i); System.out.println(index); $ java java Index if it is to be it is up to me to do it {be=4, do=11, if=0, is=2, it=1, me=9, to=3, up=7 41

42 More informa9on on collec9ons For much more informa9on on collec9ons, see the annotated outline: hjps://docs.oracle.com/javase/8/docs/technotes /guides/collec9ons/reference.html For more info on any library class, see javadoc Search web for <fully qualified class name> 8 e.g., java.util.scanner 8 42

43 What about arrays? Arrays aren t really a part of the collec9ons framework But there is an adapter: Arrays.asList Arrays and collec9ons don t mix Arrays are covariant and reified Generics are nonvariant and erased If you try to mix them and get compiler warnings, take them seriously Generally speaking, prefer collec9ons to arrays See Effec;ve Java Item 28 for details 43

44 Outline I. Hello World! explained II. The type system III. Quick n dirty I/O IV. Collec9ons V. Methods common to all Objects 44

45 Methods common to all objects How do collec9ons know how to test objects for equality? How do they know how to hash and print them? The relevant methods are all present on Object equals - returns true if the two objects are equal hashcode - returns an int that must be equal for equal objects, and is likely to differ on unequal objects tostring - returns a printable string representa9on 45

46 Object implementa9ons Provide iden;ty seman;cs equals(object o) returns true if o refers to this object hashcode() returns a near-random int that never changes over the object life9me tostring() returns a nasty looking string consis9ng of the type and hash code For example: java.lang.object@659e0bfd 46

47 Overriding Object implementa9ons No need to override equals and hashcode if you want iden/ty seman/cs When in doubt, don t override them It s easy to get it wrong Nearly always override tostring println invokes it automa9cally Why sejle for ugly? 47

48 Overriding tostring Overriding tostring is easy and beneficial final class PhoneNumber { private final short areacode; private final short prefix; private final short public String tostring() { return String.format("%03d-%03d-%04d", areacode, prefix, linenumber); Number jenny =...; System.out.println(jenny); Prints:

49 Overriding equals Overriding equals is tricky here s the contract The equals method implements an equivalence rela/on. It is: Reflexive: For any non-null reference value x, x.equals(x) must return true. Symmetric: For any non-null reference values x and y, x.equals(y) must return true if and only if y.equals(x) returns true. Transi/ve: For any non-null reference values x, y, z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) must return true. Consistent: For any non-null reference values x and y, mul9ple invoca9ons of x.equals(y) consistently return true or consistently return false, provided no informa9on used in equals comparisons on the objects is modified. For any non-null reference value x, x.equals(null) must return false. 49

50 Overriding hashcode Overriding hashcode also tricky here s contract Whenever it is invoked on the same object more than once during an execu9on of an applica9on, the hashcode method must consistently return the same integer, provided no informa9on used in equals comparisons on the object is modified. This integer need not remain consistent from one execu9on of an applica9on to another execu9on of the same applica9on. If two objects are equal according to the equals(object) method, then calling the hashcode method on each of the two objects must produce the same integer result. It is not required that if two objects are unequal according to the equals(object) method, then calling the hashcode method on each of the two objects must produce dis9nct integer results. However, the programmer should be aware that producing dis9nct integer results for unequal objects may improve the performance of hash tables. 50

51 Why the contracts majer No class is an island If you put an object with a broken equals or hashcode into a collec9on, the collec9on breaks! Arbitrary behavior may result! System may generate incorrect results or crash To build a new value type, you must override equals and hashcode Next lecture we ll show you how 51

52 Summary Java is well suited to large programs; small ones may seem a bit verbose Bipar9te type system primi9ves & object refs Single implementa9on inheritance Mul9ple interface inheritance A few simple I/O techniques will get you started Collec9ons framework is powerful & easy to use 52

Charlie Garrod Bogdan Vasilescu

Charlie Garrod Bogdan Vasilescu Principles of So3ware Construc9on: Objects, Design, and Concurrency Part 1: Design for change (class level) Introduc9on to Java + Design for change: Informa9on hiding Charlie Garrod Bogdan Vasilescu School

More information

Charlie Garrod Michael Hilton

Charlie Garrod Michael Hilton Principles of So3ware Construc9on: Objects, Design, and Concurrency Part 1: Designing classes Behavioral subtyping Charlie Garrod Michael Hilton School of Computer Science 1 Administrivia Homework 1 due

More information

The class Object. Lecture CS1122 Summer 2008

The class Object.  Lecture CS1122 Summer 2008 The class Object http://www.javaworld.com/javaworld/jw-01-1999/jw-01-object.html Lecture 10 -- CS1122 Summer 2008 Review Object is at the top of every hierarchy. Every class in Java has an IS-A relationship

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 36 April 23, 2014 Overriding and Equality HW 10 has a HARD deadline Announcements You must submit by midnight, April 30 th Demo your project to your

More information

Principles of Software Construction: Objects, Design, and Concurrency. Testing and Object Methods in Java. Josh Bloch Charlie Garrod Darya Melicher

Principles of Software Construction: Objects, Design, and Concurrency. Testing and Object Methods in Java. Josh Bloch Charlie Garrod Darya Melicher Principles of Software Construction: Objects, Design, and Concurrency Testing and Object Methods in Java Josh Bloch Charlie Garrod Darya Melicher 1 Administrivia Homework 1 due Today 11:59 p.m. Everyone

More information

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff Collections by Vlad Costel Ungureanu for Learn Stuff Collections 2 Collections Operations Add objects to the collection Remove objects from the collection Find out if an object (or group of objects) is

More information

Josh Bloch Charlie Garrod Darya Melicher

Josh Bloch Charlie Garrod Darya Melicher Principles of So3ware Construc9on: Objects, Design, and Concurrency Part 2: Class-level design Behavioral subtyping, design for reuse Josh Bloch Charlie Garrod Darya Melicher 1 Administrivia Homework 1

More information

Overloaded Methods. Sending Messages. Overloaded Constructors. Sending Parameters

Overloaded Methods. Sending Messages. Overloaded Constructors. Sending Parameters Overloaded Methods Sending Messages Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Initialization & Cleanup 2 Overloaded Constructors Sending Parameters accessor method 3 4 Sending Parameters

More information

Garbage collec,on Parameter passing in Java. Sept 21, 2016 Sprenkle - CSCI Assignment 2 Review. public Assign2(int par) { onevar = par; }

Garbage collec,on Parameter passing in Java. Sept 21, 2016 Sprenkle - CSCI Assignment 2 Review. public Assign2(int par) { onevar = par; } Objec,ves Inheritance Ø Overriding methods Garbage collec,on Parameter passing in Java Sept 21, 2016 Sprenkle - CSCI209 1 Assignment 2 Review private int onevar; public Assign2(int par) { onevar = par;

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 28 March 30, 2016 Collections and Equality Chapter 26 Announcements Dr. Steve Zdancewic is guest lecturing today He teaches CIS 120 in the Fall Midterm

More information

Getting started with Java

Getting started with Java Getting started with Java by Vlad Costel Ungureanu for Learn Stuff Programming Languages A programming language is a formal constructed language designed to communicate instructions to a machine, particularly

More information

17 Hello world 18 Type: String: literal 19 Standard API: System: out.println() 20 Hello world 21 Statement 22 Statement: simple statements are ended w

17 Hello world 18 Type: String: literal 19 Standard API: System: out.println() 20 Hello world 21 Statement 22 Statement: simple statements are ended w List of Slides 1 Title 2 Chapter 2: Sequential execution and program errors 3 Chapter aims 4 Section 2: Example:Hello world 5 Aim 6 Class: programs are divided into classes 7 Class: public class 8 Class:

More information

Chapter 11: Collections and Maps

Chapter 11: Collections and Maps Chapter 11: Collections and Maps Implementing the equals(), hashcode() and compareto() methods A Programmer's Guide to Java Certification (Second Edition) Khalid A. Mughal and Rolf W. Rasmussen Addison-Wesley,

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 31 April 3, 2013 Overriding, Equality, and Casts Announcements HW 09 due Tuesday at midnight More informajon about exam 2 available on Friday Unfinished

More information

Objec&ves. Packages Collec&ons Generics. Sept 28, 2016 Sprenkle - CSCI209 1

Objec&ves. Packages Collec&ons Generics. Sept 28, 2016 Sprenkle - CSCI209 1 Objec&ves Packages Collec&ons Generics Sept 28, 2016 Sprenkle - CSCI209 1 PACKAGES Sept 28, 2016 Sprenkle - CSCI209 2 Packages Hierarchical structure of Java classes Ø Directories of directories java lang

More information

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000 The Object Class Mark Allen Weiss Copyright 2000 1/4/02 1 java.lang.object All classes either extend Object directly or indirectly. Makes it easier to write generic algorithms and data structures Makes

More information

Why OO programming? want but aren t. Ø What are its components?

Why OO programming? want but aren t. Ø What are its components? 9/21/15 Objec,ves Assign 1 Discussion Object- oriented programming in Java Java Conven,ons: Ø Constructors Ø Default constructors Ø Sta,c methods, variables Ø Inherited methods Ø Class names: begin with

More information

History of Java. Java was originally developed by Sun Microsystems star:ng in This language was ini:ally called Oak Renamed Java in 1995

History of Java. Java was originally developed by Sun Microsystems star:ng in This language was ini:ally called Oak Renamed Java in 1995 Java Introduc)on History of Java Java was originally developed by Sun Microsystems star:ng in 1991 James Gosling Patrick Naughton Chris Warth Ed Frank Mike Sheridan This language was ini:ally called Oak

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 21 October 21 st, 2015 Transi@on to Java Announcements HW5: GUI & Paint Due Tomorrow, October 22 nd at 11:59pm HW6: Java Programming (Pennstagram)

More information

For this section, we will implement a class with only non-static features, that represents a rectangle

For this section, we will implement a class with only non-static features, that represents a rectangle For this section, we will implement a class with only non-static features, that represents a rectangle 2 As in the last lecture, the class declaration starts by specifying the class name public class Rectangle

More information

List of Slides 1 Title 2 Chapter 2: Sequential execution and program errors 3 Chapter aims 4 Section 2: Example:Hello world 5 Aim 6 Class: programs ar

List of Slides 1 Title 2 Chapter 2: Sequential execution and program errors 3 Chapter aims 4 Section 2: Example:Hello world 5 Aim 6 Class: programs ar List of Slides 1 Title 2 Chapter 2: Sequential execution and program errors 3 Chapter aims 4 Section 2: Example:Hello world 5 Aim 6 Class: programs are divided into classes 7 Class: public class 8 Class:

More information

java.lang.object: Equality

java.lang.object: Equality java.lang.object: Equality Computer Science and Engineering College of Engineering The Ohio State University Lecture 14 Class and Interface Hierarchies extends Object Runable Cloneable implements SmartPerson

More information

Condi(onals and Loops

Condi(onals and Loops Condi(onals and Loops 1 Review Primi(ve Data Types & Variables int, long float, double boolean char String Mathema(cal operators: + - * / % Comparison: < > = == 2 A Founda(on for Programming any program

More information

Creating an Immutable Class. Based on slides by Prof. Burton Ma

Creating an Immutable Class. Based on slides by Prof. Burton Ma Creating an Immutable Class Based on slides by Prof. Burton Ma 1 Value Type Classes A value type is a class that represents a value Examples of values: name, date, colour, mathematical vector Java examples:

More information

CS 11 java track: lecture 1

CS 11 java track: lecture 1 CS 11 java track: lecture 1 Administrivia need a CS cluster account http://www.cs.caltech.edu/ cgi-bin/sysadmin/account_request.cgi need to know UNIX www.its.caltech.edu/its/facilities/labsclusters/ unix/unixtutorial.shtml

More information

Inheritance and delega9on

Inheritance and delega9on Principles of So3ware Construc9on: Objects, Design, and Concurrency Designing classes Inheritance and delega9on Josh Bloch Charlie Garrod School of Computer Science 1 Administrivia Homework 2 due tonight

More information

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University Lecture 2 COMP1406/1006 (the Java course) Fall 2013 M. Jason Hinek Carleton University today s agenda a quick look back (last Thursday) assignment 0 is posted and is due this Friday at 2pm Java compiling

More information

DAD Lab. 1 Introduc7on to C#

DAD Lab. 1 Introduc7on to C# DAD 2017-18 Lab. 1 Introduc7on to C# Summary 1..NET Framework Architecture 2. C# Language Syntax C# vs. Java vs C++ 3. IDE: MS Visual Studio Tools Console and WinForm Applica7ons 1..NET Framework Introduc7on

More information

Super-Classes and sub-classes

Super-Classes and sub-classes Super-Classes and sub-classes Subclasses. Overriding Methods Subclass Constructors Inheritance Hierarchies Polymorphism Casting 1 Subclasses: Often you want to write a class that is a special case of an

More information

Architecture of so-ware systems

Architecture of so-ware systems Architecture of so-ware systems Lecture 13: Class/object ini

More information

Josh Bloch Charlie Garrod Darya Melicher

Josh Bloch Charlie Garrod Darya Melicher Principles of So3ware Construc9on: Objects, Design, and Concurrency A puzzling finale: What you see is what you get? Josh Bloch Charlie Garrod Darya Melicher 1 Administrivia Final exam review session:

More information

equals() in the class Object

equals() in the class Object equals() in the class Object 1 The Object class implements a public equals() method that returns true iff the two objects are the same object. That is: x.equals(y) == true iff x and y are (references to)

More information

Programming Languages and Techniques (CIS120e)

Programming Languages and Techniques (CIS120e) Programming Languages and Techniques (CIS120e) Lecture 33 Dec. 1, 2010 Equality Consider this example public class Point {! private final int x; // see note about final*! private final int y;! public Point(int

More information

Programming Language Concepts: Lecture 2

Programming Language Concepts: Lecture 2 Programming Language Concepts: Lecture 2 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in http://www.cmi.ac.in/~madhavan/courses/pl2011 PLC 2011, Lecture 2, 6 January 2011 Classes and

More information

Objec+ves. Review. Basics of Java Syntax Java fundamentals. What are quali+es of good sooware? What is Java? How do you compile a Java program?

Objec+ves. Review. Basics of Java Syntax Java fundamentals. What are quali+es of good sooware? What is Java? How do you compile a Java program? Objec+ves Basics of Java Syntax Java fundamentals Ø Primi+ve data types Ø Sta+c typing Ø Arithme+c operators Ø Rela+onal operators 1 Review What are quali+es of good sooware? What is Java? Ø Benefits to

More information

Object-Oriented Programming in the Java language

Object-Oriented Programming in the Java language Object-Oriented Programming in the Java language Part 6. Collections(1/2): Lists. Yevhen Berkunskyi, NUoS eugeny.berkunsky@gmail.com http://www.berkut.mk.ua Just before we start Generics Generics are a

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 32 April 5, 2013 Equality and Hashing When to override: Equality Consider this example public class Point { private final int x; private final int

More information

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

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg Ad hoc-polymorphism Outline Method overloading Sub-type Polymorphism Method overriding Dynamic

More information

Core Java Syllabus. Overview

Core Java Syllabus. Overview Core Java Syllabus Overview Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Language Features. 1. The primitive types int, double, and boolean are part of the AP Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are

More information

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content Core Java - SCJP Course content NOTE: For exam objectives refer to the SCJP 1.6 objectives. 1. Declarations and Access Control Java Refresher Identifiers & JavaBeans Legal Identifiers. Sun's Java Code

More information

COMP 250 Fall inheritance Nov. 17, 2017

COMP 250 Fall inheritance Nov. 17, 2017 Inheritance In our daily lives, we classify the many things around us. The world has objects like dogs and cars and food and we are familiar with talking about these objects as classes Dogs are animals

More information

Methods Common to all Classes

Methods Common to all Classes Methods Common to all Classes 9-2-2013 OOP concepts Overloading vs. Overriding Use of this. and this(); use of super. and super() Methods common to all classes: tostring(), equals(), hashcode() HW#1 posted;

More information

Principles of Software Construction: Objects, Design, and Concurrency

Principles of Software Construction: Objects, Design, and Concurrency Principles of Software Construction: Objects, Design, and Concurrency Part 3: Design case studies Performance Charlie Garrod Michael Hilton School of Computer Science 1 Administriva Homework 4b due Thursday,

More information

Effec%ve So*ware. Lecture 9: JVM - Memory Analysis, Data Structures, Object Alloca=on. David Šišlák

Effec%ve So*ware. Lecture 9: JVM - Memory Analysis, Data Structures, Object Alloca=on. David Šišlák Effec%ve So*ware Lecture 9: JVM - Memory Analysis, Data Structures, Object Alloca=on David Šišlák david.sislak@fel.cvut.cz JVM Performance Factors and Memory Analysis» applica=on performance factors total

More information

Inheritance (Part 5) Odds and ends

Inheritance (Part 5) Odds and ends Inheritance (Part 5) Odds and ends 1 Static Methods and Inheritance there is a significant difference between calling a static method and calling a non-static method when dealing with inheritance there

More information

Outline. Object Oriented Programming. Course goals. Staff. Course resources. Assignments. Course organization Introduction Java overview Autumn 2003

Outline. Object Oriented Programming. Course goals. Staff. Course resources. Assignments. Course organization Introduction Java overview Autumn 2003 Outline Object Oriented Programming Autumn 2003 2 Course goals Software design vs hacking Abstractions vs language (syntax) Java used to illustrate concepts NOT a course about Java Prerequisites knowledge

More information

Genericity. Philippe Collet. Master 1 IFI Interna3onal h9p://dep3nfo.unice.fr/twiki/bin/view/minfo/sofeng1314. P.

Genericity. Philippe Collet. Master 1 IFI Interna3onal h9p://dep3nfo.unice.fr/twiki/bin/view/minfo/sofeng1314. P. Genericity Philippe Collet Master 1 IFI Interna3onal 2013-2014 h9p://dep3nfo.unice.fr/twiki/bin/view/minfo/sofeng1314 P. Collet 1 Agenda Introduc3on Principles of parameteriza3on Principles of genericity

More information

The plan. Racket will return! Lecture will not recount every single feature of Java. Final project will be wri)ng a Racket interpreter in Java.

The plan. Racket will return! Lecture will not recount every single feature of Java. Final project will be wri)ng a Racket interpreter in Java. Introduc)on to Java The plan Racket will return! Final project will be wri)ng a Racket interpreter in Java. Lecture will not recount every single feature of Java. You may need to do some digging on your

More information

Course information. Petr Hnětynka 2/2 Zk/Z

Course information. Petr Hnětynka  2/2 Zk/Z JAVA Introduction Course information Petr Hnětynka hnetynka@d3s.mff.cuni.cz http://d3s.mff.cuni.cz/~hnetynka/java/ 2/2 Zk/Z exam written test zápočet practical test in the lab max 5 attempts zápočtový

More information

Java Programming Unit 8. Selected Java Collec5ons. Generics.

Java Programming Unit 8. Selected Java Collec5ons. Generics. Java Programming Unit 8 Selected Java Collec5ons. Generics. Java Collec5ons Framework Classes and interfaces from packages java.util and java.util.concurrent are called Java Collec5ons Framework. java.u5l:

More information

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I BASIC COMPUTATION x public static void main(string [] args) Fundamentals of Computer Science I Outline Using Eclipse Data Types Variables Primitive and Class Data Types Expressions Declaration Assignment

More information

Programming Language Concepts: Lecture 2

Programming Language Concepts: Lecture 2 Programming Language Concepts: Lecture 2 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in http://www.cmi.ac.in/~madhavan/courses/pl2009 PLC 2009, Lecture 2, 19 January 2009 Classes and

More information

CSC 1351: Final. The code compiles, but when it runs it throws a ArrayIndexOutOfBoundsException

CSC 1351: Final. The code compiles, but when it runs it throws a ArrayIndexOutOfBoundsException VERSION A CSC 1351: Final Name: 1 Interfaces, Classes and Inheritance 2 Basic Data Types (arrays, lists, stacks, queues, trees,...) 2.1 Does the following code compile? If it does not, how can it be fixed?

More information

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors Agenda

More information

PIC 20A Collections and Data Structures

PIC 20A Collections and Data Structures PIC 20A Collections and Data Structures Ernest Ryu UCLA Mathematics Last edited: March 14, 2018 Introductory example How do you write a phone book program? Some programmers may yell hash table! and write

More information

C12a: The Object Superclass and Selected Methods

C12a: The Object Superclass and Selected Methods CISC 3115 TY3 C12a: The Object Superclass and Selected Methods Hui Chen Department of Computer & Information Science CUNY Brooklyn College 10/4/2018 CUNY Brooklyn College 1 Outline The Object class and

More information

CMSC 132: Object-Oriented Programming II. Effective Java. Department of Computer Science University of Maryland, College Park

CMSC 132: Object-Oriented Programming II. Effective Java. Department of Computer Science University of Maryland, College Park CMSC 132: Object-Oriented Programming II Effective Java Department of Computer Science University of Maryland, College Park Effective Java Textbook Title Effective Java, Second Edition Author Joshua Bloch

More information

Introduction to Object-Oriented Programming

Introduction to Object-Oriented Programming Introduction to Object-Oriented Programming Object-Oriented Programming, Part 2 of 3 Christopher Simpkins chris.simpkins@gatech.edu CS 1331 (Georgia Tech) Object-Oriented Programming, Part 2 of 3 1 / 16

More information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

CS11 Java. Fall Lecture 1

CS11 Java. Fall Lecture 1 CS11 Java Fall 2006-2007 Lecture 1 Welcome! 8 Lectures Slides posted on CS11 website http://www.cs.caltech.edu/courses/cs11 7-8 Lab Assignments Made available on Mondays Due one week later Monday, 12 noon

More information

USAL1J: Java Collections. S. Rosmorduc

USAL1J: Java Collections. S. Rosmorduc USAL1J: Java Collections S. Rosmorduc 1 A simple collection: ArrayList A list, implemented as an Array ArrayList l= new ArrayList() l.add(x): adds x at the end of the list l.add(i,x):

More information

An overview of Java, Data types and variables

An overview of Java, Data types and variables An overview of Java, Data types and variables Lecture 2 from (UNIT IV) Prepared by Mrs. K.M. Sanghavi 1 2 Hello World // HelloWorld.java: Hello World program import java.lang.*; class HelloWorld { public

More information

1.1 Your First Program

1.1 Your First Program 1.1 Your First Program Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2002 2010 5/20/2013 9:37:22 AM Why Programming? Why programming? Need

More information

! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat.

! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat. Why Java? Lecture 2: Intro to Java Java features.! Widely available.! Widely used.! Variety of automatic checks for mistakes in programs.! Embraces full set of modern abstractions. Caveat.! No perfect

More information

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8 Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(

More information

Josh Bloch Charlie Garrod Darya Melicher

Josh Bloch Charlie Garrod Darya Melicher Principles of Software Construction: Objects, Design, and Concurrency Concurrency part 2 Synchronization, communication, and liveness Josh Bloch Charlie Garrod Darya Melicher 1 Administrivia Reading due

More information

CS121/IS223. Object Reference Variables. Dr Olly Gotel

CS121/IS223. Object Reference Variables. Dr Olly Gotel CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors CS121/IS223

More information

Canonical Form. No argument constructor Object Equality String representation Cloning Serialization Hashing. Software Engineering

Canonical Form. No argument constructor Object Equality String representation Cloning Serialization Hashing. Software Engineering CSC40232: SOFTWARE ENGINEERING Professor: Jane Cleland Huang Canonical Form sarec.nd.edu/courses/se2017 Department of Computer Science and Engineering Canonical Form Canonical form is a practice that conforms

More information

The Java Type System (continued)

The Java Type System (continued) Object-Oriented Design Lecture 5 CSU 370 Fall 2007 (Pucella) Friday, Sep 21, 2007 The Java Type System (continued) The Object Class All classes subclass the Object class. (By default, this is the superclass

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

CSE 331 Software Design & Implementation

CSE 331 Software Design & Implementation CSE 331 Software Design & Implementation Kevin Zatloukal Summer 2017 Identity, equals, and hashcode (Based on slides by Mike Ernst, Dan Grossman, David Notkin, Hal Perkins, Zach Tatlock) Overview Notions

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

CMSC131. Introduction to your Introduction to Java. Why Java?

CMSC131. Introduction to your Introduction to Java. Why Java? CMSC131 Introduction to your Introduction to Java Why Java? It s a popular language in both industry and introductory programming courses. It makes use of programming structures and techniques that can

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

Collections Questions

Collections Questions Collections Questions https://www.journaldev.com/1330/java-collections-interview-questions-and-answers https://www.baeldung.com/java-collections-interview-questions https://www.javatpoint.com/java-collections-interview-questions

More information

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018 Java + OOP CSC207 Winter 2018 1 Why OOP? Modularity: code can be written and maintained separately, and easily passed around the system Information-hiding: internal representation hidden from the outside

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

Fall 2017 Mentoring 9: October 23, Min-Heapify This. Level order, bubbling up. Level order, bubbling down. Reverse level order, bubbling up

Fall 2017 Mentoring 9: October 23, Min-Heapify This. Level order, bubbling up. Level order, bubbling down. Reverse level order, bubbling up CSM B Heaps & Hashing Fall 0 Mentoring : October 3, 0 Min-Heapify This. In general, there are 4 ways to heapify. Which ways actually work? Level order, bubbling up Level order, bubbling down Reverse level

More information

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic BIT 3383 Java Programming Sem 1 Session 2011/12 Chapter 2 JAVA basic Objective: After this lesson, you should be able to: declare, initialize and use variables according to Java programming language guidelines

More information

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 21 March 17, 2014 Connec@ng OCaml to Java Announcements No Weirich OH today - > Wed 1-3PM instead Read Chapters 19-22 of the lecture notes HW07 available

More information

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types

More information

Lecture 2: Intro to Java

Lecture 2: Intro to Java Why Java? Lecture 2: Intro to Java Java features. Widely available. Widely used. Variety of automatic checks for mistakes in programs. Embraces full set of modern abstractions. 2 Why Java? Why Java? Java

More information

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp DM550 / DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ OBJECT-ORIENTED PROGRAMMING IN JAVA 2 Programming

More information

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char Review Primitive Data Types & Variables int, long float, double boolean char String Mathematical operators: + - * / % Comparison: < > = == 1 1.3 Conditionals and Loops Introduction to Programming in

More information

Principles of Software Construction: Objects, Design and Concurrency. Inheritance, type-checking, and method dispatch. toad

Principles of Software Construction: Objects, Design and Concurrency. Inheritance, type-checking, and method dispatch. toad Principles of Software Construction: Objects, Design and Concurrency 15-214 toad Inheritance, type-checking, and method dispatch Fall 2013 Jonathan Aldrich Charlie Garrod School of Computer Science 2012-13

More information

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass? 1. Overriding Methods A subclass can modify behavior inherited from a parent class. A subclass can create a method with different functionality than the parent s method but with the same: Name Return type

More information

Collec&ons Framework Enhancements in Java 9

Collec&ons Framework Enhancements in Java 9 Collec>ons Refueled Collec&ons Framework Enhancements in Java 9 Stuart Marks Core Libraries Java PlaIorm Group, Oracle @stuartmarks Collec>ons Refueled Brief History of Collec>ons Java 8 Collec>ons Enhancements

More information

Java Magistère BFA

Java Magistère BFA Java 101 - Magistère BFA Lesson 3: Object Oriented Programming in Java Stéphane Airiau Université Paris-Dauphine Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 1 Goal : Thou Shalt

More information

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods COMP-202 Unit 2: Java Basics CONTENTS: Using Expressions and Variables Types Strings Methods Assignment 1 Assignment 1 posted on WebCt and course website. It is due May 18th st at 23:30 Worth 6% Part programming,

More information

CS 211: Methods, Memory, Equality

CS 211: Methods, Memory, Equality CS 211: Methods, Memory, Equality Chris Kauffman Week 2-1 So far... Comments Statements/Expressions Variable Types little types, what about Big types? Assignment Basic Output (Input?) Conditionals (if-else)

More information

Encapsula)on, cont d. Polymorphism, Inheritance part 1. COMP 401, Spring 2015 Lecture 7 1/29/2015

Encapsula)on, cont d. Polymorphism, Inheritance part 1. COMP 401, Spring 2015 Lecture 7 1/29/2015 Encapsula)on, cont d. Polymorphism, Inheritance part 1 COMP 401, Spring 2015 Lecture 7 1/29/2015 Encapsula)on In Prac)ce Part 2: Separate Exposed Behavior Define an interface for all exposed behavior In

More information

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8 Today... Java basics S. Bowers 1 of 8 Java main method (cont.) In Java, main looks like this: public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World!"); Q: How

More information

Recap. List Types. List Functionality. ListIterator. Adapter Design Pattern. Department of Computer Science 1

Recap. List Types. List Functionality. ListIterator. Adapter Design Pattern. Department of Computer Science 1 COMP209 Object Oriented Programming Container Classes 3 Mark Hall List Functionality Types List Iterator Adapter design pattern Adapting a LinkedList to a Stack/Queue Map Functionality Hashing Performance

More information