MIT OpenCourseWare http://ocw.mit.edu 6.005 Elements of Software Construction Fall 2008 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Introduction Rob Miller Fall 2008 © Robert Miller 2008 Why We Use Java in 6.005 safety ¾static typing catches errors before you even run (unlike Python) ¾strong typing and memory safety catch errors at run time (unlike C/C++) ubiquity ¾Java is widely used in industry and education libraries ¾Java has libraries and frameworks for many things tools ¾excellent, free tools exist for Java development (like Eclipse) it’s good to be multilingual ¾knowing two languages paves the way to learning more (which you should) why we regret using Java... ¾wordy, inconsistent, freighted with legacy baggage from older languages, no interpreter, no lambda expressions, no continuations, no tail recursion, ... © Robert Miller 2007 Today’s Topics getting up to speed with Java ¾note that programming experience is a prerequisite for 6.005 ¾we assume you’ve used Python ¾these initial lectures will show the Java way to do things you should already be able to do in Python (or some other language) what makes software “good” ¾whether it works isn’t the only consideration © Robert Miller 2007 Hailstone Sequences start with some positive integer n ¾if n is even, then next number is n/2¾if n is odd, then next number is 3n+1¾repeat these moves until you reach 1repeat 1examples 2, 1 7, 22, 11, 34, 17, 52, 26, 13, 40, ...? 3,10, 5, 16,8, 4, 2, 1 2n, 2n-1 , ..., 4, 2,1 4, 2,1 5,16, 8, 4, 2, 1 ¾why “hailstone”? because hailstones in clouds also bounce up and down hailstone ? chaotically before finally falling to the ground let’s explore this sequence ¾open question: does every positive integer n eventually reach 1? © Robert Miller 2007 1 Computing a Hailstone Sequence Java Python //hailstone sequence from n # hailstone sequence from n while (n != 1) { while n != 1: if (n % 2 == 0) { if n % 2 == 0: n = n /2; n = n /2 } else { else: n = 3 * n + 1; n = 3 * n + 1 } } © Robert Miller 2007 Computing a Hailstone Sequence intn = 3; System.out.println(n);if(n % 2 == 0) {n = n /2;} else {n = 3 * n + 1;while (n != 1) { declares the integer variable n prints a value to the console (useful for debugging) }}System.out.println(n);Java Syntax statement grouping ¾curly braces surround groups of statements ¾semicolons terminate statements ¾indentation is technically optional but essential for human readersindentation readers comments ¾//introduce comment lines¾/* ... */surround comment blockscontrol statements¾while and if require parentheses around their conditionsoperators¾mostly common with Python (+, -, *, /, <, >, <=, >=, ==)¾!= means “not equal to” ¾! means “not” , so n!=1 is the same as !(n == 1)¾the % operator computes remainder after division© Robert Miller 2007 Declarations and Types variables must be declared before being used¾a declaration includes the type of the variable¾two kinds of types, primitive and object¾primitive types includeprimitive include• int (integers up to +/-2 billion) • long (integers up to +/-263) • boolean (true or false) • double (floating-point numbers) • char (characters)¾objject types include yp • String (a sequence of characters, i.e. text) ¾you can define new object types (using classes) , but you can’t define new primitive types © Robert Miller 2007 © Robert Miller 2007 2 declares the integer variable n prints a value to the console (useful for debugging)int n = Static Typing static vs. dynamic¾static or compile-time means “known or done before the program runs”¾dynamic or run-time means “known or done while the program runs”Java has static typing ¾expressions are checked for type errors before the program runs ¾Eclipse does it while you’re writing, in factint n = 1;n = n + “2”; //type error – Eclipse won’t let you run the program¾PthPython hhasddynamiicttypiing – itit wouldldn’t ’t compllaiin abboutt n+ + “2” until it til reaches that line in the running program © Robert Miller 2007 Length of a Hailstone Sequence /* * Returns the number of moves of the hailstone sequence public static int hailstoneLength(int n) {int moves = 0;while (n != 1) {* needed to get from n to 1.type of value returned y the method by the method */if (isEven(n)) {n = n /2;} else {argument(s) of the method n = 3 * n + 1;}++moves;}return moves;}common operator, equivalent to moves = moves + 1 © Robert Miller 2007 A Complete Java Program public class Hailstone {public static void main(String[] args) {3; all Java code must be contained within a class a Java program starts by running the main method of a class while (n != 1) {System.out.println(n);if (n % 2 == 0) {n = n /2;} else {n = 3 * n + 1;}}System.out.println(n);}}we’ll talk about what public and static mean in the next lecture; for now, we’ll just use them on all methods © Robert Miller 2007 More Method Definitions /* * Returns true if and only if n is even.*/public static boolean isEven(int n) {return n % 2 == 0;}/* * Start of the program.*/public static void main(String[] args) { ... } ¾void means the method has no return type (so no return statement isrequired)¾String [ ] is an array of String objects (in this case, these strings are the arguments given to the program on the Unix/Windows/Mac command line) © Robert Miller 2007 3 all Java code must be contained within a class a Java program starts by running the main method of a class we’ll talk about what public and static mean in the next lecture; for now, we’ll just use them on all methods by the method argument(s) of the method common operator, equivalent to moves = moves + 1= * Recursive Method public static int hailstoneLength(int n) {if(n == 1) {return 0;} else if (isEven(n)) {return 1 + hailstoneLength(n/2); } else {return 1 + hailstoneLength(3*n + 1);}}recursive cases © Robert Miller 2007 Strings ¾a String is an object representing a sequence of characters • returning a List of integers would be better, but we need more machinery for Java Lists, so we’ll defer it¾stringgs can be concatenated usingg +• “8” + “4” Î “84” • String objects are immutable (never change), so concatenation creates a new string, it doesn’t change the original string objects ¾String objects have various methods String seq = “4,2,1”; seq.length() Î 5seq.chAharAt(0) (Î ‘4’seq.substr(0, 2) Î “4,”¾use Google to find the Java documentation for String• learn how to read the Java docs, and get familiar with them © Robert Miller 2007 Hailstone Sequence as a String /* * Returns the hailstone sequence from n to 1 * as a comma-separated string. * e.g. if n=5, then returns "5,16,8,4,2,1". */public static String hailstoneSequence(int n) { ... } © Robert Miller 2007 Hailstone Sequence as a String /* * Returns the hailstone sequence from n to 1* as a comma-separated string. * e.g. if n=5, then returns "5,16,8,4,2,1".*//public static String hailstoneSequence(int n) {String seq = n;String seq = String.valueOf(n);Type error! Java requires you to convert the integer into a String object. This is a compile‐time error. while (n != 1) {if (isEven(n)) {n = n /2;} else {n=3*}return seq;}n 3 n+1;}seq += common shorthand for s = s + “,” + n But the + operator converts numbers to strings automatically "," + n;© Robert Miller 2007 4 recursive cases b Type error! Java requires you to convert the integer into a String object. This is a compile‐time error. But the + operator converts numbers to strings automatically common shorthand for s = s + “,” + n base case= //sets a value Wha this Hailstone Sequence as an Array /** * Returns the hailstone sequence starting from n as an * array of integers, e.g. hailstoneArray(8) returns * the length-4 array [8,4,2,1].*//public static int[] hailstoneArray(int n) {...} © Robert Miller 2007 Hailstone Sequence as an Array /** * Returns the hailstone sequence starting from n as an* array of integers, e.g. hailstoneArray(8) returns * the length-4 array [8,4,2,1].*//public static int[] hailstoneArray(int n) {int[] array = new int[hailstoneLength(n)+1];int i = 0; while (n != 1) {array[i] = n; ++i; if (isEven(n)) {n=n n/2; } else { n = 3 * n + 1; } } t happens if you omit pp y “+1”? The array is too short, and Java produces a runtime error when you try to write the last number. array[i] = n;return array; } © Robert Miller 2007 Arrays array is a fixed-length sequence of values ¾base type of an array can be any type (primitive, object, another array type) int[] intArray; char[] charArray;String[] stringArray;double[][] matrix; //array of arrays of floating-point numbers¾fresh arrays are created with new keywordintArray = new int[5]; //makes array of 5 integers¾operations on an arrayintArray[y[0]] = 200;;intArray[0] Î 200 //gets a valueintArray.length Î 5 //gets array’s length¾unlike a String, an array’s elements can be changed¾but once created, an array’s length cannot be changed• so it’s not like a Python list – a Java array can’t grow or shrink © Robert Miller 2007 Maximum Value of an Array /** * Returns the maximum value of an array of * positive integers. * Returns 0 if the array is empty.*/public static int maxValue(int[] array) {intmax = 0;for (int i = 0; i < array.length; ++i) {if (array[i] > max) max = array[i];}return max;} © Robert Miller 2007 5 What happens if you omit this “+1”? The array is too short, and Java produces a runtime error when you try to write the last number. The for loop is commonly used for ierating through a collection iterating through a collection. for (init; test; update) {... } is roughly equivalent to init; while (test) { ... ; update }What Makes “Good” Software easy to understand ¾well chosen, descriptive names¾clear, accurate documentation¾indentationindentationready for change ¾nonredundant: complex code or important design decisions appear in only one place ¾“decoupled”: changeable parts are isolated from each other safe from bugs ¾static typing helps find bugs before runstatic you run¾testable in small parts¾no hidden assumptions waiting to trap you or another programmer later© Robert Miller 2007 Summary basic Java ¾control statements, expressions, operators ¾types and declarations ¾methodsmethods ¾strings ¾arrays properties of good software ¾easy to understand¾ready for change¾safe from bugssafe bugsA Larger View of Good Software correct ¾gets the right answers economical ¾runs ffast, uses miiniimall resources,ddoesn’’t cost muchh to prodduce dependable ¾safe from bugs maintainable ¾easy to understand and ready for change usable ¾has an effective user interface secure ¾safe from malicious attacks ... all these properties matter in practice ¾sometimes supporting each other, sometimes in conflict© Robert Miller 2007 About 6.005 lecturers ¾Daniel Jackson and Rob Miller teaching assistants ¾Hld C MGld E kK Cl Si KYHarold Cooper, Max Goldman,Eunsuk Kang, Clayton Sims,KuatYessenov lab assistants ¾TBD © Robert Miller 2007 © Robert Miller 2007 6 • Objectives what you should expect to get out of this course fundamental programming skills ¾how to specify, design, implement and test a program¾proficiency in Java and use of Java APIs¾use of standard development tools (Eclipse, SVN, JUnit)engineering sensibilities ¾capturing the essence of a problem¾inventing powerful abstractions¾appreciating the value of simplicity¾awareness of risks and fallibilitiescultural literacy ¾familiarity with a variety of technologies (http, postscript, sockets, etc) © Robert Miller 2007 Your Responsibilities assignments¾three 1-week explorations• writing a program we’ll use as a lecture example¾three 2 week problem 2-sets • both written and programming components¾three 2-week projects• in rotating teams of 3 people¾three 3-hour project labs, one for each project• project labs prepare you to get started on the project meetings ¾two lectures each week (Mon,Wed, sometimes Fri) ¾one recitation each week ¾project meetings with your team members and teaching staff • lecture time will often be made available for these meetings © Robert Miller 2007 Intellectual Structure three paradigms ¾state machine programming¾symbolic programming¾object based programming object-pervasive themes ¾models and abstractions¾interfaces and decoupling¾analysis with invariantsincremental approach ¾concepts introduced as needed ¾deepening sophistication as ideas are revisited © Robert Miller 2007 Grading Policy collaboration ¾projects in teams of 3: must have different teams for each project ¾problem sets and explorations are done individually discussion permitted but writing or code may not be shared use of available resources ¾can use publicly available code, designs, specs ¾cannot reuse work done in 6.005 by another student (in this or past term) ¾cannot make your work available to other 6.005 students grade breakdown ¾ j 40%projectts 40%¾problem sets 30%¾explorations 20%¾participation 10%© Robert Miller 2007 7 What You Should Do today ¾sign up for a recitation on the 6.005 web site tomorrow ¾ h i bidgo to the reciitation you’’ve been assigned to Friday ¾read Lab 1 before coming to lab¾go to your assigned lab location for Lab 1© Robert Miller 2007 8